问:
How to show react variable values in loop in table td tag
i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

```<code>let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })
</code>```

My td code is:

```<code><tr>
  <td className="font-weight-medium"> <img className="logo" src={jessica} alt="pam-logo" /> </td>
  <td>jessicajames@gmail.com </td>
  <td>(012)-876789876</td>
  <td>Family Physician</td>
  <td>23145655</td>
  <td>Mountain view,Ave</td>
  <td><Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/></td>
</tr>
</code>```

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

答:
try this.</p>

```<code>import React, {useState, useEffect} from 'react'

const myFunction = () => {
  const [ data, setData ] = useState(null)

  const apiUrl = "http://api_url_here"

  useEffect(() => {
    axios.get(apiUrl, {headers: headers})
      .then((response) => {
         setData(response.data)
      })
  }, [])

  return (
    <>
      {
        data && data.map((item, index) => (
          <tr key={index}>
            <td>{item.provider.firstName}</td>
            ...
          </tr>
        ))
      }
    </>
  )
}
</code>```

Body:
i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })

My td code is:

  jessicajames@gmail.com
  (012)-876789876
  Family Physician
  23145655
  Mountain view,Ave
  <Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/>

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

Body:
try this.

import React, {useState, useEffect} from 'react'

const myFunction = () => {
  const [ data, setData ] = useState(null)

  const apiUrl = "http://api_url_here"

  useEffect(() => {
    axios.get(apiUrl, {headers: headers})
      .then((response) => {
         setData(response.data)
      })
  }, [])

  return (
    <>
      {
        data && data.map((item, index) => (
          <tr key={index}>
            <td>{item.provider.firstName}</td>
            ...
          </tr>
        ))
      }
    </>
  )
}


来源: stackexchange

问:
javascript: define a variable if it doesn't exist
i feel like im trying to do something super simple, but just being stupid about it.

all i want to do is see if a variable has been set previously, and if it has NOT, set it with a default value....here is a sample:

```<code>if(!embed_BackgroundColor) {
    var embed_BackgroundColor;
    embed_BackgroundColor = "#F4F4F4";
}
</code>```

so, once you stop laughing at my code....WHY is it overwriting the variable no matter what?

please save my nerves;)

答:
```<code>if(embed_BackgroundColor == "" || embed_BackgroundColor == 'undefined' || embed_BackgroundColor == null){
}
</code>```

OwnerDisplayName: johnnietheblack

ContentLicense: CC BY-SA 2.5

Body:
i feel like im trying to do something super simple, but just being stupid about it.

all i want to do is see if a variable has been set previously, and if it has NOT, set it with a default value....here is a sample:

if(!embed_BackgroundColor) {
    var embed_BackgroundColor;
    embed_BackgroundColor = "#F4F4F4";
}

so, once you stop laughing at my code....WHY is it overwriting the variable no matter what?

please save my nerves;)

LastEditorDisplayName: eyelidlessness

ContentLicense: CC BY-SA 4.0


问:
Exporting Only changed files from subversion maintaining directory structure
When I right click my local working copy and select show log.  TortoiseSVN shows me the full path of each file changed for that revision.
From the tortoiseSVN interface what I would like to do is the following.

when I right click the revision number and choose export.  I would like it to export the files, while keeping them in their directories.

Is this possible?

To put it another way, I want to export only the files I changed in the last commit, into a folder on my harddrive (that is not my working copy ) but I don't want them to be all lumped in the parent directory.  I want them to be copied including their relative path.

答:
I did not write this answer and have added it as the previous high-rated answer was deleted as the link was dead. I have extracted the post from a dead link which was archived at WebCite.

As such, I have set my answer as community wiki.

In Windows Explorer, right-click in the right pane (where the files and folders are) and select TortoiseSVN and then the Repo-Browser option as shown in the first screenshot below.

This will open a dialog window where you need to enter the URL to the repository as shown in the second screenshot below. Enter it and then click the OK button.

Once the TortoiseSVN Repository Browser has opened, right click in the files/folders area and select the "Show Log" option. This is highlighted with the red arrow in the screenshot below.

Select the two revisions that you want to export all the changed files between. In the example below I have selected revision 68 and revision 73. This means all the files that have been changed between these two revisions will be exported (i.e. all the files changed in revisions 69, 70, 71, 72 and 73). Now right-click and select the "Compare Revisions" option.

Now a list of all the changed files will be displayed as shown in the final screenshot below. Click in the files list area and select all (Ctrl+A), right click and select the "Export selection to..." option as highlighted in the screenshot with the red arrow.

Once the option is clicked you will be prompted for the location to export the changed files to. Follow through the process and all the files that have been modified between the two versions will be exported to the path specified.


问:
How call a controller from javascript after press a button
I created a controller that returns a pdf, my problem is that I can't recall it from javascript, by pressing the button with the click action.

I have tried with ajax.rpc and rpc.query but to no avail. If I go to the url I can download the file.

Is there any way to get the file that the controller returns?

答:
If your goal is to download a file the simplest solution is to instead a button use a link with the attribute download.

Click here to download
```

Body:
If your goal is to download a file the simplest solution is to instead a button use a link with the attribute download.

<a href="http://yoururl.dev" download>Click here to download</a>


问:
Fetch data from Json array in rows and columns
I have this query to append the arrary in JSON:

```<code>DECLARE @TheTable table(TheJSON nvarchar(max), Condition int )
DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

SELECT TheJSON FROM @TheTable
</code>```

It gives me the output in 1 single Row:

```<code>[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"},{"id": 3, "name": "Three"}]
</code>```

Till this part it is correct.

Now I want to fetch the data from this table in rows and columns wise like a regular table:

```<code>ID  Name
1   One
2   Two
3   Three
</code>```

How to fetch the data from Json in rows and columns wise?

Any help would be appreciated

答:
```<code>DECLARE @TheTable table(TheJSON nvarchar(max), Condition int )
DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

SELECT @mystring =  TheJSON FROM @TheTable

SELECT  p.*
    FROM
    OPENJSON (@mystring, '$') WITH(id varchar(10) '$.id', name varchar (30) '$.name') p
</code>```

Body:
I have this query to append the arrary in JSON:

DECLARE @TheTable table(TheJSON nvarchar(max), Condition int )
DECLARE @mystring nvarchar(100)='{"id": 3, "name": "Three"}'

INSERT INTO @TheTable SELECT '[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"}]', 1

UPDATE @TheTable
SET TheJSON = JSON_MODIFY(TheJSON, 'append $', JSON_QUERY(N'{"id": 3, "name": "Three"}'))
WHERE Condition = 1;

SELECT TheJSON FROM @TheTable

It gives me the output in 1 single Row:

[{"id": 1, "name": "One"}, {"id": 2, "name": "Two"},{"id": 3, "name": "Three"}]

Till this part it is correct.

Now I want to fetch the data from this table in rows and columns wise like a regular table:

ID  Name
1   One
2   Two
3   Three

How to fetch the data from Json in rows and columns wise?

Any help would be appreciated


问:
Find which element of list is a key in a dictionary and what is it's value
I have a dictionary:

```<code>classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}
</code>```

and a list:

```<code>labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']
</code>```

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

```<code>class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])
</code>```

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

答:
To be for efficent check key on dict. </p>

```<code>#YOUR CODE
if k in self.classes_dictionary:
    #do_job

#More efficient
try:
    self.classes_dictionary[k]
    #do_job
except:
    #Key not in dict
    pass
</code>```

Body:
I have a dictionary:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}

and a list:

labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency

Body:
To be for efficent check key on dict.

#YOUR CODE
if k in self.classes_dictionary:
    #do_job

#More efficient
try:
    self.classes_dictionary[k]
    #do_job
except:
    #Key not in dict
    pass


问:
How to check iCloud free space
I want to upload my app data on iCloud but my iCloud storage has no space.
How can I check for that so I can show alert before start uploading?</p>

答:
To see how much you currently have,
1, Open the Settings app, select “iCloud”, and find where it says “Storage” to view how much space you have left in your iCloud account.
2, You can also view your available iCloud storage space by navigating to “General” > “Storage & iCloud Usage”.</p>

Title: How to check iCloud free space


问:
Trying to use FindView with a path
I'm trying to check if a couple of views exist by using paths. But the views cannot be found even if they do exist.

```<code>private string SelectFirstView(ControllerContext ctx, params string[] viewNames)
{
    return viewNames.First(view => ViewExists(ctx, view));
}

private bool ViewExists(ControllerContext ctx, string name)
{
    var result = ViewEngines.Engines.FindView(ctx, name, null);
    return result.View != null;
}
</code>```

And how I try to find the views:

```<code>var viewName = SelectFirstView(ctx, statusCodeName,
                               "~/Error/" + statusCodeName,
                               "~/Error/General",
                               "~/Shared/Error",
                               "Error");
