问:
use powershell to add Edge Extension
I have a .CRX file  (ex: lajjpilliikppcbaghjehndpfdiiphbe_main.crx) that I would like to manually load onto an Edge extension...   Powershell is preferable tool for me as a silent installer.  I can manually do this by dragging the file onto the Edge Extension menu screen, but I can't expect users to do this, and need to have this on command script during signon to the system.

Articles I've found thus far seem to point to adding Registry values to HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Edge\Extensions.  However adding the key did not trigger Edge to recognize the package.

Any suggestions are appreciated.. Rob...

答:
If you want to distribute an extension through local file path, it's impossible. According to this doc, you can know that Windows and Mac installs must come from Chrome Web Store, and install external extensions through local crx files are not allowed. Edge is based on chromium so it's the same. That's for security reasons.

If the extension has been published to Microsoft Edge Add-ons website, you can distribute the extension using registry according to this doc. For example, if I want to add this extension to Edge silently, first I need to find the extension id in the end of the page url. Then edit the registry setting like below:

Title: use powershell to add Edge Extension


来源: stackexchange

问:
MySQL Incorrect datetime value: '0000-00-00 00:00:00'
I've recently taken over an old project that was created 10 years ago. It uses MySQL 5.1.

Among other things, I need to change the default character set from latin1 to utf8.

As an example, I have tables such as this:

```<code>  CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `first_name` varchar(45) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    `last_name` varchar(45) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    `username` varchar(127) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
    `email` varchar(127) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
    `pass` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
    `active` char(1) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'Y',
    `created` datetime NOT NULL,
    `last_login` datetime DEFAULT NULL,
    `author` varchar(1) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT 'N',
    `locked_at` datetime DEFAULT NULL,
    `created_at` datetime DEFAULT NULL,
    `updated_at` datetime DEFAULT NULL,
    `ripple_token` varchar(36) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    `ripple_token_expires` datetime DEFAULT '2014-10-31 08:03:55',
    `authentication_token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `index_users_on_reset_password_token` (`reset_password_token`),
    UNIQUE KEY `index_users_on_confirmation_token` (`confirmation_token`),
    UNIQUE KEY `index_users_on_unlock_token` (`unlock_token`),
    KEY `users_active` (`active`),
    KEY `users_username` (`username`),
    KEY `index_users_on_email` (`email`)
  ) ENGINE=InnoDB AUTO_INCREMENT=1677 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC
</code>```

I set up my own Mac to work on this. Without thinking too much about it, I ran "brew install mysql" which installed MySQL 5.7. So I have some version conflicts.

I downloaded a copy of this database and imported it.

If I try to run a query like this:

```<code>  ALTER TABLE users MODIFY first_name varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci    NOT NULL
</code>```

I get this error:

```<code>  ERROR 1292 (22007): Incorrect datetime value: '0000-00-00 00:00:00' for column 'created' at row 1
</code>```

I thought I could fix this with:

```<code>  ALTER TABLE users MODIFY created datetime  NULL DEFAULT '1970-01-01 00:00:00';
  Query OK, 0 rows affected (0.06 sec)
  Records: 0  Duplicates: 0  Warnings: 0
</code>```

but I get:

```<code>  ALTER TABLE users MODIFY first_name varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci    NOT NULL ;
  ERROR 1292 (22007): Incorrect datetime value: '0000-00-00 00:00:00' for column 'created' at row 1
</code>```

Do I have to update every value?

答:
This issue is happening because MYSQL 5.7 introduced default modes like

```<code>SELECT @@GLOBAL.sql_mode global, @@SESSION.sql_mode session;
=> ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
</code>```

Among the default modes, there is a mode NO_ZERO_DATE which prevents you to put the value  0000-00-00 00:00:00 in the datetime column.

Temporary fix would be removing the mode NO_ZERO_DATE/NO_ZERO_IN_DATE from the default modes and keeping the other modes as it is.

```<code>SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
</code>```

But once you restart your mysql server, all your temporary settings will be gone and the default modes will be enabled again. To fix this on restart, change the default modes in my.cnf file on your machine.

Refer the docs :- https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#:~:text=To%20set%20the%20SQL%20mode,ini%20(Windows).

My personal opinion :- The right developmental practice would be putting a right datetime value in the column instead of 0000-00-00 00:00:00. So that you don't have to worry about the SQL modes.

ContentLicense: CC BY-SA 3.0

Body:
I've recently taken over an old project that was created 10 years ago. It uses MySQL 5.1.

Among other things, I need to change the default character set from latin1 to utf8.

As an example, I have tables such as this:

  CREATE TABLE `users` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `first_name` varchar(45) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    `last_name` varchar(45) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    `username` varchar(127) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
    `email` varchar(127) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
    `pass` varchar(20) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
    `active` char(1) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL DEFAULT 'Y',
    `created` datetime NOT NULL,
    `last_login` datetime DEFAULT NULL,
    `author` varchar(1) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT 'N',
    `locked_at` datetime DEFAULT NULL,
    `created_at` datetime DEFAULT NULL,
    `updated_at` datetime DEFAULT NULL,
    `ripple_token` varchar(36) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    `ripple_token_expires` datetime DEFAULT '2014-10-31 08:03:55',
    `authentication_token` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `index_users_on_reset_password_token` (`reset_password_token`),
    UNIQUE KEY `index_users_on_confirmation_token` (`confirmation_token`),
    UNIQUE KEY `index_users_on_unlock_token` (`unlock_token`),
    KEY `users_active` (`active`),
    KEY `users_username` (`username`),
    KEY `index_users_on_email` (`email`)
  ) ENGINE=InnoDB AUTO_INCREMENT=1677 DEFAULT CHARSET=utf8 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC

I set up my own Mac to work on this. Without thinking too much about it, I ran "brew install mysql" which installed MySQL 5.7. So I have some version conflicts.

I downloaded a copy of this database and imported it.

If I try to run a query like this:

  ALTER TABLE users MODIFY first_name varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci    NOT NULL

I get this error:

  ERROR 1292 (22007): Incorrect datetime value: '0000-00-00 00:00:00' for column 'created' at row 1

I thought I could fix this with:

  ALTER TABLE users MODIFY created datetime  NULL DEFAULT '1970-01-01 00:00:00';
  Query OK, 0 rows affected (0.06 sec)
  Records: 0  Duplicates: 0  Warnings: 0

but I get:

  ALTER TABLE users MODIFY first_name varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci    NOT NULL ;
  ERROR 1292 (22007): Incorrect datetime value: '0000-00-00 00:00:00' for column 'created' at row 1

Do I have to update every value?

Body:
This issue is happening because MYSQL 5.7 introduced default modes like

SELECT @@GLOBAL.sql_mode global, @@SESSION.sql_mode session;
=> ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION | ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

Among the default modes, there is a mode NO_ZERO_DATE which prevents you to put the value  0000-00-00 00:00:00 in the datetime column.

Temporary fix would be removing the mode NO_ZERO_DATE/NO_ZERO_IN_DATE from the default modes and keeping the other modes as it is.

SET GLOBAL sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

But once you restart your mysql server, all your temporary settings will be gone and the default modes will be enabled again. To fix this on restart, change the default modes in my.cnf file on your machine.

Refer the docs :- https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#:~:text=To%20set%20the%20SQL%20mode,ini%20(Windows).

My personal opinion :- The right developmental practice would be putting a right datetime value in the column instead of 0000-00-00 00:00:00. So that you don't have to worry about the SQL modes.

ContentLicense: CC BY-SA 4.0


问:
ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
Since im new in firebase, im having trouble with duplicated name already exists, and i need your help.

```<code>E/flutter (21802): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
E/flutter (21802): #0      MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:111
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #1      Firebase.initializeApp
package:firebase_core/src/firebase.dart:41
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #2      main
package:flutterbuyandsell/main.dart:47
E/flutter (21802): <asynchronous suspension>
E/flutter (21802):
</code>```

…/method_channel/method_channel_firebase.dart:111

package:firebase_core/src/firebase.dart:41

package:flutterbuyandsell/main.dart:47

答:
```<code>flutter clean
</code>```

and

```<code>flutter pub get
</code>```

executing these two commands consecutively solved my problem.

Body:
Since im new in firebase, im having trouble with duplicated name already exists, and i need your help.

E/flutter (21802): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/duplicate-app] A Firebase App named "[DEFAULT]" already exists
E/flutter (21802): #0      MethodChannelFirebase.initializeApp
package:firebase_core_platform_interface/…/method_channel/method_channel_firebase.dart:111
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #1      Firebase.initializeApp
package:firebase_core/src/firebase.dart:41
E/flutter (21802): <asynchronous suspension>
E/flutter (21802): #2      main
package:flutterbuyandsell/main.dart:47
E/flutter (21802): <asynchronous suspension>
E/flutter (21802):

…/method_channel/method_channel_firebase.dart:111

package:firebase_core/src/firebase.dart:41

package:flutterbuyandsell/main.dart:47

Body:
flutter clean

and

flutter pub get

executing these two commands consecutively solved my problem.


问:
jupyter lab could not bring up on windows when using question mark?
When using question mark, it brings up on windows by jupyter notebook but showing all  in cell by jupyter lab like below. I want lab could be like notebook.

答:
You said above, "I want lab to be like notebook", but I don't think you are going to get what you want. The only difference I can see is that in Lab, the output is directly under the cell and other cells can be underneath it and in notebook it is in a window at the bottom of all cells.  You can copy and paste the text in either one.  Maybe the question is how to get the 'pager' window on the bottom in lab similar to notebook.

Notebook

versus

Lab


问:
Extract number of the institutional holding that a stock has
I'm trying to extract the number of the institutional holding that a stock has.

For instance, here from Apple at the following link

https://finance.yahoo.com/quote/AAPL/holders?p=AAPL)

Extract a number

I would like to get the number 5,102 from:

```<code> "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}
</code>```

I think this is a tulip right?

Code

This is the code so far:

```<code>import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla/5.0'}