</code>```

Note that "~/Shared/Error" and "Error" is the same view, but only the latter is found.

答:
When you are working with paths you need to specify the extension as well:

```<code>~/Error/General.cshtml
~/Shared/Error.cshtml
...
</code>```

When you don't specify a path you don't need the extension as in this case the view engine follows standard conventions to discover the views.

ContentLicense: CC BY-SA 3.0

Title: Trying to use FindView with a path

Body:
I'm trying to check if a couple of views exist by using paths. But the views cannot be found even if they do exist.

private string SelectFirstView(ControllerContext ctx, params string[] viewNames)
{
    return viewNames.First(view => ViewExists(ctx, view));
}

private bool ViewExists(ControllerContext ctx, string name)
{
    var result = ViewEngines.Engines.FindView(ctx, name, null);
    return result.View != null;
}

And how I try to find the views:

var viewName = SelectFirstView(ctx, statusCodeName,
                               "~/Error/" + statusCodeName,
                               "~/Error/General",
                               "~/Shared/Error",
                               "Error");

Note that "~/Shared/Error" and "Error" is the same view, but only the latter is found.

Body:
When you are working with paths you need to specify the extension as well:

~/Error/General.cshtml
~/Shared/Error.cshtml
...

When you don't specify a path you don't need the extension as in this case the view engine follows standard conventions to discover the views.


问:
How to set the opacity/alpha of a UIImage?
I know you can do this with a UIImageView, but can it be done to a UIImage?  I want to have the animation images array property of a UIImageView to be an array of the same image but with different opacities.  Thoughts?</p>

答:
same result as others, different style:</p>

```<code>extension UIImage {

    func withAlpha(_ alpha: CGFloat) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(at: .zero, blendMode: .normal, alpha: alpha)
        }
    }

}
</code>```

Body:
same result as others, different style:

extension UIImage {

    func withAlpha(_ alpha: CGFloat) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(at: .zero, blendMode: .normal, alpha: alpha)
        }
    }

}


问:
Xgboost throws an error when trying to import
I have a project that is using xgboost. We now transfer the project to containers.
But after installing it using pip, it throws the following error:

```<code>Traceback (most recent call last):
  File "restart_db.py", line 5, in <module>
    from autoai.core.providers import GlobalEnrichmentProvider
  File "/volumes/code/autoai/core/providers/__init__.py", line 1, in <module>
    from .files_providers import CsvProvider, TsvProvider, ExcelProvider, FileProvider
  File "/volumes/code/autoai/core/providers/files_providers.py", line 10, in <module>
    from .base import BaseProvider, BaseInMemoryProvider
  File "/volumes/code/autoai/core/providers/base.py", line 1, in <module>
    from autoai.models.dataset_connection import JoinTypes
  File "/volumes/code/autoai/models/__init__.py", line 5, in <module>
    from .classifier import Classifier
  File "/volumes/code/autoai/models/classifier.py", line 8, in <module>
    from eli5 import explain_prediction
  File "/volumes/dependencies/lib/python3.6/site-packages/eli5/__init__.py", line 53, in <module>
    from .xgboost import (
  File "/volumes/dependencies/lib/python3.6/site-packages/eli5/xgboost.py", line 9, in <module>
    from xgboost import (  # type: ignore
  File "/volumes/dependencies/lib/python3.6/site-packages/xgboost/__init__.py", line 11, in <module>
    from .core import DMatrix, Booster
  File "/volumes/dependencies/lib/python3.6/site-packages/xgboost/core.py", line 150, in <module>
    _LIB = _load_lib()
  File "/volumes/dependencies/lib/python3.6/site-packages/xgboost/core.py", line 141, in _load_lib
    'Error message(s): {}\n'.format(os_error_list))
xgboost.core.XGBoostError: XGBoost Library (libxgboost.so) could not be loaded.
Likely causes:
  * OpenMP runtime is not installed (vcomp140.dll or libgomp-1.dll for Windows, libgomp.so for UNIX-like OSes)
  * You are running 32-bit Python on a 64-bit OS
Error message(s): ['libgomp.so.1: cannot open shared object file: No such file or directory']
</code>```

I checked that both my python and my ubuntu are 64-bit, and ran:
apt-get update && apt-get install -y libaio1

To make sure that package is there (I read it somewhere that this might be the problem) - but it still throws the same error.

I've been stuck on this for a while now and will appreciate any help.

答:
I had this issue while creating Docker image of my project.

I have used the command below:

```<code>RUN apt-get update && \

     apt-get -y --no-install-recommends install \

     libgomp1
</code>```

Body:
I have a project that is using xgboost. We now transfer the project to containers.
But after installing it using pip, it throws the following error:

Traceback (most recent call last):
  File "restart_db.py", line 5, in <module>
    from autoai.core.providers import GlobalEnrichmentProvider
  File "/volumes/code/autoai/core/providers/__init__.py", line 1, in <module>
    from .files_providers import CsvProvider, TsvProvider, ExcelProvider, FileProvider
  File "/volumes/code/autoai/core/providers/files_providers.py", line 10, in <module>
    from .base import BaseProvider, BaseInMemoryProvider
  File "/volumes/code/autoai/core/providers/base.py", line 1, in <module>
    from autoai.models.dataset_connection import JoinTypes
  File "/volumes/code/autoai/models/__init__.py", line 5, in <module>
    from .classifier import Classifier
  File "/volumes/code/autoai/models/classifier.py", line 8, in <module>
    from eli5 import explain_prediction
  File "/volumes/dependencies/lib/python3.6/site-packages/eli5/__init__.py", line 53, in <module>
    from .xgboost import (
  File "/volumes/dependencies/lib/python3.6/site-packages/eli5/xgboost.py", line 9, in <module>
    from xgboost import (  # type: ignore
  File "/volumes/dependencies/lib/python3.6/site-packages/xgboost/__init__.py", line 11, in <module>
    from .core import DMatrix, Booster
  File "/volumes/dependencies/lib/python3.6/site-packages/xgboost/core.py", line 150, in <module>
    _LIB = _load_lib()
  File "/volumes/dependencies/lib/python3.6/site-packages/xgboost/core.py", line 141, in _load_lib
    'Error message(s): {}\n'.format(os_error_list))
xgboost.core.XGBoostError: XGBoost Library (libxgboost.so) could not be loaded.
Likely causes:
  * OpenMP runtime is not installed (vcomp140.dll or libgomp-1.dll for Windows, libgomp.so for UNIX-like OSes)
  * You are running 32-bit Python on a 64-bit OS
Error message(s): ['libgomp.so.1: cannot open shared object file: No such file or directory']

I checked that both my python and my ubuntu are 64-bit, and ran:
apt-get update && apt-get install -y libaio1

To make sure that package is there (I read it somewhere that this might be the problem) - but it still throws the same error.

I've been stuck on this for a while now and will appreciate any help.

Body:
I had this issue while creating Docker image of my project.

I have used the command below:

RUN apt-get update && \

     apt-get -y --no-install-recommends install \

     libgomp1


问:
Get top n counted rows in table within group [MySQL]
I'm trying to get just top 3 selling products grouped within categories (just top 3 products by occurrence in transactions (id) count(id) by each category). I was searching a lot for possible solution but with no result. It looks like it is a bit tricky in MySQL since one can't simply use top() function and so on. Sample data structure bellow:

```<code>+--------+------------+-----------+
|     id |category_id | product_id|
+--------+------------+-----------+
| 1      | 10         | 32        |
| 2      | 10         | 34        |
| 3      | 10         | 32        |
| 4      | 10         | 21        |
| 5      | 10         | 100       |
| 6      | 7          | 101       |
| 7      | 7          | 39        |
| 8      | 7          | 41        |
| 9      | 7          | 39        |
+--------+------------+-----------+
</code>```

答:
In earlier versions of MySQL, I would recommend using variables:</p>

```<code>select cp.*
from (select cp.*,
             (@rn := if(@c = category_id, @rn + 1,
                        if(@c := category_id, 1, 1)
                       )
             ) as rn
      from (select category_id, product_id, count(*) as cnt
            from mytable
            group by category_id, product_id
            order by category_id, count(*) desc
           ) cp cross join
           (select @c := -1, @rn := 0) params
     ) cp
where rn <= 3;
</code>```

Body:
I'm trying to get just top 3 selling products grouped within categories (just top 3 products by occurrence in transactions (id) count(id) by each category). I was searching a lot for possible solution but with no result. It looks like it is a bit tricky in MySQL since one can't simply use top() function and so on. Sample data structure bellow:

+--------+------------+-----------+
|     id |category_id | product_id|
+--------+------------+-----------+
| 1      | 10         | 32        |
| 2      | 10         | 34        |
| 3      | 10         | 32        |
| 4      | 10         | 21        |
| 5      | 10         | 100       |
| 6      | 7          | 101       |
| 7      | 7          | 39        |
| 8      | 7          | 41        |
| 9      | 7          | 39        |
+--------+------------+-----------+

Body:
In earlier versions of MySQL, I would recommend using variables:

select cp.*
from (select cp.*,
             (@rn := if(@c = category_id, @rn + 1,
                        if(@c := category_id, 1, 1)
                       )
             ) as rn
      from (select category_id, product_id, count(*) as cnt
            from mytable
            group by category_id, product_id
            order by category_id, count(*) desc
           ) cp cross join
           (select @c := -1, @rn := 0) params
     ) cp
where rn <= 3;


问:
Ticker should not execute if already running
I have some function that has to run periodically. I have used a ticker for this. But if the ticker is already running, and the time interval passes again, it should not execute again.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(3*time.Second)
    flag := 0
    defer ticker.Stop()
    for {
        select {
        case t := <-ticker.C:
            flag = flag + 1
            if (flag % 2 ==0 ) {
                time.Sleep(time.Second*4)
            }
            fmt.Println("Current time: ", t)
        }
    }
}
</code>```

https://play.golang.org/p/2xV2MYInn4I

In the playground, the ticker prints every 3 seconds, but every even turn of the ticker the job takes more time than the interval. I expect it to not run then and drop those ticks.

How do I do this?

答:
sleeping inside the same goroutine merely delays execution. ticker meanwhile runs in a separate goroutine. So even if you used a global variable to maintain an execution state - it will not give you your desired result with sleep. However migrating the whole "sleeping" in a separate goroutine yields:

```<code>package main

import (
    "fmt"
    "time"
)

type Tick struct {
    ticker *time.Ticker
    executing bool
}

func somethingYouWantToDo(tick *Tick, flag *int, t time.Time) {
    if tick.executing {
        return
    }

    tick.executing = true

    *flag = *flag + 1

    if (*flag % 2 ==0 ) {
                time.Sleep(time.Second*4)
    }
        fmt.Println("Current time: ", t)
    tick.executing = false
}

func main() {
    tick := &Tick{
        ticker: time.NewTicker(3*time.Second),
    }
    flag := 0
    defer tick.ticker.Stop()
    for {
        select {
        case t := <-tick.ticker.C:
            go somethingYouWantToDo(tick, &flag, t)
        }
    }
}
// output
// Current time:  2009-11-10 23:00:03 +0000 UTC m=+3.000000001
// Current time:  2009-11-10 23:00:06 +0000 UTC m=+6.000000001
// Current time:  2009-11-10 23:00:12 +0000 UTC m=+12.000000001
// Current time:  2009-11-10 23:00:15 +0000 UTC m=+15.000000001
// Current time:  2009-11-10 23:00:21 +0000 UTC m=+21.000000001
// Current time:  2009-11-10 23:00:24 +0000 UTC m=+24.000000001
// Current time:  2009-11-10 23:00:30 +0000 UTC m=+30.000000001
// Current time:  2009-11-10 23:00:33 +0000 UTC m=+33.000000001
// Current time:  2009-11-10 23:00:39 +0000 UTC m=+39.000000001
// Current time:  2009-11-10 23:00:42 +0000 UTC m=+42.000000001
// Current time:  2009-11-10 23:00:48 +0000 UTC m=+48.000000001
// Current time:  2009-11-10 23:00:51 +0000 UTC m=+51.000000001
// Current time:  2009-11-10 23:00:57 +0000 UTC m=+57.000000001
// Current time:  2009-11-10 23:01:00 +0000 UTC m=+60.000000001
// Current time:  2009-11-10 23:01:06 +0000 UTC m=+66.000000001
// Current time:  2009-11-10 23:01:09 +0000 UTC m=+69.000000001
</code>```

Try it on the playground

Body:
I have some function that has to run periodically. I have used a ticker for this. But if the ticker is already running, and the time interval passes again, it should not execute again.

package main

import (
    "fmt"
    "time"
)

func main() {
    ticker := time.NewTicker(3*time.Second)
    flag := 0
    defer ticker.Stop()
    for {
        select {
        case t := <-ticker.C:
            flag = flag + 1
            if (flag % 2 ==0 ) {
                time.Sleep(time.Second*4)
            }
            fmt.Println("Current time: ", t)
        }
    }
}

https://play.golang.org/p/2xV2MYInn4I

In the playground, the ticker prints every 3 seconds, but every even turn of the ticker the job takes more time than the interval. I expect it to not run then and drop those ticks.

How do I do this?

Body:
sleeping inside the same goroutine merely delays execution. ticker meanwhile runs in a separate goroutine. So even if you used a global variable to maintain an execution state - it will not give you your desired result with sleep. However migrating the whole "sleeping" in a separate goroutine yields:

package main

import (
    "fmt"
    "time"
)

type Tick struct {
    ticker *time.Ticker
    executing bool
}

func somethingYouWantToDo(tick *Tick, flag *int, t time.Time) {
    if tick.executing {
        return
    }

    tick.executing = true

    *flag = *flag + 1

    if (*flag % 2 ==0 ) {
                time.Sleep(time.Second*4)
    }
        fmt.Println("Current time: ", t)
    tick.executing = false
}

func main() {
    tick := &Tick{
        ticker: time.NewTicker(3*time.Second),
    }
    flag := 0
    defer tick.ticker.Stop()
    for {
        select {
        case t := <-tick.ticker.C:
            go somethingYouWantToDo(tick, &flag, t)
        }
    }
}
// output
// Current time:  2009-11-10 23:00:03 +0000 UTC m=+3.000000001
// Current time:  2009-11-10 23:00:06 +0000 UTC m=+6.000000001
// Current time:  2009-11-10 23:00:12 +0000 UTC m=+12.000000001
// Current time:  2009-11-10 23:00:15 +0000 UTC m=+15.000000001
// Current time:  2009-11-10 23:00:21 +0000 UTC m=+21.000000001
// Current time:  2009-11-10 23:00:24 +0000 UTC m=+24.000000001
// Current time:  2009-11-10 23:00:30 +0000 UTC m=+30.000000001
// Current time:  2009-11-10 23:00:33 +0000 UTC m=+33.000000001
// Current time:  2009-11-10 23:00:39 +0000 UTC m=+39.000000001
// Current time:  2009-11-10 23:00:42 +0000 UTC m=+42.000000001
// Current time:  2009-11-10 23:00:48 +0000 UTC m=+48.000000001
// Current time:  2009-11-10 23:00:51 +0000 UTC m=+51.000000001
// Current time:  2009-11-10 23:00:57 +0000 UTC m=+57.000000001
// Current time:  2009-11-10 23:01:00 +0000 UTC m=+60.000000001
// Current time:  2009-11-10 23:01:06 +0000 UTC m=+66.000000001
// Current time:  2009-11-10 23:01:09 +0000 UTC m=+69.000000001

Try it on the playground


问:
Asp.net MVC Core giving null checkbox data instead of all selected checkboxes on HTTPPost
I am trying to bind list of checkboxes.On Post Model showng the value of Job_Type as 0  .It should return all selected checkboxes.Which in my case not doing so .After hours of searching I havn't found any solution.

This is the relevent part of code in my view

```<code> <div class="form-group">
                    @foreach (var item in Model.Job_Type)
                    {
                        <input name="Job_Type" value="@item.valID" type="checkbox" checked="@item.IsChecked"/>
                        @item.text <br/>
                    }

                </div>
</code>```

My Controller:

```<code>  // GET: Jobs/Create
        public IActionResult Create()
        {
            NewJob newJob = new NewJob();
            List<CheckBoxModel> chkVisatype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1, text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
                new CheckBoxModel {valID=1,text="dd",IsChecked=true },
            };
            List<CheckBoxModel> chkJobtype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1,text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="tt",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
            };
            newJob.Job_Type = chkJobtype;
            newJob.Visa_Type = chkVisatype;
            return View(newJob);
        }

        // POST: Jobs/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("JobID,Job_Title,AddedDate,Primary_Technology,MPTJob_Length,MPTJobLengthSelection,SPTJob_Length,SPTJobLengthSelection,Job_Length,JobLengthSelection,Secondary_Technology,Description,PossibiltyForExtenshion,Email,CC_Email,URL,City,State,Country,ZipCode,Employment_Type,Job_Type,Compensation,JobExperienceLevel,Visa_Type")] NewJob newJob)
        {
            if (ModelState.IsValid)
            {
                newJob.AddedDate = DateTime.Now;
                _context.Add(newJob);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(newJob);
        }
</code>```

My Model:

```<code>
 public class CheckBoxModel
    {
        [Key]
        public int valID { get; set; }
        public string text { get; set; }
        public bool IsChecked { get; set; }
    }
 public class NewJob
    {

public List<CheckBoxModel> Job_Type { get; set; }
 }
</code>```

答:
Well I tired this and it works for me.

All we need to understand how checkboxes post their data. if they have a name attribute, when checked, they post name=value.If you want to get  complete list posted back it would be:

```<code>@for (int i = 0; i < Model.Job_Type.Count(); i++)
{
    <input hidden asp-for="Job_Type[i].valID" />
    <input hidden asp-for="Job_Type[i].text" />
    <input asp-for="Job_Type[i].IsChecked" type="checkbox" />
    @Model.Job_Type[i].text<br />
}
</code>```

Body:
I am trying to bind list of checkboxes.On Post Model showng the value of Job_Type as 0  .It should return all selected checkboxes.Which in my case not doing so .After hours of searching I havn't found any solution.

This is the relevent part of code in my view

                    @foreach (var item in Model.Job_Type)
                    {
                        <input name="Job_Type" value="@item.valID" type="checkbox" checked="@item.IsChecked"/>
                        @item.text

                    }

My Controller:

  // GET: Jobs/Create
        public IActionResult Create()
        {
            NewJob newJob = new NewJob();
            List<CheckBoxModel> chkVisatype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1, text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
                new CheckBoxModel {valID=1,text="dd",IsChecked=true },
            };
            List<CheckBoxModel> chkJobtype = new List<CheckBoxModel>()
            {
                new CheckBoxModel {valID=1,text="ASp",IsChecked=true },
                new CheckBoxModel {valID=1,text="tt",IsChecked=true },
                new CheckBoxModel {valID=1,text="ss",IsChecked=true },
                new CheckBoxModel {valID=1,text="aa",IsChecked=true },
            };
            newJob.Job_Type = chkJobtype;
            newJob.Visa_Type = chkVisatype;
            return View(newJob);
        }

        // POST: Jobs/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("JobID,Job_Title,AddedDate,Primary_Technology,MPTJob_Length,MPTJobLengthSelection,SPTJob_Length,SPTJobLengthSelection,Job_Length,JobLengthSelection,Secondary_Technology,Description,PossibiltyForExtenshion,Email,CC_Email,URL,City,State,Country,ZipCode,Employment_Type,Job_Type,Compensation,JobExperienceLevel,Visa_Type")] NewJob newJob)
        {
            if (ModelState.IsValid)
            {
                newJob.AddedDate = DateTime.Now;
                _context.Add(newJob);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(newJob);
        }

My Model:

 public class CheckBoxModel
    {
        [Key]
        public int valID { get; set; }
        public string text { get; set; }
        public bool IsChecked { get; set; }
    }
 public class NewJob
    {

public List<CheckBoxModel> Job_Type { get; set; }
 }

Body:
Well I tired this and it works for me.

All we need to understand how checkboxes post their data. if they have a name attribute, when checked, they post name=value.If you want to get  complete list posted back it would be:

@for (int i = 0; i < Model.Job_Type.Count(); i++)
{
    <input hidden asp-for="Job_Type[i].valID" />
    <input hidden asp-for="Job_Type[i].text" />
    <input asp-for="Job_Type[i].IsChecked" type="checkbox" />
    @Model.Job_Type[i].text<br />
}


问:
Access express response data client side
In my express router I check if the data inserted on a form are valid then if they are I render another page passing form data. I would like to access the data I pass client-side. On the chat.ejs view I have a chatroom.js client file, I want to access the data there without having to access them in a script tag.
I thought about using Ajax but the only answer I found here on StackOverflow was marked as wrong, so how do I go about that?

router.js

```<code>module.exports=function(app) {
    const express = require('express');
    const router = express.Router();
    const {check, validationResult} = require('express-validator');
    const {matchedData} = require('express-validator/filter');

    router.get('/', (req, res) => {
        res.render('index', {
            data: {},
            errors: {}
        })
    });

    router.post('/enter', [
        check('username')
            .isLength({min: 1})
            .withMessage('Username is required').trim(),
        check('room')//implement personalized check
    ], (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.render('index', {
                data: req.body,
                errors: errors.mapped()
            })
        }
        else {
            const data = matchedData(req);

            return res.render('chat',{
                user: data.username,
                room:data.room
            })

        }
    });

    return router;

    //MOVE TO SUPPORT
    function find(name) {
        return 1;
    }

}

</code>```

there is really nothing client-side so far so It seems useless just posting my views. Alternatively, I could use Ajax on client.ejs to handle the form submission but I would like to keep this clean and handle the routing with the router file.

答:
I ended up creating two global variables in a script tag for my index.ejs page like this

```<code>  <script>
    var user = <%- JSON.stringify( user ) %>
    var room = <%- JSON.stringify(room)%>;
</script>
</code>```

and then I could access them in the chatroom.js file linked below

Body:
In my express router I check if the data inserted on a form are valid then if they are I render another page passing form data. I would like to access the data I pass client-side. On the chat.ejs view I have a chatroom.js client file, I want to access the data there without having to access them in a script tag.
I thought about using Ajax but the only answer I found here on StackOverflow was marked as wrong, so how do I go about that?

router.js

module.exports=function(app) {
    const express = require('express');
    const router = express.Router();
    const {check, validationResult} = require('express-validator');
    const {matchedData} = require('express-validator/filter');

    router.get('/', (req, res) => {
        res.render('index', {
            data: {},
            errors: {}
        })
    });

    router.post('/enter', [
        check('username')
            .isLength({min: 1})
            .withMessage('Username is required').trim(),
        check('room')//implement personalized check
    ], (req, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.render('index', {
                data: req.body,
                errors: errors.mapped()
            })
        }
        else {
            const data = matchedData(req);

            return res.render('chat',{
                user: data.username,
                room:data.room
            })

        }
    });

    return router;

    //MOVE TO SUPPORT
    function find(name) {
        return 1;
    }

}

there is really nothing client-side so far so It seems useless just posting my views. Alternatively, I could use Ajax on client.ejs to handle the form submission but I would like to keep this clean and handle the routing with the router file.

Body:
I ended up creating two global variables in a script tag for my index.ejs page like this

  <script>
    var user = <%- JSON.stringify( user ) %>
    var room = <%- JSON.stringify(room)%>;
</script>

and then I could access them in the chatroom.js file linked below


问:
Compare the colnames within two lists of data.frames?
I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.

It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.

Input lists

```<code>> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7
</code>```

Desired output

I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.

```<code>$A
  b
1 3
$B
  e
1 1
$C
  f
1 6
</code>```

My attempts

I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?

```<code>## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]
</code>```

答:
You can just apply a function to subset a data.frame based on columns in another, and ensure it always return a data.frame using drop = F. And make sure to use SIMPLIFY = F in mapply so it always returns the list structure.

mapply(function(x,y) x[,-which(names(x) %in% names(y)), drop = F], list1, list2, SIMPLIFY = F)
#> $A
#>   b
#> 1 3
#>
#> $B
#>   e
#> 1 1
#>
#> $C
#>   f
#> 1 6
```

Body:
I am using a function that drops various columns from each data.frame in a list when those variables do not meet certain criteria, and I would like a convenient way to see which columns have been dropped. The real-world data.frames will have 1000s of varied colnames, with some overlap in those names.

It this simplified example, I would like to get a list that shows the variables of each data.frame that exist in list1 but which are absent in list2.

Input lists

> list1
$A
  a b
1 2 3
$B
  c d e
1 9 8 1
$C
  f g
1 6 7

> list2
$A
  a
1 2
$B
  c d
1 9 8
$C
  g
1 7

Desired output

I'd like to keep the list structure, so that I see which columns were dropped from each data.frame.

$A
  b
1 3
$B
  e
1 1
$C
  f
1 6

My attempts

I've looked on SO, but have only found solutions that pertain to comparing data.frames. Keep in mind the names of the list elements (here A, B and C) will always be the same in the lists. My idea has been to use setdiff , or setdiff with mapply, but my tinkering has not been fruitful. What can be done?

## sample data
list1 <- list(A=data.frame(a=2, b=3), B=data.frame(c=9,d=8,e=1), C=data.frame(f= 6,g=7))
list2 <- list(A=data.frame(a=2), B=data.frame(c=9,d=8), C=data.frame(g=7))
desired_output <- list(A=data.frame(b=3), B=data.frame(e=1), C=data.frame(f= 6))

## attempts

# gives List 1
setdiff(list1, list2)

# gives 'Error: not compatible: Cols in x but not y: `b`.'
mapply(setdiff, x = list1, y = list2)

# gives 'Error in list1[[i]] : recursive indexing failed at level 3'
mapply(setdiff, x = colnames(list1[[i]]), y = colnames(list2[[i]]))

# gives 'list()'
mapply(setdiff, x = colnames(list1[i]), y = colnames(list2[i]))

# Gives 'Error in list1[colnams] : invalid subscript type 'list''
colnams <- list()
for(i in seq_along(list1)){
   colnams[i] <- !colnames(list1[[i]]) %in% colnames(list2[[i]])
}
list1[colnams]


问:
How to clear all filters in react-table
I am using react-table v7 (https://www.npmjs.com/package/react-table) . I am able to filter the data (referred from https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering ) and I am using SelectColumnFilter function for all the columns to filter . I would like to create a button which will reset all the filters. Like If I have applied filters to 4 columns by clicking on the RESET ALL button I want all the filters to be cleared. Can someone please help me with this ?
Thank you </p>

答:
You can get the setAllFilters method from useTable instance, and then

```<code>const { ...setAllFilters } = useTable({ columns, data }, userFilters)