url = 'https://finance.yahoo.com/quote/AAPL/holders?p=AAPL'

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
</code>```

What I tried

I tried to use yfinance but I don't know how to make a loop to extract all the holders for each ticker. So I though would be more easy to do a web scraping for one and then looping for each stock.

答:
Thank you so much to all for the inspiration. As hc_dev mention, would be better to use the module of yfinance. Since yfinance gives you a pandas.core.frame, I transform it to a list, so I can grab what I wanted. So I think the following would solve the problem efficiently.

CODE

```<code>import yfinance as yf

ticker = input('Enter ticker:')
stock = yf.Ticker(ticker)
holders = stock.major_holders
holders_list = holders[0].to_list()
number = holders_list[3]
print('Number of institutionals:', number)
</code>```

Body:
I'm trying to extract the number of the institutional holding that a stock has.

For instance, here from Apple at the following link

https://finance.yahoo.com/quote/AAPL/holders?p=AAPL)

Extract a number

I would like to get the number 5,102 from:

 "institutionsCount": {
    "raw": 5102,
    "fmt": "5.1k",
    "longFmt": "5,102"
}

I think this is a tulip right?

Code

This is the code so far:

import requests
from bs4 import BeautifulSoup

headers = {'user-agent': 'Mozilla/5.0'}

url = 'https://finance.yahoo.com/quote/AAPL/holders?p=AAPL'

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')

What I tried

I tried to use yfinance but I don't know how to make a loop to extract all the holders for each ticker. So I though would be more easy to do a web scraping for one and then looping for each stock.

Body:
Thank you so much to all for the inspiration. As hc_dev mention, would be better to use the module of yfinance. Since yfinance gives you a pandas.core.frame, I transform it to a list, so I can grab what I wanted. So I think the following would solve the problem efficiently.

CODE

import yfinance as yf

ticker = input('Enter ticker:')
stock = yf.Ticker(ticker)
holders = stock.major_holders
holders_list = holders[0].to_list()
number = holders_list[3]
print('Number of institutionals:', number)


问:
rbenv: version `2.0.0' is not installed
I'm trying to install the Gemfile contents using Bundle install but getting the error

```<code>rbenv: version `2.0.0' is not installed
</code>```

The version of ruby installed in my system is:

```<code>ruby 2.1.2p95 (2014-05-08 revision 45877) [i686-linux]
</code>```

and rbenv

```<code> 2.1.2 (set by /home/jay/.rbenv/version)
 2.1.3
</code>```

The Gemfile requires ruby "2.0.0". Can any one tell how to install the required version without affecting the existing ones.

答: You must change the ruby's version in .ruby-version file and in Gemfile

Title: rbenv: version `2.0.0' is not installed

Body:
I'm trying to install the Gemfile contents using Bundle install but getting the error

rbenv: version `2.0.0' is not installed

The version of ruby installed in my system is:

ruby 2.1.2p95 (2014-05-08 revision 45877) [i686-linux]

and rbenv

 2.1.2 (set by /home/jay/.rbenv/version)
 2.1.3

The Gemfile requires ruby "2.0.0". Can any one tell how to install the required version without affecting the existing ones.


问:
heredoc for Windows batch?
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

```<code>cat <<EOF > out.txt
bla
bla
..
EOF
</code>```

The idea is to create a customized file from a template file..

答:
@jeb

```<code>setlocal EnableDelayedExpansion
set LF=^

REM Two empty lines are required
</code>```

another variant:

```<code>@echo off

:)
setlocal enabledelayedexpansion
>nul,(pause&set /p LF=&pause&set /p LF=)<%0
set LF=!LF:~0,1!

echo 1!LF!2!LF!3

pause
</code>```

ContentLicense: CC BY-SA 2.5

Title: heredoc for Windows batch?

Body:
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

cat <<EOF > out.txt
bla
bla
..
EOF

The idea is to create a customized file from a template file..

Body:
@jeb

setlocal EnableDelayedExpansion
set LF=^

REM Two empty lines are required

another variant:

@echo off

:)
setlocal enabledelayedexpansion
>nul,(pause&set /p LF=&pause&set /p LF=)<%0
set LF=!LF:~0,1!

echo 1!LF!2!LF!3

pause


问:
Attempt to index nil with ‘WaitForChild’?
error

Code

I am in roblox studio and i got this when i was making an animation for my game it includes a humanoid i am attempting to animate. There are two animations the first one works but the other doesn't i get this error. when i place the humanoid down the animation  does not start however the first one does as intended but the other one should start whenever the humanoid attacks. Please help i will appreciate anything

(code)

local function setAnimation(object, animName)

local humanoid = object:WaitForChild("Humanoid")

local animationsFolder = object:WaitForChild("Animations")

(error)

Attempt to index nil with ‘WaitForChild'

答: object is a nil value. Hence you may not index it. Find out why it is nil and fix that. So you need to go to your setAnimation call and ensure that the first argument is actually an Instance, not a nil value. So you either call setAnimation() without any arguments or you provide some uninitialized variable as the first argument.


问:
Helm Chart - Process File result with multiple lines
I have a ConfigMap where I am including a file in its data attribute and I need to replace several strings from it. But I'm not able to divide it (the "replaces") into several lines so that it doesn't get a giant line. How can I do this?

This is what I don't want:

```<code>apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 | replace "var1_enabled" (toString .Values.myVar1.enabled) | replace "var2_enabled" (toString .Values.myVar2.enabled) }}
</code>```

This is what I'm trying to do:

```<code>apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 |
  replace "var1_enabled" (toString .Values.myVar1.enabled) |
  replace "var2_enabled" (toString .Values.myVar2.enabled) }}
</code>```

What is the right syntax to do this?

答:
What is the right syntax to do this?

It is well described in this documentation. There are many different ways to achieve your goal, it all depends on the specific situation. You have everything in that documentation. Look at the example most connected to your current situation:

When writing templates, you may find yourself wanting to inject the contents of a file into the template. As we saw in previous chapters, there are two ways of doing this:

Use  {{ .Files.Get "FILENAME" }}  to get the contents of a file in the chart.

Use  {{ include "TEMPLATE" . }}  to render a template and then place its contents into the chart.

When inserting files into YAML, it's good to understand the multi-line rules above. Often times, the easiest way to insert a static file is to do something like this:

myfile: |
{{ .Files.Get "myfile.txt" | indent 2 }}

```

Note how we do the indentation above:  indent 2  tells the template engine to indent every line in "myfile.txt" with two spaces. Note that we do not indent that template line. That's because if we did, the file content of the first line would be indented twice.

For more look also at the similar problem on github and question on stack.

EDIT:

But I'm not able to divide it (the "replaces") into several lines so that it doesn't get a giant line. How can I do this?

It is impossible to achieve. Go Template doesn't support newlines. For more see this question. and this documentation

The input text for a template is UTF-8-encoded text in any format. "Actions"--data evaluations or control structures--are delimited by "{{" and "}}"; all text outside actions is copied to the output unchanged. Except for raw strings, actions may not span newlines, although comments can.

Body:
I have a ConfigMap where I am including a file in its data attribute and I need to replace several strings from it. But I'm not able to divide it (the "replaces") into several lines so that it doesn't get a giant line. How can I do this?

This is what I don't want:

apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 | replace "var1_enabled" (toString .Values.myVar1.enabled) | replace "var2_enabled" (toString .Values.myVar2.enabled) }}

This is what I'm trying to do:

apiVersion: v1
kind: ConfigMap
data:
{{ (.Files.Glob "myFolder/*.json").AsConfig | indent 2 |
  replace "var1_enabled" (toString .Values.myVar1.enabled) |
  replace "var2_enabled" (toString .Values.myVar2.enabled) }}

What is the right syntax to do this?

Body:
What is the right syntax to do this?

It is well described in this documentation. There are many different ways to achieve your goal, it all depends on the specific situation. You have everything in that documentation. Look at the example most connected to your current situation:

When writing templates, you may find yourself wanting to inject the contents of a file into the template. As we saw in previous chapters, there are two ways of doing this:

Use  {{ .Files.Get "FILENAME" }}  to get the contents of a file in the chart.

Use  {{ include "TEMPLATE" . }}  to render a template and then place its contents into the chart.

When inserting files into YAML, it's good to understand the multi-line rules above. Often times, the easiest way to insert a static file is to do something like this:

myfile: |
{{ .Files.Get "myfile.txt" | indent 2 }}

Note how we do the indentation above:  indent 2  tells the template engine to indent every line in "myfile.txt" with two spaces. Note that we do not indent that template line. That's because if we did, the file content of the first line would be indented twice.

For more look also at the similar problem on github and question on stack.

EDIT:

But I'm not able to divide it (the "replaces") into several lines so that it doesn't get a giant line. How can I do this?

It is impossible to achieve. Go Template doesn't support newlines. For more see this question. and this documentation

The input text for a template is UTF-8-encoded text in any format. "Actions"--data evaluations or control structures--are delimited by "{{" and "}}"; all text outside actions is copied to the output unchanged. Except for raw strings, actions may not span newlines, although comments can.


问:
How to pass row of dataframe to a function in spark scala
I want to take the input of each row of a dataframe and retun output as a map.I have written a below methood

```<code>def getV(str:String,colValues:Map[String,Any]):Any={
    var s= colValues.get("str") match {
      case Some(value) =>value
      case None =>None
    }
    return s
  }
  def setV(key:String,value:String,colValues:scala.collection.mutable.Map[String,Any]):Unit={
    colValues(key)=value
  }

def returnNotEmptyCols_map(inputRow: Row): collection.mutable.Map[String,Any] = {
    implicit val formats = Serialization.formats(NoTypeHints)
    var colValues = inputRow.getValuesMap[Any](inputRow.schema.fieldNames)
    var mutMap = collection.mutable.Map(colValues.toSeq: _*)
    //Write my operations here------
    //print(getV("number",colValues))
    //setV("hey","there",mutMap)

    mutMap
    //return df

  }
</code>```

However the problem I am facing is that I am calling this function from a dataframe using udf and hence the resulting output is in a column format

```<code>spark.udf.register("myFilterFunction", returnNotEmptyCols _)
    import spark.implicits._
    val df = Seq(
      (12, "bat"),
      (13, "mouse"),
      (14, "horse")
    ).toDF("number", "word")
    var dr=df.rdd.collect
    val newDF=df.withColumn("newcl",callUDF("myFilterFunction",struct(df.columns.map(df(_)) : _*)))

</code>```

Is there any way where I can pass the row as an input to the methood returnNotEmptyCols_map
function and get oupput as a map(not as a column of a dataframe).
There's way we can do this using below link
function to each row of Spark Dataframe

But it is also a udf and resulting output in column format.

答:
The purpose of UDF is to continue working with DataFrame. If you don't need DataFrame, you can run map on underlying rdd with your function as a parameter and get  rdd of the type your function returns.

val rdd = df.rdd.map(returnNotEmptyCols_map)

It doesn't work with Dataset.map, because of Any

Then you can do rdd.collect or whatever

Body:
I want to take the input of each row of a dataframe and retun output as a map.I have written a below methood

def getV(str:String,colValues:Map[String,Any]):Any={
    var s= colValues.get("str") match {
      case Some(value) =>value
      case None =>None
    }
    return s
  }
  def setV(key:String,value:String,colValues:scala.collection.mutable.Map[String,Any]):Unit={
    colValues(key)=value
  }

def returnNotEmptyCols_map(inputRow: Row): collection.mutable.Map[String,Any] = {
    implicit val formats = Serialization.formats(NoTypeHints)
    var colValues = inputRow.getValuesMap[Any](inputRow.schema.fieldNames)
    var mutMap = collection.mutable.Map(colValues.toSeq: _*)
    //Write my operations here------
    //print(getV("number",colValues))
    //setV("hey","there",mutMap)

    mutMap
    //return df

  }

However the problem I am facing is that I am calling this function from a dataframe using udf and hence the resulting output is in a column format

spark.udf.register("myFilterFunction", returnNotEmptyCols _)
    import spark.implicits._
    val df = Seq(
      (12, "bat"),
      (13, "mouse"),
      (14, "horse")
    ).toDF("number", "word")
    var dr=df.rdd.collect
    val newDF=df.withColumn("newcl",callUDF("myFilterFunction",struct(df.columns.map(df(_)) : _*)))

Is there any way where I can pass the row as an input to the methood returnNotEmptyCols_map
function and get oupput as a map(not as a column of a dataframe).
There's way we can do this using below link
function to each row of Spark Dataframe

But it is also a udf and resulting output in column format.


问:
Inserting increment for each unique value in sql
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

```<code> widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d
</code>```

I would like to have another table that has each unique value incrementally numbered... Like so:

```<code>widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4
</code>```

I'm not sure how this would be done with an insert statement?

答:
My MySQL syntax is not very good, but assuming you've created your new table above, wouldn't something like this work?</p>

```<code>set @i = 0;

create temporary table t_widget_id
as
    select distinct widgets, @i:=@i+1 as widget_id from widgets

insert into widget_new
    select widgets.widgets,
            t_widget_id.widget_id
        from
            widgets inner join
                t_widget_id
                    on widgets.widgets = t_widget_id.widgets

drop table t_widget_id
</code>```

OwnerDisplayName: Chris

Body:
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

 widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d

I would like to have another table that has each unique value incrementally numbered... Like so:

widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4

I'm not sure how this would be done with an insert statement?

Body:
My MySQL syntax is not very good, but assuming you've created your new table above, wouldn't something like this work?

set @i = 0;

create temporary table t_widget_id
as
    select distinct widgets, @i:=@i+1 as widget_id from widgets

insert into widget_new
    select widgets.widgets,
            t_widget_id.widget_id
        from
            widgets inner join
                t_widget_id
                    on widgets.widgets = t_widget_id.widgets

drop table t_widget_id

OwnerDisplayName: Peter Meyer


问:
SQL Query to copy tables between servers with auto insert / update depending on Identity column
Let's say I have 2 servers, and one identical table per server. In each tables, I have identity increment on (by 1 if u ask), and there is 'time' column to note when was the record updated/inserted.

so kinda like this:

```<code>ID    Content     Time
1     banana      2011-01-01 09:59:23.000
2     apple       2011-01-02 12:41:01.000
3     pear        2011-04-05 04:05:44.000
</code>```

I want to copy (insert/update) all the contents from one table to another periodically with this requirements:

a. copy (insert/update) only before certain MONTH. i.e before August 2011. this is easy though.

b. insert only if records is really new (maybe if the ID isn't exist?)

c. update if you find the 'Time' column is newer (basically that means there is an update at that record) than the last performed copy (I save the date/time of last copy too)

I could do all that by building a program and check it record by record, but with hundred thousands records, it would be pretty slow.

Could it be done using just query?

Btw I'm using this query to copy between servers and I'm using SQL Server 2005

```<code>INSERT OPENQUERY(TESTSERVER, 'SELECT * FROM Table1')
SELECT * FROM Table1
</code>```

thx for da help :)

答:
My strategy in a situation like this is:

first do an outer join and determine the state of the data into a temp table
e.g.

```<code>   #temp
   id     state
   1      update
   2      copy
   3      copy
   4      insert
</code>```

Then run n statements joining the three tables together, one for each of the states. Sometimes you can eliminate the multiple statements  by entering empty rows in the target with the correct keys. Then you only need to do a more complex update/copy.

However since these are cross server - I'd suggest the following strategy - copy the source table over entirely to the other server, and then do the above on the other server.

Only after this do I do performance analysis to optimise if needed.

Body:
Let's say I have 2 servers, and one identical table per server. In each tables, I have identity increment on (by 1 if u ask), and there is 'time' column to note when was the record updated/inserted.

so kinda like this:

ID    Content     Time
1     banana      2011-01-01 09:59:23.000
2     apple       2011-01-02 12:41:01.000
3     pear        2011-04-05 04:05:44.000

I want to copy (insert/update) all the contents from one table to another periodically with this requirements:

a. copy (insert/update) only before certain MONTH. i.e before August 2011. this is easy though.

b. insert only if records is really new (maybe if the ID isn't exist?)

c. update if you find the 'Time' column is newer (basically that means there is an update at that record) than the last performed copy (I save the date/time of last copy too)

I could do all that by building a program and check it record by record, but with hundred thousands records, it would be pretty slow.

Could it be done using just query?

Btw I'm using this query to copy between servers and I'm using SQL Server 2005

INSERT OPENQUERY(TESTSERVER, 'SELECT * FROM Table1')
SELECT * FROM Table1

thx for da help :)

Body:
My strategy in a situation like this is:

first do an outer join and determine the state of the data into a temp table
e.g.

   #temp
   id     state
   1      update
   2      copy
   3      copy
   4      insert

Then run n statements joining the three tables together, one for each of the states. Sometimes you can eliminate the multiple statements  by entering empty rows in the target with the correct keys. Then you only need to do a more complex update/copy.

However since these are cross server - I'd suggest the following strategy - copy the source table over entirely to the other server, and then do the above on the other server.

Only after this do I do performance analysis to optimise if needed.


问:
How to fix this problem? Login if statement not working
This is my views.py

```<code>def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})
</code>```

And this is my login page:

```<code><div class="container">
<div class="jumbotron">
    <h2 class="text-dark"> Login </h2>
    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
        <label for="username"> Username </label>
        <input type="text" name="username" placeholder=" Write Your UserName Here"> <br></br>

        <label for="password"> Password </label>
        <input type="text" name="password" placeholder=" Write Your Password Here"> <br></br>

        <input  type="submit" class="btn btn-dark" name="savebutton" value="login">
    </form>
</div>
</code>```

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.

答: That's because you are using ModelBackend Authentication which is default for Django. This backend checks if user can authenticate by checking if user is_active. Your user is not active, so it can't authenticate, so your authenticate returns None instead of User. If you want to know more about this authentication method check it django.contrib.auth.backends.ModelBackend.

Body:
This is my views.py

def user_login(request):
   if request.method == "POST":
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('index'))
        else:
            return HttpResponse("Your account is Inactive.")
    else:
        return HttpResponse("Invalid User Credentials Provided!!!!")
else:
    return render(request, "MyTestApp/login.html", {})

And this is my login page:

 Login

    <form method="post" action="{ url 'MyTestApp:user_login '}">
        {%csrf_token%}
         Username
        <input type="text" name="username" placeholder=" Write Your UserName Here">

         Password
        <input type="text" name="password" placeholder=" Write Your Password Here">

        <input  type="submit" class="btn btn-dark" name="savebutton" value="login">
    </form>

When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated.


问:
ERROR: (gcloud.builds.submit) interpreting cloudbuild.yaml as build config: .args: unused
This is my cloudbuild.yaml

```<code>steps:
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t','us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}','.']
images:
- 'us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}'
</code>```

and when i try to run this command

```<code>gcloud builds submit --config=cloudbuild.yaml --substitutions=_REPOSITORY="my-repo",_IMAGE="my-node-red"
</code>```

i get this error:

```<code>ERROR: (gcloud.builds.submit) interpreting cloudbuild.yaml as build config: .args: unused
</code>```

答:
The error is due to a wrong identation in your cloudbuild.yaml file. The correct identation is (mind the 2 spaces before args):

```<code>steps:
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t','us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}','.']
images:
- 'us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}'
</code>```

You can then submit the build successfully with the same command you mentioned:

```<code>gcloud builds submit --config=cloudbuild.yaml --substitutions=_REPOSITORY="my-repo",_IMAGE="my-node-red"
</code>```

Body:
This is my cloudbuild.yaml

steps:
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t','us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}','.']
images:
- 'us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}'

and when i try to run this command

gcloud builds submit --config=cloudbuild.yaml --substitutions=_REPOSITORY="my-repo",_IMAGE="my-node-red"

i get this error:

ERROR: (gcloud.builds.submit) interpreting cloudbuild.yaml as build config: .args: unused

Body:
The error is due to a wrong identation in your cloudbuild.yaml file. The correct identation is (mind the 2 spaces before args):

steps:
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t','us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}','.']
images:
- 'us-central1-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/${_IMAGE}'

You can then submit the build successfully with the same command you mentioned:

gcloud builds submit --config=cloudbuild.yaml --substitutions=_REPOSITORY="my-repo",_IMAGE="my-node-red"


问:
Starting WinAppDriver.exe programmatically
Before starting test execution, I have to manually start this WinAppDriver.exe.

I want to automate this task when I start executing my test cases it should start this exe and after finish it will close it.

I have tried in Java with below code but I'm not success:

```<code>Runtime runTime = Runtime.getRuntime();

String executablePath = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";

Process process = runTime.exec(executablePath);
</code>```

Note: I required to run it with 'Run As Administrator'

答:
The above answers are correct but if you want to run winapp driver on specific ports then in that case you will need to use this

```<code>   String command = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";
                List<String> commands = new ArrayList<String>();
                commands.add(command);
                commands.add("8888");
                ProcessBuilder builder = new ProcessBuilder(commands).inheritIO();
                Process p=builder.start();
                p.destroy();
</code>```

Here we can pass all parameters inside the list and pass this list object inside ProcessBuilder.

Default URL: http://127.0.0.1:4723

In our case URL:http://127.0.0.1:8888

Body:
Before starting test execution, I have to manually start this WinAppDriver.exe.

I want to automate this task when I start executing my test cases it should start this exe and after finish it will close it.

I have tried in Java with below code but I'm not success:

Runtime runTime = Runtime.getRuntime();

String executablePath = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";

Process process = runTime.exec(executablePath);

Note: I required to run it with 'Run As Administrator'

Body:
The above answers are correct but if you want to run winapp driver on specific ports then in that case you will need to use this

   String command = "C:\\Program Files (x86)\\Windows Application Driver\\WinAppDriver.exe";
                List<String> commands = new ArrayList<String>();
                commands.add(command);
                commands.add("8888");
                ProcessBuilder builder = new ProcessBuilder(commands).inheritIO();
                Process p=builder.start();
                p.destroy();

Here we can pass all parameters inside the list and pass this list object inside ProcessBuilder.

Default URL: http://127.0.0.1:4723

In our case URL:http://127.0.0.1:8888


问:
Stimulus nested (child) targets
Is it possible (and is it appropriate) to use nested/child targets of parent target?

For example i have “N+“ menu items, each item (wrapper) contain link and list.
I could add data-main-menu-target="menuItem" to each of parent items and then iterate over them in controller loop using this.menuItemTargets.forEach(...)

But what's the best practice to find menu-item-link and menu-item-list for each menu-item target on each loop iteration?

In general i could add targets also for those elements, e.g. menuItemLink & menuItemList, but how then i could select them from parent menuItem target, Is it possible to do something like menuItemTarget.find(this.this.menuListTarget)?

To visualise the structure is the following:

```<code>data-controller="main-menu"
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....
</code>```

How then select "menuLink" for certain "menuItem" target on each loop?

答:
Answer from another conversation,

A) For menuLink and menuList, you handle it by yourself: use CSS
classes, and then use normal selectors. So, once you've used the
menuItem target to find the menuItem you want, you would then do
menuItem.querySelector('.menu-link'). Not a Stimulus solution, but
it's pretty simple and it's nice to be able to "back out" and do
things manually if you need to.

B) I'm not sure what your overall Stimulus controller is meant to do,
but it's possible that there should be a menu-item controller that
lives on the menuItem target. Depending on what you're trying to
accomplish, that could replace the main-menu controller or, more
likely (because I'm assuming you are doing some "work" on the top
level main-menu where you want to be aware of all of the "items"), in
addition to the main-menu controller. With this setup, your main-menu
controller could loop over the menuItem targets and, in each one,
directly use its underlying controller instance - even calling methods
on it. This is not something I showed on the tutorial, but it's not an
uncommon pattern: you would expose the "controller instance" of the
"menu-item" controller on its element - e.g.
https://www.betterstimulus.... (the big difference in that example is
that both of the controllers are on the same element - so adjust
accordingly).

(c) weaverryan

Title: Stimulus nested (child) targets

Body:
Is it possible (and is it appropriate) to use nested/child targets of parent target?

For example i have “N+“ menu items, each item (wrapper) contain link and list.
I could add data-main-menu-target="menuItem" to each of parent items and then iterate over them in controller loop using this.menuItemTargets.forEach(...)

But what's the best practice to find menu-item-link and menu-item-list for each menu-item target on each loop iteration?

In general i could add targets also for those elements, e.g. menuItemLink & menuItemList, but how then i could select them from parent menuItem target, Is it possible to do something like menuItemTarget.find(this.this.menuListTarget)?

To visualise the structure is the following:

data-controller="main-menu"
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....

How then select "menuLink" for certain "menuItem" target on each loop?


问:
Create Pivot table for each column in Pandas df
I have a DataFrame where I have many columns (there is one dependent variable and many independent variables)

variable_id
dep_var
variable_1
variable_2

new
1
6
3

new
0
3
6

new
0
8
7

new
1
11
1

new
0
17
9

new
1
1
2

I want to create a Pivot table such as this:

```<code>pd.pivot_table(df,index=['variable_1'], columns=['dep_var'], values=['variable_id'],aggfunc='count')
</code>```

I want to create it for each column separatly (so I need to change index in pd.pivot_table)

I have written a sample code:

```<code>def pivot_table(df):
    df_columns = list(df)
    for column in df_columns:
        print("indexing by: ", column)
        print(pd.pivot_table(df,index=[column], columns=['dep_var'], values=['variable_id'],aggfunc='count'))
</code>```

but I want my result to be saved as pandas DataFrame

desired output:
how I want my output for each variable separately

答:
Use:</p>
```<code>def pivot_table(df):
    dfs = []
    for column in df:
        print("indexing by: ", column)
        df = pd.pivot_table(df,index=[column], values=['dep_var'])
        dfs.append(df)
    return dfs

</code>```

Body:
I have a DataFrame where I have many columns (there is one dependent variable and many independent variables)

variable_id
dep_var
variable_1
variable_2

new
1
6
3

new
0
3
6

new
0
8
7

new
1
11
1

new
0
17
9

new
1
1
2

I want to create a Pivot table such as this:

pd.pivot_table(df,index=['variable_1'], columns=['dep_var'], values=['variable_id'],aggfunc='count')

I want to create it for each column separatly (so I need to change index in pd.pivot_table)

I have written a sample code:

def pivot_table(df):
    df_columns = list(df)
    for column in df_columns:
        print("indexing by: ", column)
        print(pd.pivot_table(df,index=[column], columns=['dep_var'], values=['variable_id'],aggfunc='count'))

but I want my result to be saved as pandas DataFrame

desired output:
how I want my output for each variable separately

Body:
Use:

def pivot_table(df):
    dfs = []
    for column in df:
        print("indexing by: ", column)
        df = pd.pivot_table(df,index=[column], values=['dep_var'])
        dfs.append(df)
    return dfs


问:
Implement lazy loading in nested routes
I'm trying to add implement lazy loading in react app which works well in top-level routes. But I also want the <Suspense></Suspense> and provide a fallback for nested routes. According to react-router-dom, there must be only Fragment or Route as the children of Routes. Is there any way to handle this?

Here is the code:

```<code>import { lazy, Fragment, Suspense } from "react";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";

import Header from "./components/Header";

const Home = lazy(() => import("./components/layout/Home"));
const Destination = lazy(() => import("./components/layout/Destination"));
const Planet = lazy(() => import("./components/Planet"));
const Crew = lazy(() => import("./components/layout/Crew"));
const Biography = lazy(() => import("./components/Biography"));
const Technology = lazy(() => import("./components/layout/Technology"));
const Procedure = lazy(() => import("./components/Procedure"));

function App() {
  return (
    <BrowserRouter>
      <Header />
      <Suspense fallback={<p className='fixed left-1/2 top-1/2 -translate-x-1/2 text-2xl'>Loading ...</p>}>
        <Routes>
          <Route path="/" element={<Navigate to="home" />} />
          <Route path="home" element={<Home />} />
          <Route path="destination" element={<Destination />}>
            <Route path=":id/:planet" element={<Planet />} />
          </Route>
          <Route path="crew" element={<Crew />}>
            <Route path=":id" element={<Biography />} />
          </Route>
          <Route path="technology" element={<Technology />}>
            <Route path=":id" element={<Procedure />} />
          </Route>
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

export default App;
</code>```

答:
You can wrap individual routed components in their own Suspense.

Example:

```<code><BrowserRouter>
  <Header />
  <Suspense
    fallback={(
      <p className='fixed left-1/2 top-1/2 -translate-x-1/2 text-2xl'>
        Loading ...
      </p>
    )}
  >
    <Routes>
      ...
      <Route path="destination" element={<Destination />}>
        <Route
          path=":id/:planet"
          element={(
            <Suspense fallback={<>Loading Planet ...</>}>
              <Planet />
            </Suspense>
          )}
        />
      </Route>
      ...
    </Routes>
  </Suspense>
</BrowserRouter>
</code>```

Title: Implement lazy loading in nested routes