// somewhere at you code
<button onClick={() => setAllFilters([])}>Reset</button>
</code>```

checkout setAllFilters at https://github.com/tannerlinsley/react-table/blob/master/docs/api/useFilters.md

Title: How to clear all filters in react-table

Body:
You can get the setAllFilters method from useTable instance, and then

const { ...setAllFilters } = useTable({ columns, data }, userFilters)

// somewhere at you code
<button onClick={() => setAllFilters([])}>Reset</button>

checkout setAllFilters at https://github.com/tannerlinsley/react-table/blob/master/docs/api/useFilters.md


问:
Border color on default input style
here's a tricky question...

I have default styled input fields (no css added, just width/height/padding), but now I want to give it a red border (error style). How can I do this? Just setting border will delete the default style of the input, setting only border-color will look weird, setting an outline will work in some cases (and doesn't look so good in Firefox).

Any tips?

EDIT: Come on guys read the question before answering. I want the browser default look of the input, I just want to give it a red border.

答:
You can use jquery for this by utilizing addClass() method

CSS

```<code> .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>
</code>```

Jquery Code

```<code>$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});
</code>```

Update:
 You can remove that error class using

```<code>$('.defaultInput').removeClass('error');
</code>```

It won't remove that default style. It will remove .error class only

Title: Border color on default input style

Body:
You can use jquery for this by utilizing addClass() method

CSS

 .defaultInput
    {
     width: 100px;
     height:25px;
     padding: 5px;
    }

.error
{
 border:1px solid red;
}

<input type="text" class="defaultInput"/>

Jquery Code

$(document).ready({
  $('.defaultInput').focus(function(){
       $(this).addClass('error');
  });
});

Update:
 You can remove that error class using

$('.defaultInput').removeClass('error');

It won't remove that default style. It will remove .error class only


问:
matching consecutive pairs in pd.Series
I have a DataFrame which looks like this :-

```<code>ID | act
 1    A
 1    B
 1    C
 1    D
 2    A
 2    B
 3    A
 3    C
</code>```

I am trying to get the IDs where an activity act1 is followed by another act2, for example, A is followed by B. In that case, I want to get [1,2] as the ids. How do I go about this in a vectorized manner?

Edit :- Expected output : For the sample df defined above, the output should be a list/Series of all the IDs where A is followed immediately by B

```<code>IDs
 1
 2
</code>```

答:
Here is one approach: groupby, and don't sort, since we need to track B immediately following A, based on the current dataframe structure.

Next aggregate using str.cat

 check if A,B is present

 get the index

 pass as a list

```<code>(df
.groupby('ID',sort=False)
.Act
.agg(lambda x: x.str.cat(sep=','))
.str.contains('A,B')
.loc[lambda x: x==1]
.index.tolist()
 )

 [1, 2]