Body:
I'm trying to add implement lazy loading in react app which works well in top-level routes. But I also want the <Suspense></Suspense> and provide a fallback for nested routes. According to react-router-dom, there must be only Fragment or Route as the children of Routes. Is there any way to handle this?

Here is the code:

import { lazy, Fragment, Suspense } from "react";
import { BrowserRouter, Route, Routes, Navigate } from "react-router-dom";

import Header from "./components/Header";

const Home = lazy(() => import("./components/layout/Home"));
const Destination = lazy(() => import("./components/layout/Destination"));
const Planet = lazy(() => import("./components/Planet"));
const Crew = lazy(() => import("./components/layout/Crew"));
const Biography = lazy(() => import("./components/Biography"));
const Technology = lazy(() => import("./components/layout/Technology"));
const Procedure = lazy(() => import("./components/Procedure"));

function App() {
  return (
    <BrowserRouter>

      <Suspense fallback={
Loading ...
}>
        <Routes>
          <Route path="/" element={<Navigate to="home" />} />
          <Route path="home" element={<Home />} />
          <Route path="destination" element={<Destination />}>
            <Route path=":id/:planet" element={<Planet />} />
          </Route>
          <Route path="crew" element={<Crew />}>
            <Route path=":id" element={<Biography />} />
          </Route>
          <Route path="technology" element={<Technology />}>
            <Route path=":id" element={<Procedure />} />
          </Route>
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

export default App;

Body:
You can wrap individual routed components in their own Suspense.

Example:

<BrowserRouter>
  <Header />
  <Suspense
    fallback={(
      <p className='fixed left-1/2 top-1/2 -translate-x-1/2 text-2xl'>
        Loading ...
      </p>
    )}
  >
    <Routes>
      ...
      <Route path="destination" element={<Destination />}>
        <Route
          path=":id/:planet"
          element={(
            <Suspense fallback={<>Loading Planet ...</>}>
              <Planet />
            </Suspense>
          )}
        />
      </Route>
      ...
    </Routes>
  </Suspense>
</BrowserRouter>


问:
Golang flag: Ignore missing flag and parse multiple duplicate flags
I am new to Golang and I have been unable to find a solution to this problem using flag.

How can I use flag so my program can handle calls like these, where the -term flag may be present a variable number of times, including 0 times:

```<code>./myprogram -f flag1
./myprogram -f flag1 -term t1 -term t2 -term  t3
</code>```

答:
This question is an interesting one and can play in many variations.

Array

Map

Struct

The core content is the same as @reticentroot answered,

Complete the definition of this interface: Flag.Value

The following are examples to share and provide relevant links as much as possible

Example

expected usage:

type Books []string

func (*Books) String() string   { return "" }
func (*Books) Set(string) error { return nil }

type Dict map[string]string

func (*Dict) String() string   { return "" }
func (*Dict) Set(string) error { return nil }

type Person struct {
    Name string
    Age  int
}

func (*Person) String() string   { return "" }
func (*Person) Set(string) error { return nil }

func pseudocode() {
    flagSetTest := flag.NewFlagSet("test", flag.ContinueOnError)

    books := Books{}
    flagSetTest.Var(&books, "book", "-book C++ -book Go -book javascript")
    // expected output: books: []string{C++,Go,javascript}

    dict := Dict{}
    flagSetTest.Var(&dict, "dict", "-dict A:65|B:66")
    // expected output: dict: map[string]string{"A":"65", "B":"66"}

    // map
    person := Person{}
    flagSetTest.Var(&person, "person", "-person Name:foo|Age:18")
    // output: {Name:foo Age:18}

    flagSetTest.Parse(os.Args[1:])
    fmt.Println(person, books, dict)
}
```
<p>Full code</p>
<pre class="lang-golang prettyprint-override"><code>package main

import (
    "bufio"
    "errors"
    "flag"
    "fmt"
    "os"
    "reflect"
    "strconv"
    "strings"
)

type BooksValue []string

// https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L298
func (arr *BooksValue) String() string {
    /*
        value.String(): https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L870
        DefValue string:
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L348
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L914-L920
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L529-L536
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L464
    */
    return ""
}

// https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L299
func (arr *BooksValue) Set(value string) error {
    /*
        value: https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L947
        bool: Set(value): https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L966-L975
        else: Set(value): https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L986-L988
    */
    *arr = append(*arr, strings.TrimSpace(value))
    return nil
}

type DictValue map[string]string

func (m *DictValue) String() string {
    return ""
}

func (m *DictValue) Set(value string) error {
    arr := strings.Split(value, "|") // "key1:val1|key2:val2|..."
    for _, curPairStr := range arr {
        itemArr := strings.Split(curPairStr, ":")
        key := itemArr[0]
        val := itemArr[1]
        (*m)[key] = val
    }
    return nil
}

type PersonValue struct {
    Name     string
    Age      int
    Msg      string
    IsActive bool
}

func (s *PersonValue) String() string {
    return ""
}

func (s *PersonValue) Set(value string) error {
    arr := strings.Split(value, "|") // "Field1:Value1|F2:V2|...|FN:VN"

    for _, curPairStr := range arr {
        itemArr := strings.Split(curPairStr, ":")
        key := itemArr[0]
        val := itemArr[1]

        // [Access struct property by name](https://stackoverflow.com/a/66470232/9935654)
        pointToStruct := reflect.ValueOf(s)
        curStruct := pointToStruct.Elem()
        curField := curStruct.FieldByName(key)
        if !curField.IsValid() {
            return errors.New("not found")
        }

        // CanSet one of conditions: Name starts with a capital
        if !curField.CanSet() {
            return errors.New("can't set")
        }

        t := reflect.TypeOf(*s)
        structFieldXXX, isFound := t.FieldByName(key)
        if !isFound {
            return errors.New("not found")
        }

        switch structFieldXXX.Type.Name() {
        case "int":
            // https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L146-L153
            intValue, err := strconv.ParseInt(val, 0, strconv.IntSize)
            if err != nil {
                return errors.New("parse error: [int]")
            }
            curField.SetInt(intValue)
        case "bool":
            // https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L117-L121
            boolValue, err := strconv.ParseBool(val)
            if err != nil {
                return errors.New("parse error: [bool]")
            }
            curField.SetBool(boolValue)
        case "string":
            curField.SetString(val)
        default:
            return errors.New("not support type=" + structFieldXXX.Type.Name())
        }
    }

    return nil
}

func main() {

    flagSetTest := flag.NewFlagSet("test", flag.ContinueOnError)

    // array
    books := BooksValue{}
    flagSetTest.Var(&books, "book", "-book Go -book javascript ...")

    // map
    myMap := DictValue{}
    flagSetTest.Var(&myMap, "map", "-dict A:65|B:66")

    // struct
    person := PersonValue{Msg: "Hello world"}
    flagSetTest.Var(&person, "person", "-person Name:string|Age:int|Msg:string|IsActive:bool")

    testArgs := []string{"test",
        "-book", "Go", "-book", "javascript", // testArray
        "-map", "A:65|B:66|Name:Carson", // testMap
        "-person", "Name:Carson|Age:30|IsActive:true", // testStruct
    }

    testFunc := func(args []string, reset bool) {
        if reset {
            books = BooksValue{}
            myMap = DictValue{}
            person = PersonValue{}
        }

        if err := flagSetTest.Parse(args); err != nil {
            fmt.Printf(err.Error())
        }
        fmt.Printf("%+v\n", books)
        fmt.Printf("%+v\n", myMap)
        fmt.Printf("%+v\n", person)
    }

    testFunc(testArgs[1:], false)

    // ↓ play by yourself
    scanner := bufio.NewScanner(os.Stdin)
    for {
        fmt.Println("Enter CMD: ") // example: test -book item1 -book item2 -map key1:value1|key2:v2 -person Age:18|Name:Neil|IsActive:true
        scanner.Scan()             // Scans a line from Stdin(Console)
        text := scanner.Text()     // Holds the string that scanned
        args := strings.Split(text, " ")

        switch args[0] {
        case "quit":
            return
        case "test":
            testFunc(args[1:], true)
        }
    }
}
</code>```

go playground

Body:
I am new to Golang and I have been unable to find a solution to this problem using flag.

How can I use flag so my program can handle calls like these, where the -term flag may be present a variable number of times, including 0 times:

./myprogram -f flag1
./myprogram -f flag1 -term t1 -term t2 -term  t3

Body:
This question is an interesting one and can play in many variations.

Array

Map

Struct

The core content is the same as @reticentroot answered,

Complete the definition of this interface: Flag.Value

The following are examples to share and provide relevant links as much as possible

Example

expected usage:

type Books []string

func (*Books) String() string   { return "" }
func (*Books) Set(string) error { return nil }

type Dict map[string]string

func (*Dict) String() string   { return "" }
func (*Dict) Set(string) error { return nil }

type Person struct {
    Name string
    Age  int
}

func (*Person) String() string   { return "" }
func (*Person) Set(string) error { return nil }

func pseudocode() {
    flagSetTest := flag.NewFlagSet("test", flag.ContinueOnError)

    books := Books{}
    flagSetTest.Var(&books, "book", "-book C++ -book Go -book javascript")
    // expected output: books: []string{C++,Go,javascript}

    dict := Dict{}
    flagSetTest.Var(&dict, "dict", "-dict A:65|B:66")
    // expected output: dict: map[string]string{"A":"65", "B":"66"}

    // map
    person := Person{}
    flagSetTest.Var(&person, "person", "-person Name:foo|Age:18")
    // output: {Name:foo Age:18}

    flagSetTest.Parse(os.Args[1:])
    fmt.Println(person, books, dict)
}

Full code

package main

import (
    "bufio"
    "errors"
    "flag"
    "fmt"
    "os"
    "reflect"
    "strconv"
    "strings"
)

type BooksValue []string

// https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L298
func (arr *BooksValue) String() string {
    /*
        value.String(): https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L870
        DefValue string:
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L348
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L914-L920
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L529-L536
            - https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L464
    */
    return ""
}

// https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L299
func (arr *BooksValue) Set(value string) error {
    /*
        value: https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L947
        bool: Set(value): https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L966-L975
        else: Set(value): https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L986-L988
    */
    *arr = append(*arr, strings.TrimSpace(value))
    return nil
}

type DictValue map[string]string

func (m *DictValue) String() string {
    return ""
}

func (m *DictValue) Set(value string) error {
    arr := strings.Split(value, "|") // "key1:val1|key2:val2|..."
    for _, curPairStr := range arr {
        itemArr := strings.Split(curPairStr, ":")
        key := itemArr[0]
        val := itemArr[1]
        (*m)[key] = val
    }
    return nil
}

type PersonValue struct {
    Name     string
    Age      int
    Msg      string
    IsActive bool
}

func (s *PersonValue) String() string {
    return ""
}

func (s *PersonValue) Set(value string) error {
    arr := strings.Split(value, "|") // "Field1:Value1|F2:V2|...|FN:VN"

    for _, curPairStr := range arr {
        itemArr := strings.Split(curPairStr, ":")
        key := itemArr[0]
        val := itemArr[1]

        // [Access struct property by name](https://stackoverflow.com/a/66470232/9935654)
        pointToStruct := reflect.ValueOf(s)
        curStruct := pointToStruct.Elem()
        curField := curStruct.FieldByName(key)
        if !curField.IsValid() {
            return errors.New("not found")
        }

        // CanSet one of conditions: Name starts with a capital
        if !curField.CanSet() {
            return errors.New("can't set")
        }

        t := reflect.TypeOf(*s)
        structFieldXXX, isFound := t.FieldByName(key)
        if !isFound {
            return errors.New("not found")
        }

        switch structFieldXXX.Type.Name() {
        case "int":
            // https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L146-L153
            intValue, err := strconv.ParseInt(val, 0, strconv.IntSize)
            if err != nil {
                return errors.New("parse error: [int]")
            }
            curField.SetInt(intValue)
        case "bool":
            // https://github.com/golang/go/blob/2580d0e/src/flag/flag.go#L117-L121
            boolValue, err := strconv.ParseBool(val)
            if err != nil {
                return errors.New("parse error: [bool]")
            }
            curField.SetBool(boolValue)
        case "string":
            curField.SetString(val)
        default:
            return errors.New("not support type=" + structFieldXXX.Type.Name())
        }
    }

    return nil
}

func main() {

    flagSetTest := flag.NewFlagSet("test", flag.ContinueOnError)

    // array
    books := BooksValue{}
    flagSetTest.Var(&books, "book", "-book Go -book javascript ...")

    // map
    myMap := DictValue{}
    flagSetTest.Var(&myMap, "map", "-dict A:65|B:66")

    // struct
    person := PersonValue{Msg: "Hello world"}
    flagSetTest.Var(&person, "person", "-person Name:string|Age:int|Msg:string|IsActive:bool")

    testArgs := []string{"test",
        "-book", "Go", "-book", "javascript", // testArray
        "-map", "A:65|B:66|Name:Carson", // testMap
        "-person", "Name:Carson|Age:30|IsActive:true", // testStruct
    }

    testFunc := func(args []string, reset bool) {
        if reset {
            books = BooksValue{}
            myMap = DictValue{}
            person = PersonValue{}
        }

        if err := flagSetTest.Parse(args); err != nil {
            fmt.Printf(err.Error())
        }
        fmt.Printf("%+v\n", books)
        fmt.Printf("%+v\n", myMap)
        fmt.Printf("%+v\n", person)
    }

    testFunc(testArgs[1:], false)

    // ↓ play by yourself
    scanner := bufio.NewScanner(os.Stdin)
    for {
        fmt.Println("Enter CMD: ") // example: test -book item1 -book item2 -map key1:value1|key2:v2 -person Age:18|Name:Neil|IsActive:true
        scanner.Scan()             // Scans a line from Stdin(Console)
        text := scanner.Text()     // Holds the string that scanned
        args := strings.Split(text, " ")

        switch args[0] {
        case "quit":
            return
        case "test":
            testFunc(args[1:], true)
        }
    }
}

go playground


问:
Javascript image upload and display
My basic task is select image and display it,without saving it in database.

For this

1.I have made a select tag in html,through which I can upload the image.

2.I have made a blank image tag in which at there is no image source,alternate is upload image.

3.select tag has onchange javascript event handler which calls javascript function changeimage.

```<code><script>
       function changeimage()
       {
            document.form_name.imagetag.src=document.form_name.filetag.value;
       }
</script>
</code>```

In above Code

form_name : Is the name of my form

```<code><form name = "form_name">
</code>```

imagetag : Is the name of my Img tag

```<code><Img src=" " name = "imagetag">
</code>```

filetag : Is the name of my

```<code><input type="file" name = "filetag" onchange="changeimage()">
</code>```

I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.

I am using window 7,wamp server and chrome latest version.

答:
You need one input tag to upload file and a image tag to render on the site.

The HTML and Javascript should look like

const renderFile = () => {
  const render = document.querySelector('img')
  const file = document.querySelector('input[type=file]').files[0]
  const reader = new FileReader();

  reader.addEventListener('load' , ()=> {
    render.src = reader.result;
  }, false)

  if(file){
    reader.readAsDataURL(file);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image'  ></code>```

Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need

Title: Javascript image upload and display

Body:
My basic task is select image and display it,without saving it in database.

For this

1.I have made a select tag in html,through which I can upload the image.

2.I have made a blank image tag in which at there is no image source,alternate is upload image.

3.select tag has onchange javascript event handler which calls javascript function changeimage.

In above Code

form_name : Is the name of my form

<form name = "form_name">

imagetag : Is the name of my Img tag

filetag : Is the name of my

<input type="file" name = "filetag" onchange="changeimage()">

I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.

I am using window 7,wamp server and chrome latest version.

Body:
You need one input tag to upload file and a image tag to render on the site.

The HTML and Javascript should look like

const renderFile = () => {
  const render = document.querySelector('img')
  const file = document.querySelector('input[type=file]').files[0]
  const reader = new FileReader();

  reader.addEventListener('load' , ()=> {
    render.src = reader.result;
  }, false)

  if(file){
    reader.readAsDataURL(file);
  }
}

<input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image'  >

Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need


问:
Error: One of the `NSLocation*UsageDescription` keys must be present in Info.plist to be able to use geolocation
When I want to test my app with Expo Go on iOS I get this error:

[Unhandled promise rejection: Error: One of the `NSLocation*UsageDescription` keys must be present in Info.plist to be able to use geolocation.]

Stack trace:
  node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:104:50 in promiseMethodWrapper
  node_modules\expo-modules-core\build\NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
```
<p>I added that configuration to info.plist, rebuilt the project, but I get the same error, I also reinstalled node packages, but it didn't change anything.</p>
<p>package.json</p>
<pre class="lang-json prettyprint-override"><code>    "dependencies": {
        "@expo/vector-icons": "^12.0.0",
        "expo": "~43.0.2",
        "expo-location": "~13.0.4",
        "expo-status-bar": "~1.1.0",
        "expo-task-manager": "~10.0.3",
        "react": "17.0.1",
        "react-dom": "17.0.1",
        "react-native": "0.64.3",
        "react-native-paper": "4.9.2",
        "react-native-web": "0.17.1",
        "expo-splash-screen": "~0.13.5",
        "expo-updates": "~0.10.13",
        "react-native-gesture-handler": "~1.10.2",
        "react-native-reanimated": "~2.2.0",
        "react-native-safe-area-context": "3.3.2",
        "react-native-screens": "~3.8.0"
      },
      "devDependencies": {
        "@babel/core": "^7.12.9"
      }
</code>```

My js code

  const { status } = await Location.requestForegroundPermissionsAsync();
    if (status === "granted") {
      const background = await Location.requestBackgroundPermissionsAsync();
      if (background.status === "granted") {
        await Location.startLocationUpdatesAsync(TASK_FETCH_LOCATION, {
          activityType: Location.LocationActivityType.BestForNavigation,
          showsBackgroundLocationIndicator: true,
          accuracy: Location.Accuracy.BestForNavigation,
          deferredUpdatesInterval: 3000,
          deferredUpdatesDistance: 50,
          showsBackgroundLocationIndicator: true,
        }).then(() => {
          Alert.alert("Turn on", null, [
            { text: "OK", onPress: () => console.log("listening gps") },
          ]);
        });
      }
    }
```
<p>app.json</p>
<pre class="lang-json prettyprint-override"><code>   "ios": {
      "supportsTablet": true,
      "infoPlist": {
        "UIBackgroundModes": [
          "location",
          "fetch"
        ],
        "NSLocationAlwaysAndWhenInUseUsageDescription": "Allows App to use location services in the foreground and background.",
        "NSFaceIDUsageDescription": "Allows App to use Face ID for a simpler sign in."
      }
    }
</code>```

答:
You need to explicitly set these key-string pair inside of the Info.plist of your project.</p>
```<code>    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>Your geolocation string</string>
</code>```

Body:
When I want to test my app with Expo Go on iOS I get this error:

[Unhandled promise rejection: Error: One of the `NSLocation*UsageDescription` keys must be present in Info.plist to be able to use geolocation.]

Stack trace:
  node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:104:50 in promiseMethodWrapper
  node_modules\expo-modules-core\build\NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name

I added that configuration to info.plist, rebuilt the project, but I get the same error, I also reinstalled node packages, but it didn't change anything.

package.json

    "dependencies": {
        "@expo/vector-icons": "^12.0.0",
        "expo": "~43.0.2",
        "expo-location": "~13.0.4",
        "expo-status-bar": "~1.1.0",
        "expo-task-manager": "~10.0.3",
        "react": "17.0.1",
        "react-dom": "17.0.1",
        "react-native": "0.64.3",
        "react-native-paper": "4.9.2",
        "react-native-web": "0.17.1",
        "expo-splash-screen": "~0.13.5",
        "expo-updates": "~0.10.13",
        "react-native-gesture-handler": "~1.10.2",
        "react-native-reanimated": "~2.2.0",
        "react-native-safe-area-context": "3.3.2",
        "react-native-screens": "~3.8.0"
      },
      "devDependencies": {
        "@babel/core": "^7.12.9"
      }

My js code

  const { status } = await Location.requestForegroundPermissionsAsync();
    if (status === "granted") {
      const background = await Location.requestBackgroundPermissionsAsync();
      if (background.status === "granted") {
        await Location.startLocationUpdatesAsync(TASK_FETCH_LOCATION, {
          activityType: Location.LocationActivityType.BestForNavigation,
          showsBackgroundLocationIndicator: true,
          accuracy: Location.Accuracy.BestForNavigation,
          deferredUpdatesInterval: 3000,
          deferredUpdatesDistance: 50,
          showsBackgroundLocationIndicator: true,
        }).then(() => {
          Alert.alert("Turn on", null, [
            { text: "OK", onPress: () => console.log("listening gps") },
          ]);
        });
      }
    }

app.json

   "ios": {
      "supportsTablet": true,
      "infoPlist": {
        "UIBackgroundModes": [
          "location",
          "fetch"
        ],
        "NSLocationAlwaysAndWhenInUseUsageDescription": "Allows App to use location services in the foreground and background.",
        "NSFaceIDUsageDescription": "Allows App to use Face ID for a simpler sign in."
      }
    }

Body:
You need to explicitly set these key-string pair inside of the Info.plist of your project.

    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>Your geolocation string</string>


问:
Guaranteed always on top on a webpage
I'm developing a chrome extension, without going too much into it I need to inject some code into webpages and put an overlay over the full page. Thus far I have nearly achieved this butI just cannot seem to get the overlay over certain parts of some websites. These include videos from youtube, the searchbar on top of google search results, random parts of kongregate (the stars and monthly comp info).

Below is the css I'm currently using to achieve this, I have played around and looked for solutions at various places but no solutions seems to work.

```<code>.cssX9482Overlay
{
    position: fixed;
    width: 100%;
    Height: 100%;
    vertical-align: middle;
    background: #000000;
    opacity: 0.97;
    filter: alpha(opacity=97);
    text-align: center;
    top: 0;
    left: 0;
}
</code>```

The strange css name is just so it doesn't clash with pages formatting. As you probably guessed this is being used to format a div

Remember this is a Chrome extension, therefore HTML5 and CSS3 solutions are valid.

答:
You might need a z-index in there; on a Google search results page for me, adding a z-index: 999; covers everything except the top navigation (Web, Images, Videos). This is because Google's CSS looks like:

```<code>#gbz, #gbg {
  ...
  z-index: 1000;
}
</code>```

Elements with a larger z-index are placed on top of others. Even while using this property, I've had problems in the placing content on top of Adobe Flash elements and Java applets.

Title: Guaranteed always on top on a webpage

Body:
I'm developing a chrome extension, without going too much into it I need to inject some code into webpages and put an overlay over the full page. Thus far I have nearly achieved this butI just cannot seem to get the overlay over certain parts of some websites. These include videos from youtube, the searchbar on top of google search results, random parts of kongregate (the stars and monthly comp info).

Below is the css I'm currently using to achieve this, I have played around and looked for solutions at various places but no solutions seems to work.

.cssX9482Overlay
{
    position: fixed;
    width: 100%;
    Height: 100%;
    vertical-align: middle;
    background: #000000;
    opacity: 0.97;
    filter: alpha(opacity=97);
    text-align: center;
    top: 0;
    left: 0;
}

The strange css name is just so it doesn't clash with pages formatting. As you probably guessed this is being used to format a div

Remember this is a Chrome extension, therefore HTML5 and CSS3 solutions are valid.

Body:
You might need a z-index in there; on a Google search results page for me, adding a z-index: 999; covers everything except the top navigation (Web, Images, Videos). This is because Google's CSS looks like:

#gbz, #gbg {
  ...
  z-index: 1000;
}

Elements with a larger z-index are placed on top of others. Even while using this property, I've had problems in the placing content on top of Adobe Flash elements and Java applets.


问:
Get domain name from full URL
say someone enters a URL like this:

```<code>http://i.imgur.com/a/b/c?query=value&query2=value
</code>```

And I want to return: imgur.com

not i.imgur.com

This is code I have right now

```<code>$sourceUrl = parse_url($url);
$sourceUrl = $sourceUrl['host'];
</code>```

But this returns i.imgur.com

答:
Check Simaple Code
You can get host, subdomain, domain, extension

```<code>$urls = array("https://www.face.com","www.asdasd.asd","sasdas.com/asdas","sdfsdf.sdf","https://app.abcdlink.com/user/test/");
</code>```

Function :-

```<code>function getDomainname($a)
{
   $r = "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
   $r = "!$r!";// Delimiters
   preg_match($r, $a, $out);

// if you need only domain then return $out['domain'];
// if you need only host then return $out['host'];
// if you need only subdomain then return $out['subdomain'];
// if you need only extension then return $out['extension'];

// Full Data array
    return $out;

}

$urls = array_map('getDomainname', $urls);
</code>```

OR

```<code>function getsingaldomainHost($a)
{
    $a = (substr($a, 0, 7) == "http://" || substr($a, 0, 8) == "https://") ?  $a : 'http://' . $a;
    $r = "/(?P<host>(?:(?P<subdomain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z0-9]{0,62}))?(?P<domain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z0-9]{0,62})(?P<extension>[a-z0-9][a-z0-9\-]{0,63}\.[a-z\.]{0,61}))$/i";
    $pieces = parse_url($a);
    if (isset($pieces['host'])) {
        $domain = substr($pieces['host'], 0, 4) == "www." ?  $pieces['host'] : 'www.' . $pieces['host'];
    } else {
        $domain = $pieces['path'];
    }

    if (preg_match($r, $domain, $regs)) {
        return substr($regs['host'], 0, 4) == "www." ? substr($regs['host'], 4) : $regs['host'];
    } else {
        if ($rr == 1) {
            return false;
        } else {
            return $a;
        }
    }
}
$urls = array_map('getsingaldomainHost', $urls);
</code>```

Title: Get domain name from full URL

Body:
say someone enters a URL like this:

http://i.imgur.com/a/b/c?query=value&query2=value

And I want to return: imgur.com

not i.imgur.com

This is code I have right now

$sourceUrl = parse_url($url);
$sourceUrl = $sourceUrl['host'];

But this returns i.imgur.com

Body:
Check Simaple Code
You can get host, subdomain, domain, extension

$urls = array("https://www.face.com","www.asdasd.asd","sasdas.com/asdas","sdfsdf.sdf","https://app.abcdlink.com/user/test/");

Function :-

function getDomainname($a)
{
   $r = "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
   $r = "!$r!";// Delimiters
   preg_match($r, $a, $out);

// if you need only domain then return $out['domain'];
// if you need only host then return $out['host'];
// if you need only subdomain then return $out['subdomain'];
// if you need only extension then return $out['extension'];

// Full Data array
    return $out;

}

$urls = array_map('getDomainname', $urls);

OR

function getsingaldomainHost($a)
{
    $a = (substr($a, 0, 7) == "http://" || substr($a, 0, 8) == "https://") ?  $a : 'http://' . $a;
    $r = "/(?P<host>(?:(?P<subdomain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z0-9]{0,62}))?(?P<domain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z0-9]{0,62})(?P<extension>[a-z0-9][a-z0-9\-]{0,63}\.[a-z\.]{0,61}))$/i";
    $pieces = parse_url($a);
    if (isset($pieces['host'])) {
        $domain = substr($pieces['host'], 0, 4) == "www." ?  $pieces['host'] : 'www.' . $pieces['host'];
    } else {
        $domain = $pieces['path'];
    }

    if (preg_match($r, $domain, $regs)) {
        return substr($regs['host'], 0, 4) == "www." ? substr($regs['host'], 4) : $regs['host'];
    } else {
        if ($rr == 1) {
            return false;
        } else {
            return $a;
        }
    }
}
$urls = array_map('getsingaldomainHost', $urls);


问:
Strip blanks at the beginning & trailing blanks in AWK
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

```<code>001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith
</code>```

My objective is to achieve the following set of data (without the leading/trailing spaces)

```<code>001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

I have tried the following without satisfaction.

```<code>awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith
</code>```

答:
You've got good awk answers. However if you want to consider sed this is pretty simple with:

sed -E 's/ *(\|) *|^ +| +$/\1/g' file

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
```
<p>Or else with <code>gnu-awk</code>:</p>
<pre class="lang-sh prettyprint-override"><code>awk '{print gensub(/ *(\|) *|^ +| +$/, "\\1", "g")}' file
</code>```

PS: This sed command requires GNU or BSD versions.

Body:
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith

My objective is to achieve the following set of data (without the leading/trailing spaces)

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

I have tried the following without satisfaction.

awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith

Body:
You've got good awk answers. However if you want to consider sed this is pretty simple with:

sed -E 's/ *(\|) *|^ +| +$/\1/g' file

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

Or else with gnu-awk:

awk '{print gensub(/ *(\|) *|^ +| +$/, "\\1", "g")}' file

PS: This sed command requires GNU or BSD versions.


问:
`line()` in p5js crosses the edges. Beside doing the math myself, is there an easier way to make the line just connect their edges?
I'm trying to draw a line to connect two given circles.

function setup() {
  createCanvas(300, 100);
  background(220);
  noFill();
  ellipse(150, 30, 20, 20);
  ellipse(100, 50, 20, 20);
  line(100, 50, 150, 30);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script></code>```

The parameters I get are the x, y of the circle's center. If I use the info directly, the line crosses both circles.

I know I can do the math, I'd just like to know if there is an easier way to make the line just connect their edges?

答:
One easy way would be draw the line first then draw the circles and fill them with the background color this way the line inside the circles will be hidden, this only work if you don't mind the background and the circles color to be the same

function setup() {
  createCanvas(300, 100);
  background(220);
  line(100, 50, 150, 30);
  fill(220);
  ellipse(150, 30, 20, 20);
  ellipse(100, 50, 20, 20);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script></code>```

Body:
I'm trying to draw a line to connect two given circles.

function setup() {
  createCanvas(300, 100);
  background(220);
  noFill();
  ellipse(150, 30, 20, 20);
  ellipse(100, 50, 20, 20);
  line(100, 50, 150, 30);
}

The parameters I get are the x, y of the circle's center. If I use the info directly, the line crosses both circles.

I know I can do the math, I'd just like to know if there is an easier way to make the line just connect their edges?

Body:
One easy way would be draw the line first then draw the circles and fill them with the background color this way the line inside the circles will be hidden, this only work if you don't mind the background and the circles color to be the same

function setup() {
  createCanvas(300, 100);
  background(220);
  line(100, 50, 150, 30);
  fill(220);
  ellipse(150, 30, 20, 20);
  ellipse(100, 50, 20, 20);

}

<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js"></script>


问:
.net 6 and Redis cache integration using sets , hashes
.net 6 and Redis cache integration using sets , hashes.
Please provide source code for this.
Use latest stack exchange library.</p>

答:
Here is a simple save demo, you can take a look:

Program.cs:

```<code>builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = "127.0.0.1:6379";
});
builder.Services.AddSession();

app.UseSession();
</code>```

Controller:

```<code>[ApiController]
    public class TestController : Controller
    {
        private readonly IDistributedCache _distributedCache;

        public TestController(IDistributedCache distributedCache)
        {
            _distributedCache = distributedCache;
        }
        [HttpGet]
        [Route("test")]
        public void Test()
        {
            const string key = "message";
            const string value = "hello";
            _distributedCache.SetString(key, value);

        }
    }
</code>```

Result:

For more examples, you can refer to this article：

Distributed caching in ASP.NET Core

Body:
Here is a simple save demo, you can take a look:

Program.cs:

builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = "127.0.0.1:6379";
});
builder.Services.AddSession();

app.UseSession();

Controller:

[ApiController]
    public class TestController : Controller
    {
        private readonly IDistributedCache _distributedCache;

        public TestController(IDistributedCache distributedCache)
        {
            _distributedCache = distributedCache;
        }
        [HttpGet]
        [Route("test")]
        public void Test()
        {
            const string key = "message";
            const string value = "hello";
            _distributedCache.SetString(key, value);

        }
    }

Result:

For more examples, you can refer to this article：

Distributed caching in ASP.NET Core


问:
Replace values from a string if they are present in an array of variables
Having the following array of objects:

```<code>const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];
</code>```

And the input string:

```<code>const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;
</code>```

The function should take as arguments variables and inputString and return the following sting:

```<code>'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'
</code>```

Here is the function so far:

```<code>function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}
</code>```

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?

答:
My solution with use "reduce"

const variables = [
  { name: "%NAME%", value: "joe" },
  { name: "%EMAIL%", value: "%NAME%@mail.com" },
  { name: "%HOBBY%", value: "tennis" }
];
const inputString =
  "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";

function doMagic(string, variables) {
  const replaceVar = (s, v) =>
    v.reduce((prev = "", { name, value }) => prev.replace(name, value), s);
  const fixedVariables = variables.map((v) => ({
    ...v,
    value: replaceVar(v.value, variables)
  }));

  return replaceVar(string, fixedVariables);
}

console.log(doMagic(inputString, variables));```
</div>
</div>
</p>
<p>Also if you want, you can modify my code to prototype, like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const inputString =
  "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";