</code>```

Another approach is using the shift function and filtering:

```<code>df['x'] = df.Act.shift()

df.loc[lambda x: (x['Act']=='B') & (x['x']=='A')].ID
</code>```

Title: matching consecutive pairs in pd.Series

Body:
I have a DataFrame which looks like this :-

ID | act
 1    A
 1    B
 1    C
 1    D
 2    A
 2    B
 3    A
 3    C

I am trying to get the IDs where an activity act1 is followed by another act2, for example, A is followed by B. In that case, I want to get [1,2] as the ids. How do I go about this in a vectorized manner?

Edit :- Expected output : For the sample df defined above, the output should be a list/Series of all the IDs where A is followed immediately by B

IDs
 1
 2

Body:
Here is one approach: groupby, and don't sort, since we need to track B immediately following A, based on the current dataframe structure.

Next aggregate using str.cat

 check if A,B is present

 get the index

 pass as a list

(df
.groupby('ID',sort=False)
.Act
.agg(lambda x: x.str.cat(sep=','))
.str.contains('A,B')
.loc[lambda x: x==1]
.index.tolist()
 )

 [1, 2]

Another approach is using the shift function and filtering:

df['x'] = df.Act.shift()

df.loc[lambda x: (x['Act']=='B') & (x['x']=='A')].ID


问:
AspNetCore Httpsys configure useURLS from webapi Appsettings file
I am building a AspNetCore webapi application for internal corporate use and I need to enable Windows Authentication.

So I am creating a httpsys server to listen at a specific endpoint:

```<code>    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .UseHttpSys(options =>
                {
                    options.Authentication.Schemes =
                            AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                    options.Authentication.AllowAnonymous = true;
                    options.UrlPrefixes.Add("http://localhost:16000");
                }).UseUrls("http://localhost:16000");
</code>```

so while this obviously works fine, I want to be able to configure it in the config file.

Earlier in the project I was using Kestrel, so I just added these settings to the   application config:

```<code>"Kestrel": {
   "EndPoints": {
     "HttpsInlineCertStore": {
       "Url": "https://*:16000",
        "Certificate": {
          "Subject": "localhost",
          "Store": "My",
          "Location": "LocalMachine",
          "AllowInvalid": "true"
        }
    } ...
</code>```

Now I understand perfectly that HttpSYS can be configured by the registry etc, so I am not interested in those kinds of responses.

My Specific question is:  For a NetCoreApi web api application, is it possible to use the IConfiguration inside the (static) CreateWebHostBuilder method?

I am injecting the IConfiguration into the startup class, but it appears the limitation is in the framework preventing access to it in the CreateWebHostBuilder method.  Have I missed something?

答:
For a NetCoreApi web api application, is it possible to use the
  IConfiguration inside the (static) CreateWebHostBuilder method?

Yes, you will be able to access it inside ConfigureServices, which is enough to make your configurations. The overloaded of UseHttpSys actually does the exact same thing.

So basically you just have to configure your HttpSysOptions.

For netcoreapp2.1 :

```<code>public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseHttpSys()
        .ConfigureServices((context, services) =>
        {
            // Option 1. Set options manually.
            services.Configure<HttpSysOptions>(options =>
            {
                // Use context.Configuration to access your config.
                var url = context.Configuration.GetSection("MySection")["Url"];
                options.UrlPrefixes.Add(url);
            });

            // Option 2. Build options from settings.
            services.Configure<HttpSysOptions>(context.Configuration.GetSection("WebSys"));
        });
</code>```

For netcoreapp3.1:

```<code>    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.ConfigureServices((context, services) =>
                {
                    // Option 1. Set options manually.
                    services.Configure<HttpSysOptions>(options =>
                    {
                        // Use context.Configuration to access your config.
                        var url = context.Configuration.GetSection("MySection")["Url"];
                        options.UrlPrefixes.Add(url);
                    });

                    // Option 2. Build options from settings.
                    services.Configure<HttpSysOptions>(context.Configuration.GetSection("HttpSys"));
                });
                webBuilder.UseHttpSys(options =>
                {
                    // Verify that your options is correct here.
                });
            });
</code>```

In case you want to use option 2, your appsettings.json should look something like this:

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "HttpSys": {
    "AllowSynchronousIO": false,
    "RequestQueueLimit": 2,
    "MaxAccepts": 3
  },
  "AllowedHosts": "*"
}
</code>```

Note that the property UrlPrefixes in HttpSysOptions is a rather complex object, so I'm not sure if you will be able to serialize it correctly from appsettings. However, you can simply set the field as urls in your config, as mentioned here. Then HttpSys will pick it up as long as your Configuration is correct.

```<code> {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "urls": "http://*:5005;",
  "HttpSys": {
    "AllowSynchronousIO": false,
    "RequestQueueLimit": 2,
    "MaxAccepts": 3
  },
  "AllowedHosts": "*"
 }
</code>```

Body:
I am building a AspNetCore webapi application for internal corporate use and I need to enable Windows Authentication.

So I am creating a httpsys server to listen at a specific endpoint:

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .UseHttpSys(options =>
                {
                    options.Authentication.Schemes =
                            AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                    options.Authentication.AllowAnonymous = true;
                    options.UrlPrefixes.Add("http://localhost:16000");
                }).UseUrls("http://localhost:16000");

so while this obviously works fine, I want to be able to configure it in the config file.

Earlier in the project I was using Kestrel, so I just added these settings to the   application config:

"Kestrel": {
   "EndPoints": {
     "HttpsInlineCertStore": {
       "Url": "https://*:16000",
        "Certificate": {
          "Subject": "localhost",
          "Store": "My",
          "Location": "LocalMachine",
          "AllowInvalid": "true"
        }
    } ...

Now I understand perfectly that HttpSYS can be configured by the registry etc, so I am not interested in those kinds of responses.

My Specific question is:  For a NetCoreApi web api application, is it possible to use the IConfiguration inside the (static) CreateWebHostBuilder method?

I am injecting the IConfiguration into the startup class, but it appears the limitation is in the framework preventing access to it in the CreateWebHostBuilder method.  Have I missed something?

Body:
For a NetCoreApi web api application, is it possible to use the
  IConfiguration inside the (static) CreateWebHostBuilder method?

Yes, you will be able to access it inside ConfigureServices, which is enough to make your configurations. The overloaded of UseHttpSys actually does the exact same thing.

So basically you just have to configure your HttpSysOptions.

For netcoreapp2.1 :

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseHttpSys()
        .ConfigureServices((context, services) =>
        {
            // Option 1. Set options manually.
            services.Configure<HttpSysOptions>(options =>
            {
                // Use context.Configuration to access your config.
                var url = context.Configuration.GetSection("MySection")["Url"];
                options.UrlPrefixes.Add(url);
            });

            // Option 2. Build options from settings.
            services.Configure<HttpSysOptions>(context.Configuration.GetSection("WebSys"));
        });

For netcoreapp3.1:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                webBuilder.ConfigureServices((context, services) =>
                {
                    // Option 1. Set options manually.
                    services.Configure<HttpSysOptions>(options =>
                    {
                        // Use context.Configuration to access your config.
                        var url = context.Configuration.GetSection("MySection")["Url"];
                        options.UrlPrefixes.Add(url);
                    });

                    // Option 2. Build options from settings.
                    services.Configure<HttpSysOptions>(context.Configuration.GetSection("HttpSys"));
                });
                webBuilder.UseHttpSys(options =>
                {
                    // Verify that your options is correct here.
                });
            });

In case you want to use option 2, your appsettings.json should look something like this:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "HttpSys": {
    "AllowSynchronousIO": false,
    "RequestQueueLimit": 2,
    "MaxAccepts": 3
  },
  "AllowedHosts": "*"
}

Note that the property UrlPrefixes in HttpSysOptions is a rather complex object, so I'm not sure if you will be able to serialize it correctly from appsettings. However, you can simply set the field as urls in your config, as mentioned here. Then HttpSys will pick it up as long as your Configuration is correct.

 {
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "urls": "http://*:5005;",
  "HttpSys": {
    "AllowSynchronousIO": false,
    "RequestQueueLimit": 2,
    "MaxAccepts": 3
  },
  "AllowedHosts": "*"
 }


问:
Java priority queue
Java's priority queue is a data structure with O(log n) complexity for put (insertion) and O(log n) for poll (retrieval and removal of the min element).

C++ STL's multimap has the same functionality but O(1) complexity for retrieval and removal of the min element (begin and erase). Is there an equivalent in Java ?

答:
First, I'd check that C++'s multimap actually does give O(1) for removing the min element. The most common structures for sotred maps/priority queues are tree structures in which querying the min element has O(1) complexity, but removing it is O(log n).

That said, I think that a skip list (as implemented by Java's ConcurrentSkipListMap) might give you O(1) for removal of the minimum element, but I'm not absolutely sure. One of the problems when assessing performance of ConcurrentSkipListMap is that traversal operations "tidy up" markers left by previous deletions. So the complexity of an operation can actually depend on what the previous operations were. (On the other hand, at some level, that's true of pretty much any algorithm: whether some data is in the CPU cache can depend on whether a previous operation put it there...)

P.S. Forgot to say: look at ConcurrentSkipListMap.pollFirstEntry().

OwnerDisplayName: Helltone

Title: Java priority queue

OwnerDisplayName: Neil Coffey


问:
Image Uploader in React by merging an object and DataForm file

I’ve been struggling to find a solution to upload an image and store it in the database.

Tried them all:  Dropzone, react-dropzone, react-uploader, etc.....

The BackEnd API is expecting this:

```<code>{
  "course": {
    "title": "Hic et velit sed.",
    "subtitle": "Omnis quibusdam illum itaque.",
    "description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
    "end_date": "2020-02-01",
    "attachment_attributes": {
      "file": {
        --- here the uploaded data file ---
      }
    }
  }
}
</code>```

My component is now only written with 1 input type=file to speed up this testing. The API requirements such as title, subtitle etc., will be hardcoded.

Here the component:

```<code>import React, { Component } from 'react';
import api from '../../../../helpers/API';

class Uploader extends Component {
  constructor(props) {
    super(props);
      this.state = {
        selectedFile: null
      }
  }
  onChangeHandler = event => {
    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0,
    })
  }

  onClickHandler = () => {

   ** HARDCODED API REQUIREMENT**
   const body = "course": {
      "title": "Hic et velit sed.",
      "subtitle": "Omnis quibusdam illum itaque.",
      "description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
      "end_date": "2020-02-01",
      "attachment_attributes": {
        "file": {
          --- here the uploaded file data ---
        }
      }
    }

   ** THIS SHOULD HANDLE THE UPLOADED FILE DATA FORMAT **
    const data = new FormData()
    data.append('file', this.state.selectedFile)

    return api
      .post("http://localhost:3000/api/v1/files", ??????). <— DATA or BODY?
      .then(res => {
        console.log(res.statusText)
      })
      .catch(res => console.log('error ==> ', res))
  }

  render() {
    return (
      <>
        <div>
          <label>Upload Your File </label>
          <input
            type="file"
            multiple onChange={this.onChangeHandler}/>
        </div>
        <button type="button" className="btn btn-success btn-block" onClick={this.onClickHandler}>Upload</button>
      </>
    )
  }
}

export default Uploader
</code>```

Issue

If I pass DATA, in the API call, the uploaded file get nicely stored in the Browser > Network > Header > Data Form section, as file: binary

And that is good.

But I need to pass the uploaded file as part of my BODY object. So, below is what I did, but it gets returned empty:

```<code>onClickHandler = () => {
    const data = new FormData()
    data.append('file', this.state.selectedFile)

    const body = {
      "course": {
        "title": "Hic et velit sed.",
        "subtitle": "Omnis quibusdam illum itaque.",
        "description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
        "end_date": "2020-02-01",
        "attachment_attributes": {
          "file": data  <-- trying to pass the uploaded DataForm here
        }
      }
    }

    return api
      .post("http://localhost:3000/api/v1/files", body)
      .then(res => {
        console.log(res.statusText)
      })
      .catch(res => console.log('error ==> ', res))
  }
</code>```

Unfortunately I get 422 error, {"errors":{"attachment.file":["blank"]}}

Any help is much appreciated. Thanks

Jow

答:
OK, found the way.

It's impossible to call the DataForm of the uploaded file from the Object BODY.

What it needs to be done is to data.append each single item in the object.

Here the file:

```<code>const data = new FormData()
data.append('course[title]', "Hic et dddvelit sed.")
data.append('course[subtitle]', "Omnis quibusdam illum itaque.")
data.append('course[description]', "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.")
data.append('course[end_date]', "2020-02-01")
data.append('course[attachment_attributes][file]', this.state.selectedFile)
</code>```

This way, the Browser > Network > Header > Data Form, will show each item passed correctly and the uploaded image will maintain the binary format.

Here a preview:

```<code>course[title]: 6666Hic et dddvelit sed.
course[subtitle]: Omnis quibusdam illum itaque.
course[description]: Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.
course[end_date]: 2020-02-01
course[attachment_attributes][file]: (binary)
</code>```

POST API will be looking like this:

```<code>return api
  .post("http://localhost:3000/api/v1/courses", data)
  .then(res => {
    console.log(res.statusText)
  })
  .catch(res => console.log('error ==> ', res))
</code>```

I really hope this can help someone else because it has driven me crazy for weeks.

Happy coding.
Joe

Body:
I’ve been struggling to find a solution to upload an image and store it in the database.

Tried them all:  Dropzone, react-dropzone, react-uploader, etc.....

The BackEnd API is expecting this:

{
  "course": {
    "title": "Hic et velit sed.",
    "subtitle": "Omnis quibusdam illum itaque.",
    "description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
    "end_date": "2020-02-01",
    "attachment_attributes": {
      "file": {
        --- here the uploaded data file ---
      }
    }
  }
}

My component is now only written with 1 input type=file to speed up this testing. The API requirements such as title, subtitle etc., will be hardcoded.

Here the component:

import React, { Component } from 'react';
import api from '../../../../helpers/API';

class Uploader extends Component {
  constructor(props) {
    super(props);
      this.state = {
        selectedFile: null
      }
  }
  onChangeHandler = event => {
    this.setState({
      selectedFile: event.target.files[0],
      loaded: 0,
    })
  }

  onClickHandler = () => {

   ** HARDCODED API REQUIREMENT**
   const body = "course": {
      "title": "Hic et velit sed.",
      "subtitle": "Omnis quibusdam illum itaque.",
      "description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
      "end_date": "2020-02-01",
      "attachment_attributes": {
        "file": {
          --- here the uploaded file data ---
        }
      }
    }

   ** THIS SHOULD HANDLE THE UPLOADED FILE DATA FORMAT **
    const data = new FormData()
    data.append('file', this.state.selectedFile)

    return api
      .post("http://localhost:3000/api/v1/files", ??????). <— DATA or BODY?
      .then(res => {
        console.log(res.statusText)
      })
      .catch(res => console.log('error ==> ', res))
  }

  render() {
    return (
      <>

          Upload Your File
          <input
            type="file"
            multiple onChange={this.onChangeHandler}/>

        <button type="button" className="btn btn-success btn-block" onClick={this.onClickHandler}>Upload</button>
      </>
    )
  }
}

export default Uploader

Issue

If I pass DATA, in the API call, the uploaded file get nicely stored in the Browser > Network > Header > Data Form section, as file: binary

And that is good.

But I need to pass the uploaded file as part of my BODY object. So, below is what I did, but it gets returned empty:

onClickHandler = () => {
    const data = new FormData()
    data.append('file', this.state.selectedFile)

    const body = {
      "course": {
        "title": "Hic et velit sed.",
        "subtitle": "Omnis quibusdam illum itaque.",
        "description": "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.",
        "end_date": "2020-02-01",
        "attachment_attributes": {
          "file": data  <-- trying to pass the uploaded DataForm here
        }
      }
    }

    return api
      .post("http://localhost:3000/api/v1/files", body)
      .then(res => {
        console.log(res.statusText)
      })
      .catch(res => console.log('error ==> ', res))
  }

Unfortunately I get 422 error, {"errors":{"attachment.file":["blank"]}}

Any help is much appreciated. Thanks

Jow

Body:
OK, found the way.

It's impossible to call the DataForm of the uploaded file from the Object BODY.

What it needs to be done is to data.append each single item in the object.

Here the file:

const data = new FormData()
data.append('course[title]', "Hic et dddvelit sed.")
data.append('course[subtitle]', "Omnis quibusdam illum itaque.")
data.append('course[description]', "Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.")
data.append('course[end_date]', "2020-02-01")
data.append('course[attachment_attributes][file]', this.state.selectedFile)

This way, the Browser > Network > Header > Data Form, will show each item passed correctly and the uploaded image will maintain the binary format.

Here a preview:

course[title]: 6666Hic et dddvelit sed.
course[subtitle]: Omnis quibusdam illum itaque.
course[description]: Et ullam ipsum. Illum dolor odit. Id veritatis ducimus.
course[end_date]: 2020-02-01
course[attachment_attributes][file]: (binary)

POST API will be looking like this:

return api
  .post("http://localhost:3000/api/v1/courses", data)
  .then(res => {
    console.log(res.statusText)
  })
  .catch(res => console.log('error ==> ', res))

I really hope this can help someone else because it has driven me crazy for weeks.

Happy coding.
Joe


问:
AWS Elastic Beanstalk, wont update django.config with "eb deploy"
I've deployed a API application to AWS Elastic Beanstalk written in python and django. I'm now developing the frontend from which I'm trying to send a simple get request to the AWS python server. Trying different solutions to the CORS header issue I added:

```<code>files:
  "/etc/httpd/conf.d/cors.conf" :
    mode: "000644"
    owner: root
    group: root
    content: |
      <Location "/">
        Header set Access-Control-Allow-Origin: *
        Header set Access-Control-Allow-Methods: "POST, GET, PUT, DELETE, OPTIONS"
        Header add Access-Control-Allow-Headers: "Authorization, Content-Type, Accept"
        Header set Access-Control-Allow-Credentials: true

        SetOutputFilter DEFLATE
      </Location>
</code>```

to the django.config file which made it work on AWS but not locally (the django.config file is located in .ebextensions file). I decided to instead use the 'django-cors-headers' middleware so that it would work both locally and on AWS. But now it wont work on AWS since it registers multiple Access-Control-Allow-Origin domains.

So after removing the above files: code from django.config the problem persisted so the reasonable problem would be that the header is added both by the middleware and by the django.config code which I'm not able to remove.

Could someone help me find a solution?

答:
I had the same issue, to fix it, you need to add this on your django.config:</p>

```<code>container_commands:
  01_wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
</code>```

Body:
I've deployed a API application to AWS Elastic Beanstalk written in python and django. I'm now developing the frontend from which I'm trying to send a simple get request to the AWS python server. Trying different solutions to the CORS header issue I added:

files:
  "/etc/httpd/conf.d/cors.conf" :
    mode: "000644"
    owner: root
    group: root
    content: |
      <Location "/">
        Header set Access-Control-Allow-Origin: *
        Header set Access-Control-Allow-Methods: "POST, GET, PUT, DELETE, OPTIONS"
        Header add Access-Control-Allow-Headers: "Authorization, Content-Type, Accept"
        Header set Access-Control-Allow-Credentials: true

        SetOutputFilter DEFLATE
      </Location>

to the django.config file which made it work on AWS but not locally (the django.config file is located in .ebextensions file). I decided to instead use the 'django-cors-headers' middleware so that it would work both locally and on AWS. But now it wont work on AWS since it registers multiple Access-Control-Allow-Origin domains.

So after removing the above files: code from django.config the problem persisted so the reasonable problem would be that the header is added both by the middleware and by the django.config code which I'm not able to remove.

Could someone help me find a solution?

Body:
I had the same issue, to fix it, you need to add this on your django.config:

container_commands:
  01_wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'


问:
Getting "ARCHIVE FAILED" error while doing archive process using command "xcodebuild archive \"
I have one iOS project in Swift language and I have to create archive and .ipa using command on terminal.

I am using Github actions for uploading iOS build on test flight.
I am following all instruction which mentioned in this link:

https://zach.codes/ios-builds-using-github-actions-without-fastlane/#install-gpg

When I am hitting this command on iMac system's terminal:

```<code>xcodebuild archive \
            -workspace GitHubActions.xcworkspace \
            -scheme GitHubActions \
            -sdk iphoneos12.4 \
            -configuration Release \
            -archivePath $PWD/build/GitHubActions.xcarchive \
            IPHONEOS_DEPLOYMENT_TARGET=9.0
            PROVISIONING_PROFILE="<UUID>" \
            CODE_SIGN_IDENTITY="<Code_Sign_IDENTITY>"
</code>```

I am getting success response:

```<code>** ARCHIVE SUCCEEDED **
</code>```

But When I am connecting my iMac using this command:

```<code>ssh <system_username>@192.168.1.100
</code>```

I am connecting successfully then I have reached to project folders using 'cd' command.

And then when I am hitting the same command:

```<code>xcodebuild archive \
                -workspace GitHubActions.xcworkspace \
                -scheme GitHubActions \
                -sdk iphoneos12.4 \
                -configuration Release \
                -archivePath $PWD/build/GitHubActions.xcarchive \
                IPHONEOS_DEPLOYMENT_TARGET=9.0
                PROVISIONING_PROFILE="<UUID>" \
                CODE_SIGN_IDENTITY="<Code_Sign_IDENTITY>"
</code>```

But when I am using this command on another system then I am getting this error:

```<code>** ARCHIVE FAILED **

The following build commands failed:
    PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks /Users/webcubator/Library/Developer/Xcode/DerivedData/GitHubActions-djymswinwihmdobtcnvllpcfgvht/Build/Intermediates.noindex/ArchiveIntermediates/GitHubActions/IntermediateBuildFilesPath/GitHubActions.build/Release-iphoneos/GitHubActions.build/Script-678E7AE3D9F6AC7BF3ABDA96.sh
(1 failure)
</code>```

What exactly I am doing wrong. Not able to understand. Whey this error is showing when accessing iMac from another system.

答:
After search a lot I finally found the solution of issue where I was not able to submit using remote connection from other system.

keychain handles your keys and certificates (used by code sign to sign your build ) is not usable out of the box for the remote user. Its needs to be unlocked first !!!

To know about the available keychains on your system just type in on your terminal :

```<code>security list-keychains
</code>```

You should see something like :

```<code>"/Users/'YOURUSER'/Library/Keychains/login.keychain-db"
"/Library/Keychains/System.keychain"
</code>```

And you guessed it right there, you have to unlock the keychain of your user ! Juste run this :

```<code>security unlock-keychain -p 'USER_PASSWORD' 'PATH_TO_USER_KEYCHAIN'
</code>```

Body:
I have one iOS project in Swift language and I have to create archive and .ipa using command on terminal.

I am using Github actions for uploading iOS build on test flight.
I am following all instruction which mentioned in this link:

https://zach.codes/ios-builds-using-github-actions-without-fastlane/#install-gpg

When I am hitting this command on iMac system's terminal:

xcodebuild archive \
            -workspace GitHubActions.xcworkspace \
            -scheme GitHubActions \
            -sdk iphoneos12.4 \
            -configuration Release \
            -archivePath $PWD/build/GitHubActions.xcarchive \
            IPHONEOS_DEPLOYMENT_TARGET=9.0
            PROVISIONING_PROFILE="<UUID>" \
            CODE_SIGN_IDENTITY="<Code_Sign_IDENTITY>"

I am getting success response:

** ARCHIVE SUCCEEDED **

But When I am connecting my iMac using this command:

ssh <system_username>@192.168.1.100

I am connecting successfully then I have reached to project folders using 'cd' command.

And then when I am hitting the same command:

xcodebuild archive \
                -workspace GitHubActions.xcworkspace \
                -scheme GitHubActions \
                -sdk iphoneos12.4 \
                -configuration Release \
                -archivePath $PWD/build/GitHubActions.xcarchive \
                IPHONEOS_DEPLOYMENT_TARGET=9.0
                PROVISIONING_PROFILE="<UUID>" \
                CODE_SIGN_IDENTITY="<Code_Sign_IDENTITY>"

But when I am using this command on another system then I am getting this error:

** ARCHIVE FAILED **

The following build commands failed:
    PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks /Users/webcubator/Library/Developer/Xcode/DerivedData/GitHubActions-djymswinwihmdobtcnvllpcfgvht/Build/Intermediates.noindex/ArchiveIntermediates/GitHubActions/IntermediateBuildFilesPath/GitHubActions.build/Release-iphoneos/GitHubActions.build/Script-678E7AE3D9F6AC7BF3ABDA96.sh
(1 failure)

What exactly I am doing wrong. Not able to understand. Whey this error is showing when accessing iMac from another system.

Body:
After search a lot I finally found the solution of issue where I was not able to submit using remote connection from other system.

keychain handles your keys and certificates (used by code sign to sign your build ) is not usable out of the box for the remote user. Its needs to be unlocked first !!!

To know about the available keychains on your system just type in on your terminal :

security list-keychains

You should see something like :

"/Users/'YOURUSER'/Library/Keychains/login.keychain-db"
"/Library/Keychains/System.keychain"

And you guessed it right there, you have to unlock the keychain of your user ! Juste run this :

security unlock-keychain -p 'USER_PASSWORD' 'PATH_TO_USER_KEYCHAIN'


问:
Android - Media Scanner not working on api 28-29
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));
```

<p>I used <code>Broadcast</code>, but it didn't work the same way. Because it is "deprecated".</p>

```java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");
```

答:
Did you add this to the manifest file?</p>

```<code><provider
     android:name="androidx.core.content.FileProvider"
     android:authorities="${app_package_name}.provider"
     android:exported="false"
     android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>