String.prototype.doMagic = function (variables) {
  const replaceVar = (s, v) =>
    v.reduce((prev = "", { name, value }) => prev.replace(name, value), s);
  const fixedVariables = variables.map(({ value, ...rest }) => ({
    ...rest,
    value: replaceVar(value, variables)
  }));

  return replaceVar(this, fixedVariables);
};

console.log(
  inputString.doMagic([
    { name: "%NAME%", value: "joe" },
    { name: "%EMAIL%", value: "%NAME%@mail.com" },
    { name: "%HOBBY%", value: "tennis" }
  ])
)</code>```

Body:
Having the following array of objects:

const variables = [
  { name: '%NAME%', value: 'joe' },
  { name: '%EMAIL%', value: '%NAME%@mail.com' },
  { name: '%HOBBY%', value: 'tennis' }
];

And the input string:

const inputString = `Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%`;

The function should take as arguments variables and inputString and return the following sting:

'Hi, my name is joe, I like tennis, you can contact me at joe@mail.com'

Here is the function so far:

function doMagic(variables, inputString) {
  let output = inputString;
  for (let i = 0; i < variables.length; i++) {
     output = inputString.replace(variables[i].name, variables[i].value);
  }
  return output;
}

Unfortunatelly, this only finds one occurrence, in case there are more, and it doesn't go into nested variables, like %EMAIL%.

Any ideas to improve?

Body:
My solution with use "reduce"

const variables = [
  { name: "%NAME%", value: "joe" },
  { name: "%EMAIL%", value: "%NAME%@mail.com" },
  { name: "%HOBBY%", value: "tennis" }
];
const inputString =
  "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";

function doMagic(string, variables) {
  const replaceVar = (s, v) =>
    v.reduce((prev = "", { name, value }) => prev.replace(name, value), s);
  const fixedVariables = variables.map((v) => ({
    ...v,
    value: replaceVar(v.value, variables)
  }));

  return replaceVar(string, fixedVariables);
}

console.log(doMagic(inputString, variables));

Also if you want, you can modify my code to prototype, like this:

const inputString =
  "Hi, my name is %NAME%, I like %HOBBY%, you can contact me at %EMAIL%";

String.prototype.doMagic = function (variables) {
  const replaceVar = (s, v) =>
    v.reduce((prev = "", { name, value }) => prev.replace(name, value), s);
  const fixedVariables = variables.map(({ value, ...rest }) => ({
    ...rest,
    value: replaceVar(value, variables)
  }));

  return replaceVar(this, fixedVariables);
};

console.log(
  inputString.doMagic([
    { name: "%NAME%", value: "joe" },
    { name: "%EMAIL%", value: "%NAME%@mail.com" },
    { name: "%HOBBY%", value: "tennis" }
  ])
)


问:
OutOfMemoryError: java heap space when reading a 35MB xlsx file using Apache POI HSSFWorkbook
I am using Apache POI HSSFWorkbook to read a 35MB xlsx file with 15000 rows and 400 columns, the memory consumption is 3.06GB and an OutOfMemoryError: java heap space appears. Do you have any optimization suggestions?

    public static ArrayList<List<String>> readWorkBook(InputStream in, int columnCount, int beginLine, boolean isXlsx) throws Exception {
        ArrayList<List<String>> result = new ArrayList<>();
        Workbook xssfWorkbook;
        try {
            if (isXlsx) {
                xssfWorkbook = new XSSFWorkbook(in);
            } else {
                xssfWorkbook = new HSSFWorkbook(in);
            }
            for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
                Sheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
                if (xssfSheet == null) {
                    continue;
                }
                for (int rowNum = beginLine; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                    Row xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow == null) {
                        continue;
                    }
                    ArrayList<String> curarr = new ArrayList<>();
                    int temp = 0;
                    for (int columnNum = 0; columnNum < columnCount; columnNum++) {
                        Cell cell = xssfRow.getCell(columnNum);
                        if (cell == null || Trim_str(getValue(cell)) == null) {
                            curarr.add("");
                            temp++;
                        } else {
                            curarr.add(Trim_str(getValue(cell)));
                        }
                    }
                    if (temp != columnCount) {
                        result.add(curarr);
                    }
                }
            }
        } finally {
            in.close();
        }
        return result;
    }
```