</code>```

Body:
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));

I used Broadcast, but it didn't work the same way. Because it is "deprecated".

java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");

Body:
Did you add this to the manifest file?

<provider
     android:name="androidx.core.content.FileProvider"
     android:authorities="${app_package_name}.provider"
     android:exported="false"
     android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
</provider>


问:
split url with comma and semicolon
I have image URL string like this

```<code>"Image1.jpg,Image2.jpg;Image3.jpg";
</code>```

Now I want to split my imageurls with both comma and semicolon and store it into some array so how can I achieve that

答:
In JS: use a regex for the split function separator:</p>

```<code>const url = "Image1.jpg,Image2.jpg;Image3.jpg";
const arr = url.split(/[,;]+/);
</code>```

Title: split url with comma and semicolon

Body:
I have image URL string like this

"Image1.jpg,Image2.jpg;Image3.jpg";

Now I want to split my imageurls with both comma and semicolon and store it into some array so how can I achieve that

Body:
In JS: use a regex for the split function separator:

const url = "Image1.jpg,Image2.jpg;Image3.jpg";
const arr = url.split(/[,;]+/);


问:
how to get returned value from stored function in PDO?
I have this code :

```<code>include("connect.php");
// Call database function
$p = 100;
$sth = $conn->prepare('SELECT ISPPRO.USERPKG.GET_USER(:bind1, :bind3) AS v FROM DUAL');
$sth->bindParam(":bind1", $p, PDO::PARAM_INT);
$sth->bindParam(":bind3", $p, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r( $result);
echo "<br>```";
print_r($conn->errorInfo());
echo "```";
</code>```

The ISPPRO.USERPKG.GET_USER returns 1 or 0;

How I can get it??

Thanks in advance.

EDIT:

I changed the above code and I am getting this error:

```<code>OCIStmtExecute: ORA-00904: "ISPPRO"."USERPKG"."GET_USER": invalid identifier
</code>```

答:
If you have an Oracle function that returns a scalar you read it as any other value, e.g.:

```<code>SELECT ISPPRO.USERPKG.GET_USER(:user, :pass) AS foo
FROM DUAL
</code>```

... and read the value from the column foo as in any other query.

Body:
I have this code :

include("connect.php");
// Call database function
$p = 100;
$sth = $conn->prepare('SELECT ISPPRO.USERPKG.GET_USER(:bind1, :bind3) AS v FROM DUAL');
$sth->bindParam(":bind1", $p, PDO::PARAM_INT);
$sth->bindParam(":bind3", $p, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r( $result);
echo "

";
print_r($conn->errorInfo());
echo "
";

The ISPPRO.USERPKG.GET_USER returns 1 or 0;

How I can get it??

Thanks in advance.

EDIT:

I changed the above code and I am getting this error:

OCIStmtExecute: ORA-00904: "ISPPRO"."USERPKG"."GET_USER": invalid identifier

Body:
If you have an Oracle function that returns a scalar you read it as any other value, e.g.:

SELECT ISPPRO.USERPKG.GET_USER(:user, :pass) AS foo
FROM DUAL

... and read the value from the column foo as in any other query.


问:
Could NOT find Protobuf (missing: Protobuf_PROTOC_EXECUTABLE)
When I am doing a cmake in the build directory of the project I am getting this error. Initially I got a

protobuf-config.cmake not found

error. So I gave a path of the protobuf-config.cmake file to Protobuf_DIR. Later it started to show this new error:

CMake Error at
  /opt/cmake/share/cmake-3.13/Modules/FindPackageHandleStandardArgs.cmake:137
  (message):   Could NOT find Protobuf (missing:
  Protobuf_PROTOC_EXECUTABLE)

(found   suitable version "3.6.1", minimum required is "3.0.0")

I am also attaching the error log file:
https://drive.google.com/open?id=1y7BZ6lDBtxvla7r-o188xM_FjwLqwhCx

I am doing this on Ubuntu-18 with cmake version: 3.13 and protobuf version: 3.6.1

答:
Default repositories usually contain outdated protobuf version. It is best to install it manually, from sources:</p>

```<code>git clone --progress -b v3.10.0 https://github.com/protocolbuffers/protobuf && \
    ( \
      cd protobuf; \
      mkdir build; \
      cd build; \
      cmake ../cmake \
        -DCMAKE_BUILD_TYPE=Release \
        -Dprotobuf_BUILD_SHARED_LIBS=ON \
        -Dprotobuf_BUILD_TESTS=OFF; \
      make -j4 install; \
    ) && \
    rm -rf protobuf
</code>```

Body:
Default repositories usually contain outdated protobuf version. It is best to install it manually, from sources:

git clone --progress -b v3.10.0 https://github.com/protocolbuffers/protobuf && \
    ( \
      cd protobuf; \
      mkdir build; \
      cd build; \
      cmake ../cmake \
        -DCMAKE_BUILD_TYPE=Release \
        -Dprotobuf_BUILD_SHARED_LIBS=ON \
        -Dprotobuf_BUILD_TESTS=OFF; \
      make -j4 install; \
    ) && \
    rm -rf protobuf


问:
IDE for php prado
iam looking for IDE with intellisense support for PHP Prado.

please suggest me some ide's.

-------My Answer----------------

None of the answers solved my problem, so carried on my research and found one ide phpedit

http://www.waterproof.fr/

答:
iam looking for IDE with intellisense support for PHP Prado.

Well, I'm a Netbeans user, and use multiple frameworks. If you use a framework and make sure that it's in your include-path, Netbeans will automatically index the framework, and provide intellisense for it. I don't think you need an IDE with framework specific intellisense, I think you need an IDE that can do intellisense on existing frameworks :)

Title: IDE for php prado


问:
How get a generated PIL image from Django REST framework backend to frontend?
I was planning to make a web app where I can make a POST request to generate an image with PIL on the backend and link it to the frontend through the REST framework by GET where I can download it. I don't want to save the generated image in the database. Just wanna generate it one time only for download. Any idea on how I can pull it off?</p>

答: You may want to use StreamingHttpResponse, which allows you to send a FileField (or an ImageField, for that matter) as an http response.</p>


问:
ERROR: Failed to resolve: com.google.android.gms:play-services-ads:18.3.0
While syncing the project after added play-services-ads, I am always getting this error "failed to resolve play-services-ads".

build.gradle at project level

```<code>    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}
</code>```

build.gradle at app level

```<code>dependencies {
   implementation 'androidx.media:media:1.0.1'
   implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.11.3'
   implementation 'com.google.android.gms:playservices-ads:18.3.0'
}
</code>```

答:
Have you added apply plugin line in app level build.gradle

```<code>dependencies {
   implementation 'androidx.media:media:1.0.1'
   implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.11.3'
   implementation 'com.google.android.gms:playservices-ads:18.3.0'
}
apply plugin: 'com.google.gms.google-services' //add this
</code>```

Body:
While syncing the project after added play-services-ads, I am always getting this error "failed to resolve play-services-ads".

build.gradle at project level

    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

build.gradle at app level

dependencies {
   implementation 'androidx.media:media:1.0.1'
   implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.11.3'
   implementation 'com.google.android.gms:playservices-ads:18.3.0'
}

Body:
Have you added apply plugin line in app level build.gradle

dependencies {
   implementation 'androidx.media:media:1.0.1'
   implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.11.3'
   implementation 'com.google.android.gms:playservices-ads:18.3.0'
}
apply plugin: 'com.google.gms.google-services' //add this


问:
How to get img and p tag inside div using vue?
I want to get image src and text of
 when I click on
 element.

```<code><div class="image-holder" @click="showImage($event)" >
  img class="img-fluid"  src="images/models-detail-small.png" alt="" />
  <p>elevation {{elevationA}}- {{elevationASqt}} sq. ft</p>