答:
try use xlsx-streamer this api provide streamer method  to read xlsx(just support xlsx)</p>
```<code><dependency>
  <groupId>com.monitorjbl</groupId>
  <artifactId>xlsx-streamer</artifactId>
  <version>2.0.0</version>
</dependency>
Workbook wb = StreamingReader.builder().rowCacheSize(100).bufferSize(8192).open(is);
</code>```

Body:
try use xlsx-streamer this api provide streamer method  to read xlsx(just support xlsx)

<dependency>
  <groupId>com.monitorjbl</groupId>
  <artifactId>xlsx-streamer</artifactId>
  <version>2.0.0</version>
</dependency>
Workbook wb = StreamingReader.builder().rowCacheSize(100).bufferSize(8192).open(is);


问:
String array in query parameters swagger
I'm working on a project where there is an endpoint that receives a list of strings in the parameter, as shown in the code below:

```<code>public class PaymentFilter
{
    public List<string> Status  {get; set; }
}

[HttpGet]
public IActionResult Get([FromQuery] PaymentFilter filter)
{
    ...
}
</code>```

However, in the swagger interface the status list is not reflected, as shown in the image:

How do I enable entries for the status list?

答:
Click Try it out button and click Add string item then you can add
parameter

Body:
I'm working on a project where there is an endpoint that receives a list of strings in the parameter, as shown in the code below:

public class PaymentFilter
{
    public List<string> Status  {get; set; }
}

[HttpGet]
public IActionResult Get([FromQuery] PaymentFilter filter)
{
    ...
}

However, in the swagger interface the status list is not reflected, as shown in the image:

How do I enable entries for the status list?