</div>

var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);

            // href = element.getAttribute('src');
            // this.imgSrc=href;
        }
    }
});
</code>```

答:
Considering you are getting the div element by event.CurrentTarget You can try something like below.

```<code>var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);
            var img = element.getElementsByTagName('img');
            this.imgSrc = img.length > 0 ? img[0].src : null;
            var pTag = element.getElementsByTagName('p');
            this.text = pTag.length > 0 ? pTag[0].textContent : null;
        }
    }
});

</code>```

Body:
I want to get image src and text of
 when I click on
 element.

  img class="img-fluid"  src="images/models-detail-small.png" alt="" />

elevation {{elevationA}}- {{elevationASqt}} sq. ft

var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);

            // href = element.getAttribute('src');
            // this.imgSrc=href;
        }
    }
});

Body:
Considering you are getting the div element by event.CurrentTarget You can try something like below.

var vm = new Vue({
    el: '#app',
    methods: {
        showImage: function (event) {
            element = event.currentTarget;
            console.log(element);
            var img = element.getElementsByTagName('img');
            this.imgSrc = img.length > 0 ? img[0].src : null;
            var pTag = element.getElementsByTagName('p');
            this.text = pTag.length > 0 ? pTag[0].textContent : null;
        }
    }
});


问:
Cocoapods - Swift framework with internal static library dependency
I'm implementing an iOS framework written on Swift. This framework has an internal dependency on a C based static library. To make it work and based on some tutorials I've made a module map similar to this:

```<code>framework module Module {
    umbrella header "Module.h"

    explicit module ModuleDep {
        private header "header1.h"
    }

    export *
}
</code>```

Based on that I can include C code in Swift like this:

```<code>import Module.ModuleDep
</code>```

When export framework manually everything seems to work just fine. It is a sure thing, I want to have Cocoapods support for my framework with code visibility (easier to debug). The podspec, that make it work was this (some parts are omitted):

```<code>Pod::Spec.new do |s|
  s.platform = :ios
  s.ios.deployment_target = '12.0'

  s.module_map = "Module.modulemap"
  s.source_files = "Module/*.{h,swift}", "ModuleDep/*.h"
  s.vendored_libraries  = "ModuleDep/*.a"

  s.swift_version = "5.1"
end
</code>```

From my understanding, vendored_libraries is used when this is the artifact you are providing to your users and that is why I don't like this solution.

I've also tried this spec variant:

```<code>Pod::Spec.new do |s|
  s.platform = :ios
  s.ios.deployment_target = '12.0'

  s.module_map = "Module.modulemap"
  s.source_files = "Module/*.{h,swift}", "ModuleDep/*.h", "ModuleDep/*.a"
  s.swift_version = "5.1"
end
</code>```

but it doesn't compile.

So what is the correct way to do this? Or what have I done wrong?

答:
Since you are using a static library as a dependency then you must specify it as a library in your podspec file. Which is why your second approach is not working because it's a library not a source file.

As mentioned in the docs vendored_libraries are for libraries that come shipped with the Pod. Also in your case that C based static library is a dependency which must be shipped with the Pod. Thus using vendored_libraries should be ok in your case.

Body:
I'm implementing an iOS framework written on Swift. This framework has an internal dependency on a C based static library. To make it work and based on some tutorials I've made a module map similar to this:

framework module Module {
    umbrella header "Module.h"

    explicit module ModuleDep {
        private header "header1.h"
    }

    export *
}

Based on that I can include C code in Swift like this:

import Module.ModuleDep

When export framework manually everything seems to work just fine. It is a sure thing, I want to have Cocoapods support for my framework with code visibility (easier to debug). The podspec, that make it work was this (some parts are omitted):

Pod::Spec.new do |s|
  s.platform = :ios
  s.ios.deployment_target = '12.0'

  s.module_map = "Module.modulemap"
  s.source_files = "Module/*.{h,swift}", "ModuleDep/*.h"
  s.vendored_libraries  = "ModuleDep/*.a"

  s.swift_version = "5.1"
end

From my understanding, vendored_libraries is used when this is the artifact you are providing to your users and that is why I don't like this solution.

I've also tried this spec variant:

Pod::Spec.new do |s|
  s.platform = :ios
  s.ios.deployment_target = '12.0'

  s.module_map = "Module.modulemap"
  s.source_files = "Module/*.{h,swift}", "ModuleDep/*.h", "ModuleDep/*.a"
  s.swift_version = "5.1"
end

but it doesn't compile.

So what is the correct way to do this? Or what have I done wrong?