问:
MouseEvent.offsetX/Y resets to 0 if moving over different child elements
Take the following fiddle.

It contains a parent div with 3 child divs. A click-listener is attached to the parent div and should throw alerts with the mouse position relative to the parent div:

```<code>const parent = document.getElementById('main');
parent.addEventListener('click', handleMouseClick);

function handleMouseClick(e) {
    alert(e.offsetX, e.offsetY);
}
</code>```

What I expect: Click on any of the child divs and get the click position relative to the parent div (#main).

What actually happens: OffsetX/Y always equals the click position relative to the child I clicked on.

Why does this happen? How can I fix it? Is there another way to get the mouse position relative to the parent div, taking potential scrolling into account?

答:
you can add a css attribute to child element

```<code>.child {
  pointer-events: none;
}
</code>```

take the following codepen

Body:
Take the following fiddle.

It contains a parent div with 3 child divs. A click-listener is attached to the parent div and should throw alerts with the mouse position relative to the parent div:

const parent = document.getElementById('main');
parent.addEventListener('click', handleMouseClick);

function handleMouseClick(e) {
    alert(e.offsetX, e.offsetY);
}

What I expect: Click on any of the child divs and get the click position relative to the parent div (#main).

What actually happens: OffsetX/Y always equals the click position relative to the child I clicked on.

Why does this happen? How can I fix it? Is there another way to get the mouse position relative to the parent div, taking potential scrolling into account?

Body:
you can add a css attribute to child element

.child {
  pointer-events: none;
}

take the following codepen


来源: stackexchange

问:
Error while loading parquet format file into Amazon Redshift using copy command and manifest file
I'm trying to load parquet file using manifest file and getting below error.

query:     124138ailed due to an internal error. File 'https://s3.amazonaws.com/sbredshift-east/data/000002_0  has an invalid version number: )

Here is my copy command

copy testtable from 's3://sbredshift-east/manifest/supplier.manifest'
IAM_ROLE 'arn:aws:iam::123456789:role/MyRedshiftRole123'
FORMAT AS PARQUET
manifest;

here is my manifest file

```<code>**{
   "entries":[
      {
         "url":"s3://sbredshift-east/data/000002_0",
         "mandatory":true,
         "meta":{
            "content_length":1000
         }
      }
   ]
}**
</code>```

I'm able to load the same file using copy command by specifying the file name.

copy testtable from 's3://sbredshift-east/data/000002_0'                                                                                IAM_ROLE 'arn:aws:iam::123456789:role/MyRedshiftRole123'                                                                                FORMAT AS PARQUET;

INFO:  Load into table 'supplier' completed, 800000 record(s) loaded successfully.
COPY

What could be wrong in my copy statement?

答:
The only way I've gotten parquet copy to work with manifest file is to add the meta key with the content_length.

From what I can gather in my error logs, the COPY command for parquet (w/ manifest) might first be reading the files using Redshift Spectrum as an external table. If that's the case, this hidden step does require the content_step which contradicts their initial statement about COPY commands.

https://docs.amazonaws.cn/en_us/redshift/latest/dg/loading-data-files-using-manifest.html

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to load parquet file using manifest file and getting below error.

query:     124138ailed due to an internal error. File 'https://s3.amazonaws.com/sbredshift-east/data/000002_0  has an invalid version number: )

Here is my copy command

copy testtable from 's3://sbredshift-east/manifest/supplier.manifest'
IAM_ROLE 'arn:aws:iam::123456789:role/MyRedshiftRole123'
FORMAT AS PARQUET
manifest;

here is my manifest file

**{
   "entries":[
      {
         "url":"s3://sbredshift-east/data/000002_0",
         "mandatory":true,
         "meta":{
            "content_length":1000
         }
      }
   ]
}**

I'm able to load the same file using copy command by specifying the file name.

copy testtable from 's3://sbredshift-east/data/000002_0'                                                                                IAM_ROLE 'arn:aws:iam::123456789:role/MyRedshiftRole123'                                                                                FORMAT AS PARQUET;

INFO:  Load into table 'supplier' completed, 800000 record(s) loaded successfully.
COPY

What could be wrong in my copy statement?


问:
Odd type of a column in a Data Frame
I used to think that a single column in a Data Frame is a Vector.

I have some code below.

In the last line, what does it mean that typeof(incomeAndState$state) is integer?

```<code>> income <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,
          61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,
          59, 46, 58, 43)
> state <- c("tas", "sa",  "qld", "nsw", "nsw", "nt",  "wa",  "wa",
        "qld", "vic", "nsw", "vic", "qld", "qld", "sa",  "tas",
        "sa",  "nt",  "wa",  "vic", "qld", "nsw", "nsw", "wa",
        "sa",  "act", "nsw", "vic", "vic", "act")
> incomeAndState <- data.frame(state=state, income=income)
> incomeAndState$state
</code>```

Output:

```<code>[1] tas sa  qld nsw nsw nt  wa  wa  qld vic nsw vic qld qld sa  tas sa  nt  wa  vic qld nsw
[23] nsw wa  sa  act nsw vic vic act
Levels: act nsw nt qld sa tas vic wa

> typeof(incomeAndState$state)
</code>```

Output (WHAT DOES THIS MEAN?):

```<code>[1] "integer"
</code>```

答:
state column is a factor.

```<code>class(incomeAndState$state)
#[1] "factor"
</code>```

and factors are internally stored as integers hence you see

```<code>typeof(incomeAndState$state)
#[1] "integer"
</code>```

which can also be verified with mode

```<code>mode(incomeAndState$state)
#[1] "numeric"
</code>```

This can be avoided if you use stringsAsFactors = FALSE while constructing the dataframe

```<code>incomeAndState <- data.frame(state=state, income=income, stringsAsFactors = FALSE)
</code>```

which will give you

```<code>typeof(incomeAndState$state)
#[1] "character"

mode(incomeAndState$state)
#[1] "character"
</code>```

Title: Odd type of a column in a Data Frame

Body:
I used to think that a single column in a Data Frame is a Vector.

I have some code below.

In the last line, what does it mean that typeof(incomeAndState$state) is integer?

> income <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,
          61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,
          59, 46, 58, 43)
> state <- c("tas", "sa",  "qld", "nsw", "nsw", "nt",  "wa",  "wa",
        "qld", "vic", "nsw", "vic", "qld", "qld", "sa",  "tas",
        "sa",  "nt",  "wa",  "vic", "qld", "nsw", "nsw", "wa",
        "sa",  "act", "nsw", "vic", "vic", "act")
> incomeAndState <- data.frame(state=state, income=income)
> incomeAndState$state

Output:

[1] tas sa  qld nsw nsw nt  wa  wa  qld vic nsw vic qld qld sa  tas sa  nt  wa  vic qld nsw
[23] nsw wa  sa  act nsw vic vic act
Levels: act nsw nt qld sa tas vic wa

> typeof(incomeAndState$state)

Output (WHAT DOES THIS MEAN?):

[1] "integer"

Body:
state column is a factor.

class(incomeAndState$state)
#[1] "factor"

and factors are internally stored as integers hence you see

typeof(incomeAndState$state)
#[1] "integer"

which can also be verified with mode

mode(incomeAndState$state)
#[1] "numeric"

This can be avoided if you use stringsAsFactors = FALSE while constructing the dataframe

incomeAndState <- data.frame(state=state, income=income, stringsAsFactors = FALSE)

which will give you

typeof(incomeAndState$state)
#[1] "character"

mode(incomeAndState$state)
#[1] "character"


问:
How to create a 0x appended hex string from a hex string for each byte of hex characters in golang?
Using the following as a starting point I was able to get something working.

How to insert a Character every X Characters in a String in Golang?

But I want to know if there is an idiomatic way to write golang for what I wan to do, which is the output of the first fmt.Println shown below:
```<code>package main

import (
    "bytes"
    "fmt"
)

func insertStringInto(s string, interval int, sep string) string {
    var buffer bytes.Buffer
    before := interval - 1
    last := len(s) - 1
    for i, char := range s {
        buffer.WriteRune(char)
        if i%interval == before && i != last {
            buffer.WriteString(sep)
        }
    }
    return buffer.String()
}

func main() {
    fmt.Println("0x" + insertStringInto("01234567891011121314151617181920", 2, ", 0x"))

    fmt.Println(insertStringInto("01234567891011121314151617181920", 2, ", 0x"))
}
</code>```

Produces the following:

```<code>0x01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
</code>```

Link to play.golang.org below:

https://play.golang.org/p/TvLFAKsrcCB

答:
I'm not sure how idiomatic this is but re-slicing of strings is often used for this sort of thing. Also strings.builder was introduced recently.

```<code>func insertInto(s string, interval int, prefix, sep string) string {
    sb := strings.Builder{}
    sb.Grow((len(s)/interval+1)*(interval+len(prefix)+len(sep)))

    first := true
    for i := 0; i < len(s)/interval; i++ {
        if first {
            first = false
        } else {
            sb.WriteString(sep)
        }
        sb.WriteString(prefix)
        sb.WriteString(s[i*interval :(i+1)*interval])
    }
    return sb.String()
}

...
    print(insertInto("0123456789101112131415161718192", 2, "0x", ", "))
</code>```

Note that this does not try to validate that the string only contains hex digits.  It also assumes that it is a multiple of interval, but could be easily tweaked.

Body:
Using the following as a starting point I was able to get something working.

How to insert a Character every X Characters in a String in Golang?

But I want to know if there is an idiomatic way to write golang for what I wan to do, which is the output of the first fmt.Println shown below:

package main

import (
    "bytes"
    "fmt"
)

func insertStringInto(s string, interval int, sep string) string {
    var buffer bytes.Buffer
    before := interval - 1
    last := len(s) - 1
    for i, char := range s {
        buffer.WriteRune(char)
        if i%interval == before && i != last {
            buffer.WriteString(sep)
        }
    }
    return buffer.String()
}

func main() {
    fmt.Println("0x" + insertStringInto("01234567891011121314151617181920", 2, ", 0x"))

    fmt.Println(insertStringInto("01234567891011121314151617181920", 2, ", 0x"))
}

Produces the following:

0x01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20
01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x20

Link to play.golang.org below:

https://play.golang.org/p/TvLFAKsrcCB

Body:
I'm not sure how idiomatic this is but re-slicing of strings is often used for this sort of thing. Also strings.builder was introduced recently.

func insertInto(s string, interval int, prefix, sep string) string {
    sb := strings.Builder{}
    sb.Grow((len(s)/interval+1)*(interval+len(prefix)+len(sep)))

    first := true
    for i := 0; i < len(s)/interval; i++ {
        if first {
            first = false
        } else {
            sb.WriteString(sep)
        }
        sb.WriteString(prefix)
        sb.WriteString(s[i*interval :(i+1)*interval])
    }
    return sb.String()
}

...
    print(insertInto("0123456789101112131415161718192", 2, "0x", ", "))

Note that this does not try to validate that the string only contains hex digits.  It also assumes that it is a multiple of interval, but could be easily tweaked.


问:
Suspend Neptune services?
Is there any way to suspend Neptune? I want to continue experimenting with it, but I'm facing hundreds of dollars per month while my instances are mostly idle. Ideally, I'd like to be able to wind down the cluster when I'm not using it, then boot back up later with the same endpoints and settings.</p>

答:
You can start/stop cluster from the console or CLI.

```<code>aws neptune stop-db-cluster --db-cluster-identifier mydbcluster
aws neptune start-db-cluster --db-cluster-identifier mydbcluster
</code>```

See https://docs.aws.amazon.com/neptune/latest/userguide/manage-console-stop-start.html for details.

Title: Suspend Neptune services?

Body:
You can start/stop cluster from the console or CLI.

aws neptune stop-db-cluster --db-cluster-identifier mydbcluster
aws neptune start-db-cluster --db-cluster-identifier mydbcluster

See https://docs.aws.amazon.com/neptune/latest/userguide/manage-console-stop-start.html for details.


问:
Data Table Solution In R To Find Group Min/Max
Data

```<code>data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))
</code>```

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

答:
Another data.table option:

```<code>setDT(data)[, c("min","max") := as.list(range(score, na.rm=TRUE)), student]
</code>```

Body:
Data

data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

Body:
Another data.table option:

setDT(data)[, c("min","max") := as.list(range(score, na.rm=TRUE)), student]


问:
Creating a timer with a pause function in python
I have been helped to make a timer where if I press the space key, it restarts. I would like to edit this code so when I press the return/enter button, it pauses the timer, regardless of where the timer is (restarted, at 0, or in the middle). Of course, I don't want it to affect the rest of the code. Here is my code:

from turtle import Screen, Turtle, bgcolor
bgcolor('dodgerblue')
FONT = ("Arial", 60, "normal")

strings = input("Please enter the time: ").strip().split(' ')

time = [60 ** (len(strings) - index - 1) * int(unit) for index, unit in enumerate(strings)]

seconds = -1
ticking = False
def delSec(string):
    if len(string)==1:
        return "0"+string
    else:
        return string
def tick():
    global seconds, ticking

    turtle.clear()

    if seconds < 0:
        turtle.write("TIMER DONE", align='center', font=FONT)
        ticking = False
    else:
        turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
        seconds -= 1
        screen.ontimer(tick, 1000)
key = "space"
def reset():
    global seconds, ticking, key

    screen.onkey(None, key)  # Disable event handler inside handler

    seconds = sum(time)

    if not ticking:
        ticking = True
        tick()

    screen.onkey(reset, key)  # Reenable event handler

screen = Screen()

turtle = Turtle()
turtle.hideturtle()
turtle.color('white')

reset()

screen.listen()
screen.mainloop()
```

I would appreciate any help, thanks in advance!

EDIT: I want it so that if the timer is paused, I can still reset it.

答:
I use key Return to run function which change paused

```<code>def pause():
    global paused

    paused = not paused
</code>```

and use this paused to control tick()

```<code>def tick():
    global seconds, ticking

    if not paused:
        turtle.clear()

        if seconds < 0:
            turtle.write("TIMER DONE", align='center', font=FONT)
            ticking = False
            return
        else:
            turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
            seconds -= 1

    screen.ontimer(tick, 1000)
</code>```

tick() has to run ontimer() even if it paused

```<code>from turtle import Screen, Turtle, bgcolor

# --- functions ---

def delSec(string):
    if len(string) == 1:
        return "0" + string
    else:
        return string

def tick():
    global seconds, ticking

    if not paused:
        turtle.clear()

        if seconds < 0:
            turtle.write("TIMER DONE", align='center', font=FONT)
            ticking = False
            return
        else:
            turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
            seconds -= 1

    screen.ontimer(tick, 1000)

def reset():
    global seconds, ticking, key,
    #global paused

    screen.onkey(None, key)  # Disable event handler inside handler
    screen.onkey(None, key_pause)  # Disable event handler inside handler

    seconds = sum(time)

    if not ticking:
        ticking = True
        tick()

    #paused = False

    screen.onkey(reset, key)  # Reenable event handler
    screen.onkey(pause, key_pause)  # Reenable event handler

def pause():
    global paused

    paused = not paused

# --- main ---

bgcolor('dodgerblue')
FONT = ("Arial", 60, "normal")

#strings = input("Please enter the time: ").strip().split(' ')
strings = '10'.strip().split(' ')

time = [60 ** (len(strings) - index - 1) * int(unit) for index, unit in enumerate(strings)]

seconds = -1
ticking = False
paused = False
key = "space"
key_pause = "Return"

screen = Screen()

turtle = Turtle()
turtle.hideturtle()
turtle.color('white')

reset()

screen.listen()
screen.mainloop()
</code>```

To reset text even when it paused I pause only seconds -= 1 - so it redraw time in every loop - even if it paused - so reset can change value.

```<code>def tick():
    global seconds, ticking

    turtle.clear()

    if seconds < 0:
        turtle.write("TIMER DONE", align='center', font=FONT)
        ticking = False
        return
    else:
        turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
        if not paused:
              seconds -= 1

    screen.ontimer(tick, 1000)
</code>```

Body:
I have been helped to make a timer where if I press the space key, it restarts. I would like to edit this code so when I press the return/enter button, it pauses the timer, regardless of where the timer is (restarted, at 0, or in the middle). Of course, I don't want it to affect the rest of the code. Here is my code:

from turtle import Screen, Turtle, bgcolor
bgcolor('dodgerblue')
FONT = ("Arial", 60, "normal")

strings = input("Please enter the time: ").strip().split(' ')

time = [60 ** (len(strings) - index - 1) * int(unit) for index, unit in enumerate(strings)]

seconds = -1
ticking = False
def delSec(string):
    if len(string)==1:
        return "0"+string
    else:
        return string
def tick():
    global seconds, ticking

    turtle.clear()

    if seconds < 0:
        turtle.write("TIMER DONE", align='center', font=FONT)
        ticking = False
    else:
        turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
        seconds -= 1
        screen.ontimer(tick, 1000)
key = "space"
def reset():
    global seconds, ticking, key

    screen.onkey(None, key)  # Disable event handler inside handler

    seconds = sum(time)

    if not ticking:
        ticking = True
        tick()

    screen.onkey(reset, key)  # Reenable event handler

screen = Screen()

turtle = Turtle()
turtle.hideturtle()
turtle.color('white')

reset()

screen.listen()
screen.mainloop()

I would appreciate any help, thanks in advance!

EDIT: I want it so that if the timer is paused, I can still reset it.

Body:
I use key Return to run function which change paused

def pause():
    global paused

    paused = not paused

and use this paused to control tick()

def tick():
    global seconds, ticking

    if not paused:
        turtle.clear()

        if seconds < 0:
            turtle.write("TIMER DONE", align='center', font=FONT)
            ticking = False
            return
        else:
            turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
            seconds -= 1

    screen.ontimer(tick, 1000)

tick() has to run ontimer() even if it paused

from turtle import Screen, Turtle, bgcolor

# --- functions ---

def delSec(string):
    if len(string) == 1:
        return "0" + string
    else:
        return string

def tick():
    global seconds, ticking

    if not paused:
        turtle.clear()

        if seconds < 0:
            turtle.write("TIMER DONE", align='center', font=FONT)
            ticking = False
            return
        else:
            turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
            seconds -= 1

    screen.ontimer(tick, 1000)

def reset():
    global seconds, ticking, key,
    #global paused

    screen.onkey(None, key)  # Disable event handler inside handler
    screen.onkey(None, key_pause)  # Disable event handler inside handler

    seconds = sum(time)

    if not ticking:
        ticking = True
        tick()

    #paused = False

    screen.onkey(reset, key)  # Reenable event handler
    screen.onkey(pause, key_pause)  # Reenable event handler

def pause():
    global paused

    paused = not paused

# --- main ---

bgcolor('dodgerblue')
FONT = ("Arial", 60, "normal")

#strings = input("Please enter the time: ").strip().split(' ')
strings = '10'.strip().split(' ')

time = [60 ** (len(strings) - index - 1) * int(unit) for index, unit in enumerate(strings)]

seconds = -1
ticking = False
paused = False
key = "space"
key_pause = "Return"

screen = Screen()

turtle = Turtle()
turtle.hideturtle()
turtle.color('white')

reset()

screen.listen()
screen.mainloop()

To reset text even when it paused I pause only seconds -= 1 - so it redraw time in every loop - even if it paused - so reset can change value.

def tick():
    global seconds, ticking

    turtle.clear()

    if seconds < 0:
        turtle.write("TIMER DONE", align='center', font=FONT)
        ticking = False
        return
    else:
        turtle.write(delSec(str(seconds//3600))+":"+delSec(str((seconds%3600)//60))+":"+delSec(str((seconds%60)//1)), align='center', font=FONT)
        if not paused:
              seconds -= 1

    screen.ontimer(tick, 1000)


问:
Securing Spring Boot 2 Actuator Prometheus End Points
I have a Spring Boot 2 with Spring Security microservice that I have configured with Micometer/Spring Actuator.  All is well when I permitAll() on the antMatcher("/actuator/**") end points.  I am able to retrieve the Prometheus metrics via a properly configured Prometheus yaml file.

But, my microservice is not behind a firewall and thus open to the world.  I only want Prometheus to be able to access my microservice "/actuator/prometheus" end point.

I have the following configurations:

In my Spring Boot 2 microservice ResourceServerConfig class:

```<code>@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  @Autowired
  private JdbcTokenStore tokenStore;

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.resourceId("springsecurity").tokenStore(tokenStore);
  }

  public void configure(HttpSecurity http) throws Exception {
    http.anonymous().and().authorizeRequests()
      .antMatchers("/actuator/**").hasRole("ENDPOINT_ADMIN")
      .antMatchers("/**").authenticated();
  }
</code>```

For the application.properties file I have:

```<code>spring.security.user.name=user
spring.security.user.password=password
spring.security.user.roles=ENDPOINT_ADMIN

# For Prometheus (and other data loggers)
management.endpoint.metrics.enabled=true
management.endpoints.web.exposure.include=*
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true
</code>```

Then for my Prometheus YAML file I have this:

```<code>global:
  scrape_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
    - targets: ["localhost:9090"]

  - job_name: 'myservice'
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8080']
    basic_auth:
      username: 'user'
      password: 'password'
</code>```

When I go to /targets in Prometheus I get "server returned HTTP status 401".

I fully assume I'm not understanding something quite right.  Is there a way for me to properly do this?  Thank you so much.

答:
Was the prometheus system and the services system in the internal network.
If they was in the same internal network, you can use internal IP to get actuator data.</p>

Body:
I have a Spring Boot 2 with Spring Security microservice that I have configured with Micometer/Spring Actuator.  All is well when I permitAll() on the antMatcher("/actuator/**") end points.  I am able to retrieve the Prometheus metrics via a properly configured Prometheus yaml file.

But, my microservice is not behind a firewall and thus open to the world.  I only want Prometheus to be able to access my microservice "/actuator/prometheus" end point.

I have the following configurations:

In my Spring Boot 2 microservice ResourceServerConfig class:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

  @Autowired
  private JdbcTokenStore tokenStore;

  @Override
  public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    resources.resourceId("springsecurity").tokenStore(tokenStore);
  }

  public void configure(HttpSecurity http) throws Exception {
    http.anonymous().and().authorizeRequests()
      .antMatchers("/actuator/**").hasRole("ENDPOINT_ADMIN")
      .antMatchers("/**").authenticated();
  }

For the application.properties file I have:

spring.security.user.name=user
spring.security.user.password=password
spring.security.user.roles=ENDPOINT_ADMIN

# For Prometheus (and other data loggers)
management.endpoint.metrics.enabled=true
management.endpoints.web.exposure.include=*
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true

Then for my Prometheus YAML file I have this:

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: "prometheus"
    static_configs:
    - targets: ["localhost:9090"]

  - job_name: 'myservice'
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8080']
    basic_auth:
      username: 'user'
      password: 'password'

When I go to /targets in Prometheus I get "server returned HTTP status 401".

I fully assume I'm not understanding something quite right.  Is there a way for me to properly do this?  Thank you so much.


问:
A justification for remote code use is required. - Chrome Extenstion
My Extension is not getting published because of 2 error

A justification for remote code use is required.

The single purpose description is required.

Here's my manifest:

```<code>{
  "name": "Spotlight",
  "icons": {
    "128": "icon_128.png",
    "96": "icon.png"
  },
  "description": "Spotlight - Browse open tabs, search history, bookmarks, downloads, and do much more!",
  "version": "1.19",
  "manifest_version": 2,
  "permissions": [],
  "update_url": "https://clients2.google.com/service/update2/crx",
  "homepage_url": "https://usespotlight.co",
  "optional_permissions" : [
    "<all_urls>",
    "tabs",
    "bookmarks",
    "history",
    "downloads",
    "storage"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "icon.png"
  },
  "commands": {
    "toggle-feature": {
      "suggested_key": {
        "default": "Ctrl+M",
        "mac": "Command+M"
       },
      "description": "Toggle spotlight"
    }
  }
}
</code>```

答:
These new requirements are not actually part of the manifest. In the new developer console, click your item and go to the privacy tab. You can find the various requirements there.
ActiveTab - Used to open tabs
Host Permission - Used to load files onto certain websites

```<code> "matches": [
   "https://www.google.com/"
 ],
 "js": [
   "googleHome.js"
 ]
</code>```

Single purpose description is an old suggestion and a new requirement. Just now being enforced because extensions are supposed to be small and serve a single purpose.

Body:
My Extension is not getting published because of 2 error

A justification for remote code use is required.

The single purpose description is required.

Here's my manifest:

{
  "name": "Spotlight",
  "icons": {
    "128": "icon_128.png",
    "96": "icon.png"
  },
  "description": "Spotlight - Browse open tabs, search history, bookmarks, downloads, and do much more!",
  "version": "1.19",
  "manifest_version": 2,
  "permissions": [],
  "update_url": "https://clients2.google.com/service/update2/crx",
  "homepage_url": "https://usespotlight.co",
  "optional_permissions" : [
    "<all_urls>",
    "tabs",
    "bookmarks",
    "history",
    "downloads",
    "storage"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "icon.png"
  },
  "commands": {
    "toggle-feature": {
      "suggested_key": {
        "default": "Ctrl+M",
        "mac": "Command+M"
       },
      "description": "Toggle spotlight"
    }
  }
}

Body:
These new requirements are not actually part of the manifest. In the new developer console, click your item and go to the privacy tab. You can find the various requirements there.
ActiveTab - Used to open tabs
Host Permission - Used to load files onto certain websites

 "matches": [
   "https://www.google.com/"
 ],
 "js": [
   "googleHome.js"
 ]

Single purpose description is an old suggestion and a new requirement. Just now being enforced because extensions are supposed to be small and serve a single purpose.


问:
Building Python with SSL support in non-standard location
I need to install several Python modules on a RHEL where I don't have root access. At least one of the modules also needs access to Python.h.

In this case I find that the best thing is to install python and it dependencies in ~/local. It usually just works, but this time Python fails to build the SSL module (see details below). Here's the trace of what I'm doing.

So I  downloaded python 6 source and off I went:

```<code>./configure --prefix=/home/fds/rms/local
make >& make.log
</code>```

An inspection to log reveals that ssl module has not been compiled, but there is no mention of the cause (no other occurence of ssl in make or configure):

```<code>Failed to find the necessary bits to build these modules:
_bsddb             _curses            _curses_panel
_hashlib           _sqlite3           _ssl   <----------
</code>```

So I figure, python is not finding any ssl library at all (which is strange, but hey...). So I download openssl-0.9.8r and

```<code>./config --prefix=/home/fds/rms/local shared
make
make install
</code>```

Now back to Python, I ./configure and make again. It fails, but this time it's different:

```<code>Failed to build these modules:
_hashlib           _ssl
</code>```

A closer inspection to the log file reveals this:

```<code>gcc -pthread -shared build/temp.linux-x86_64-2.6/home/fds/rms/installers/Python-2.6.6/Modules/_ssl.o -L/home/fds/rms/local/lib -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-x86_64-2.6/_ssl.so
*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
</code>```

So now it's picking up the library but not quite getting it right (the file is there where is should be):

```<code>$ find /home/fds/rms/local -iname libssl.so.0.9.8
/home/fds/rms/local/lib/libssl.so.0.9.8
</code>```

Next thing is tracing make and see where is it looking for the file:

```<code>$ strace -f make 2>&1 | grep libssl.so.0.9.8
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or   directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_ssl\" sin"..., 131*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_hashlib\""..., 135*** WARNING: renaming "_hashlib" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
</code>```

Mhhh, it's looking in all the wrong places. I try to give a hint:

```<code>CPPFLAGS="-I/home/fds/rms/local/include -I/home/fds/rms/local/include/openssl" LDFLAGS="-L/home/fds/rms/local/lib" ./configure --prefix=/home/fds/rms/local
</code>```

But nothing changes, and make does not seem to try /home/fds/rms/local/lib at all.

I haven't done this in years, so maybe I'm overlooking something. Can anyone help with the problem?

答:
On Linux Red Hat 7.7 x86_64, the following worked to install openssl-1.1.1d and Python-3.8.1 in my home directory (/home/unix/vangalen):

Install OpenSSL
source1 source2

```<code>cd ~
wget https://www.openssl.org/source/openssl-1.1.1d.tar.gz
tar -xzf openssl-1.1.1d.tar.gz
cd /home/unix/vangalen/openssl-1.1.1d
./config --prefix=/home/unix/vangalen/openssl --openssldir=/home/unix/vangalen/openssl
make
make test
make install
</code>```

Install Python
source2 source3 source4

```<code>cd ~
wget https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz
tar xf Python-3.8.1.tgz
</code>```

Modify Python-3.8.1/Modules/Setup in a text editor. If this file doesn't exist you may need to go through a failed run first. Uncomment lines and adjust the alias for SSL in lines 206 to 213::

```<code>_socket socketmodule.c

# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
SSL=/home/unix/vangalen/openssl
_ssl _ssl.c \
  -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
  -L$(SSL)/lib -lssl -lcrypto
</code>```

```<code>cd ~/Python-3.8.1
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/unix/vangalen/openssl/lib
./configure --prefix=/home/unix/vangalen/py-381 --with-openssl=/home/unix/vangalen/openssl
make
make test
make install
</code>```

Body:
I need to install several Python modules on a RHEL where I don't have root access. At least one of the modules also needs access to Python.h.

In this case I find that the best thing is to install python and it dependencies in ~/local. It usually just works, but this time Python fails to build the SSL module (see details below). Here's the trace of what I'm doing.

So I  downloaded python 6 source and off I went:

./configure --prefix=/home/fds/rms/local
make >& make.log

An inspection to log reveals that ssl module has not been compiled, but there is no mention of the cause (no other occurence of ssl in make or configure):

Failed to find the necessary bits to build these modules:
_bsddb             _curses            _curses_panel
_hashlib           _sqlite3           _ssl   <----------

So I figure, python is not finding any ssl library at all (which is strange, but hey...). So I download openssl-0.9.8r and

./config --prefix=/home/fds/rms/local shared
make
make install

Now back to Python, I ./configure and make again. It fails, but this time it's different:

Failed to build these modules:
_hashlib           _ssl

A closer inspection to the log file reveals this:

gcc -pthread -shared build/temp.linux-x86_64-2.6/home/fds/rms/installers/Python-2.6.6/Modules/_ssl.o -L/home/fds/rms/local/lib -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-x86_64-2.6/_ssl.so
*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory

So now it's picking up the library but not quite getting it right (the file is there where is should be):

$ find /home/fds/rms/local -iname libssl.so.0.9.8
/home/fds/rms/local/lib/libssl.so.0.9.8

Next thing is tracing make and see where is it looking for the file:

$ strace -f make 2>&1 | grep libssl.so.0.9.8
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or   directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_ssl\" sin"..., 131*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_hashlib\""..., 135*** WARNING: renaming "_hashlib" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory

Mhhh, it's looking in all the wrong places. I try to give a hint:

CPPFLAGS="-I/home/fds/rms/local/include -I/home/fds/rms/local/include/openssl" LDFLAGS="-L/home/fds/rms/local/lib" ./configure --prefix=/home/fds/rms/local

But nothing changes, and make does not seem to try /home/fds/rms/local/lib at all.

I haven't done this in years, so maybe I'm overlooking something. Can anyone help with the problem?

Body:
On Linux Red Hat 7.7 x86_64, the following worked to install openssl-1.1.1d and Python-3.8.1 in my home directory (/home/unix/vangalen):

Install OpenSSL
source1 source2

cd ~
wget https://www.openssl.org/source/openssl-1.1.1d.tar.gz
tar -xzf openssl-1.1.1d.tar.gz
cd /home/unix/vangalen/openssl-1.1.1d
./config --prefix=/home/unix/vangalen/openssl --openssldir=/home/unix/vangalen/openssl
make
make test
make install

Install Python
source2 source3 source4

cd ~
wget https://www.python.org/ftp/python/3.8.1/Python-3.8.1.tgz
tar xf Python-3.8.1.tgz

Modify Python-3.8.1/Modules/Setup in a text editor. If this file doesn't exist you may need to go through a failed run first. Uncomment lines and adjust the alias for SSL in lines 206 to 213::

_socket socketmodule.c

# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
SSL=/home/unix/vangalen/openssl
_ssl _ssl.c \
  -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
  -L$(SSL)/lib -lssl -lcrypto

cd ~/Python-3.8.1
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/home/unix/vangalen/openssl/lib
./configure --prefix=/home/unix/vangalen/py-381 --with-openssl=/home/unix/vangalen/openssl
make
make test
make install


问:
Provider/ChangeNotifier: Set state after Widget is build
Im using the Provider/ChangenNotifier Pattern to handle state as described in the official docs.

I have a state field which I want to set after a Widget is build. However if I try to set in in the build method. I get an Error:

setState() or markNeedsBuild() called during build.

Where can I call something like:

```<code>var state = Provider.of<StateModel>(context);
state.field = 'new Val';
</code>```

答:
You can not set the state during a build, if you want to test a change of state, put this code state.field = 'new Val'; inside a button event, like FloatActionButton or a event after build completed (with Future.delayed or add post fram callback, see Is there any callback to tell me when "build" function is done in Flutter?)

Warning If you are invoking notifyListeners() inside your state.field set, and listening changes in your widget with provider, It would cause an infinite cycle of rebuild... this is another reason that you can not set state during build...

Body:
Im using the Provider/ChangenNotifier Pattern to handle state as described in the official docs.

I have a state field which I want to set after a Widget is build. However if I try to set in in the build method. I get an Error:

setState() or markNeedsBuild() called during build.

Where can I call something like:

var state = Provider.of<StateModel>(context);
state.field = 'new Val';


问:
Problem with React-Toolkit, Types and Javascript
I was following this tutorial to understand how to use redux-toolkit in a React project.
https://redux-flash-cards.netlify.com/
I was able to compile and execute the project successfully.

Due to restrictions in my current project, I am not able to use Typescript for this React project, so I am trying to use the same project only with javascript.
So, I started to rewrite some of the code in the Javascript way. However, there are some incompatibilities that I do not know how to solve.

My problem is that I'm geeting an error

```<code>'type arguments' can only be used in a .ts file
</code>```

in the line (16) of flash-cards/src/redux/store.ts.

```<code>export type RootState = ReturnType<typeof store.getState>
</code>```

I think that it is becasue Javascript cannot use types.

The above problem is causing other errors on lines 25, 30 and 31 of flash-cards/src/App.tsx, because this file cannot import the previous file (in JS version). So I don't know how to do (line 25)

```<code>import { RootState } from "./redux/store"
</code>```

Somebody was suggesting me to use flow or proptypes to solve the problem, but really I got lost finding the correct solution.

I will appreciate a lot if you can give a hand to solve this problem.

Thanks

答: I was using an incorrect path and double store.</p>

Body:
I was following this tutorial to understand how to use redux-toolkit in a React project.
https://redux-flash-cards.netlify.com/
I was able to compile and execute the project successfully.

Due to restrictions in my current project, I am not able to use Typescript for this React project, so I am trying to use the same project only with javascript.
So, I started to rewrite some of the code in the Javascript way. However, there are some incompatibilities that I do not know how to solve.

My problem is that I'm geeting an error

'type arguments' can only be used in a .ts file

in the line (16) of flash-cards/src/redux/store.ts.

export type RootState = ReturnType<typeof store.getState>

I think that it is becasue Javascript cannot use types.

The above problem is causing other errors on lines 25, 30 and 31 of flash-cards/src/App.tsx, because this file cannot import the previous file (in JS version). So I don't know how to do (line 25)

import { RootState } from "./redux/store"

Somebody was suggesting me to use flow or proptypes to solve the problem, but really I got lost finding the correct solution.

I will appreciate a lot if you can give a hand to solve this problem.

Thanks


问:
Reading specific columns from csv file
I have a csv file called beers.csv and I am trying to read 4 columns from it ( brewery_name, beer_style, beer_name, beer_abv) which are all column headers. I have the following code:

```<code>import csv

csvFile = "beers.csv"
csvData = csv.reader(csvFile, delimiter=',', skipinitialspace=True)

beer, abv, style, brewery = set(), set(), set(), set()
for row in csvData:
    beer.add(row[10])
    abv.add(row[11])
    style.add(row[7])
    brewery.add(row[1])
print(beer, abv, style, brewery)
</code>```

For some reason, I am getting an error:

```<code>Traceback (most recent call last):
  File "filter.py", line 8, in <module>
    beer.add(row[10])
IndexError: list index out of range
</code>```

Here is a the top 15 lines of my beers.csv file:

```<code>brewery_id,brewery_name,review_time,review_overall,review_aroma,review_appearance,review_profilename,beer_style,review_palate,review_taste,beer_name,beer_abv,beer_beerid
10325,Vecchio Birraio,1234817823,1.5,2,2.5,stcules,Hefeweizen,1.5,1.5,Sausa Weizen,5,47986
10325,Vecchio Birraio,1235915097,3,2.5,3,stcules,English Strong Ale,3,3,Red Moon,6.2,48213
10325,Vecchio Birraio,1235916604,3,2.5,3,stcules,Foreign / Export Stout,3,3,Black Horse Black Beer,6.5,48215
10325,Vecchio Birraio,1234725145,3,3,3.5,stcules,German Pilsener,2.5,3,Sausa Pils,5,47969
1075,Caldera Brewing Company,1293735206,4,4.5,4,johnmichaelsen,American Double / Imperial IPA,4,4.5,Cauldron DIPA,7.7,64883
1075,Caldera Brewing Company,1325524659,3,3.5,3.5,oline73,Herbed / Spiced Beer,3,3.5,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1318991115,3.5,3.5,3.5,Reidrover,Herbed / Spiced Beer,4,4,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1306276018,3,2.5,3.5,alpinebryant,Herbed / Spiced Beer,2,3.5,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1290454503,4,3,3.5,LordAdmNelson,Herbed / Spiced Beer,3.5,4,Caldera Ginger Beer,4.7,52159
</code>```

What am I doing wrong?

答:
```<code>import csv

cols = ('brewery_name', 'beer_style', 'beer_name', 'beer_abv')
sets = {}
with open("beers.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        for col in cols:
            sets.setdefault(col, set()).add(row[col])
print(sets)
</code>```

$ python3 beers.py
      {'brewery_name': {'Caldera Brewing Company', 'Vecchio Birraio'}, 'beer_style': {'American Double / Imperial IPA', 'Foreign / Export Stout', 'Herbed / Spiced Beer', 'German Pilsener', 'Hefeweizen', 'English Strong Ale'}, 'beer_name': {'Black Horse Black Beer', 'Sausa Pils', 'Sausa Weizen', 'Cauldron DIPA', 'Caldera Ginger Beer', 'Red Moon'}, 'beer_abv': {'5', '7.7', '4.7', '6.5', '6.2'}}

Title: Reading specific columns from csv file

Body:
I have a csv file called beers.csv and I am trying to read 4 columns from it ( brewery_name, beer_style, beer_name, beer_abv) which are all column headers. I have the following code:

import csv

csvFile = "beers.csv"
csvData = csv.reader(csvFile, delimiter=',', skipinitialspace=True)

beer, abv, style, brewery = set(), set(), set(), set()
for row in csvData:
    beer.add(row[10])
    abv.add(row[11])
    style.add(row[7])
    brewery.add(row[1])
print(beer, abv, style, brewery)

For some reason, I am getting an error:

Traceback (most recent call last):
  File "filter.py", line 8, in <module>
    beer.add(row[10])
IndexError: list index out of range

Here is a the top 15 lines of my beers.csv file:

brewery_id,brewery_name,review_time,review_overall,review_aroma,review_appearance,review_profilename,beer_style,review_palate,review_taste,beer_name,beer_abv,beer_beerid
10325,Vecchio Birraio,1234817823,1.5,2,2.5,stcules,Hefeweizen,1.5,1.5,Sausa Weizen,5,47986
10325,Vecchio Birraio,1235915097,3,2.5,3,stcules,English Strong Ale,3,3,Red Moon,6.2,48213
10325,Vecchio Birraio,1235916604,3,2.5,3,stcules,Foreign / Export Stout,3,3,Black Horse Black Beer,6.5,48215
10325,Vecchio Birraio,1234725145,3,3,3.5,stcules,German Pilsener,2.5,3,Sausa Pils,5,47969
1075,Caldera Brewing Company,1293735206,4,4.5,4,johnmichaelsen,American Double / Imperial IPA,4,4.5,Cauldron DIPA,7.7,64883
1075,Caldera Brewing Company,1325524659,3,3.5,3.5,oline73,Herbed / Spiced Beer,3,3.5,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1318991115,3.5,3.5,3.5,Reidrover,Herbed / Spiced Beer,4,4,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1306276018,3,2.5,3.5,alpinebryant,Herbed / Spiced Beer,2,3.5,Caldera Ginger Beer,4.7,52159
1075,Caldera Brewing Company,1290454503,4,3,3.5,LordAdmNelson,Herbed / Spiced Beer,3.5,4,Caldera Ginger Beer,4.7,52159

What am I doing wrong?

Body:
import csv

cols = ('brewery_name', 'beer_style', 'beer_name', 'beer_abv')
sets = {}
with open("beers.csv") as f:
    reader = csv.DictReader(f)
    for row in reader:
        for col in cols:
            sets.setdefault(col, set()).add(row[col])
print(sets)

$ python3 beers.py
      {'brewery_name': {'Caldera Brewing Company', 'Vecchio Birraio'}, 'beer_style': {'American Double / Imperial IPA', 'Foreign / Export Stout', 'Herbed / Spiced Beer', 'German Pilsener', 'Hefeweizen', 'English Strong Ale'}, 'beer_name': {'Black Horse Black Beer', 'Sausa Pils', 'Sausa Weizen', 'Cauldron DIPA', 'Caldera Ginger Beer', 'Red Moon'}, 'beer_abv': {'5', '7.7', '4.7', '6.5', '6.2'}}


问:
Read the excel file from the specific location
I don't want to use this way(link)
because I don't want to open new window for file selection.
I just want to load & read excel file when I click some button.
But this is not work.. help me to load the excel file.

MYCODE:

```<code>const FILE_NAME = "C:/Users/A/project_list.xlsx";

function LoadSpread(json) {
  jsonData = json;
  workbook.fromJSON(json);

  workbook.setActiveSheet("Revenues (Sales)");
}

function excelExport(fileName) {
  console.log(fileName);

  var excelUrl = fileName;

  var oReq = new XMLHttpRequest();
  oReq.open("get", excelUrl, true);
  oReq.responseType = "blob";
  oReq.onload = function() {
    var blob = oReq.response;
    excelIO.open(blob, LoadSpread, function(message) {
      console.log(message);
    });
  };
  oReq.send(null);
}

function chkPrtNum(event) {
  var fileName = FILE_NAME;
  excelExport(fileName);
}
</code>```

答:
Try creating a small server for the same, you will easily get your job done. – Raghu Chahar Jan 28 at 9:50

This was very helpful

Body:
I don't want to use this way(link)
because I don't want to open new window for file selection.
I just want to load & read excel file when I click some button.
But this is not work.. help me to load the excel file.

MYCODE:

const FILE_NAME = "C:/Users/A/project_list.xlsx";

function LoadSpread(json) {
  jsonData = json;
  workbook.fromJSON(json);

  workbook.setActiveSheet("Revenues (Sales)");
}

function excelExport(fileName) {
  console.log(fileName);

  var excelUrl = fileName;

  var oReq = new XMLHttpRequest();
  oReq.open("get", excelUrl, true);
  oReq.responseType = "blob";
  oReq.onload = function() {
    var blob = oReq.response;
    excelIO.open(blob, LoadSpread, function(message) {
      console.log(message);
    });
  };
  oReq.send(null);
}

function chkPrtNum(event) {
  var fileName = FILE_NAME;
  excelExport(fileName);
}


问:
How to use user_data url when creating an AWS instance in terraform?
Terraform Version = 0.12

```<code>data "template_file" "user_data" {
  template = file("${path.module}/userdata.sh")
}

resource "aws_instance" "bespin-ec2-web-a" {
  ami = "ami-0bea7fd38fabe821a"
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.bespin-sg.id]
  subnet_id = aws_subnet.bespin-subnet-public-a.id
  associate_public_ip_address = true
  tags = {
    Name = "bespin-ec2-web-a"
  }
  user_data = data.template_file.user_data.rendered
}
</code>```

I want to upload user_data to S3 and use it by calling URL.
What can I do?

ex)

```<code>resource "template_file" "userdata_sh" {
  template = "https://test.s3.ap-northeast-2.amazonaws.com/userdata.sh"
}
</code>```

答:
Not 100% clear what is to be achieved, however, if to specify userdata for EC2 instances to use, then use a sh file in S3 would not be possible.

Need to specify userdata content directly to aws_instance terraform resource.

EC2/userdata

```<code>resource "aws_instance" "this" {
  ami = "${local.ami_this_id}"
  instance_type = "${var.instance_type}"
  subnet_id = "${var.subnet_id}"
  vpc_security_group_ids = "${var.security_group_ids}"
  key_name = "${aws_key_pair.this.key_name}"
  iam_instance_profile = "${var.ec2_instance_profile_id}"

  user_data = data.template_file.user_data.rendered   # <----- Specify userdata content

  root_block_device {
    volume_type = "${var.root_volume_type}"
    volume_size = "${var.root_volume_size}"
    delete_on_termination = true
  }
}
</code>```

If it is to upload to S3 and copy it into EC2 instance and run it as a shell script, then would not need to upload to S3 then copy it into EC2 instances with AWS CLI S3 commands or mounting the S3 bucket inside EC2 using e.g. S3 Fuse.

S3 upload

First, use https://www.terraform.io/docs/providers/local/r/file.html

```<code>resource "local_file" "userdata_sh" {
  content  = data.template_file.user_data.rendered
  filename = "your_local_userdata_sh_path"
}
</code>```

Then use https://www.terraform.io/docs/providers/aws/r/s3_bucket_object.html to upload to S3.

```<code>resource "aws_s3_bucket_object" "object" {
  bucket = "your_s3_bucket_name"
  key    = "userdata.sh"
  source = "your_local_userdata_sh_path"

  etag = "${filemd5("your_local_userdata_sh_path")}"
}
</code>```

URL in template resource

Will not be possible. Template file needs to be in your local machine. If sharing the userdata.sh is the goal, then consider mounting S3 in your machine using e.g. S3 Fuse.

Body:
Terraform Version = 0.12

data "template_file" "user_data" {
  template = file("${path.module}/userdata.sh")
}

resource "aws_instance" "bespin-ec2-web-a" {
  ami = "ami-0bea7fd38fabe821a"
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.bespin-sg.id]
  subnet_id = aws_subnet.bespin-subnet-public-a.id
  associate_public_ip_address = true
  tags = {
    Name = "bespin-ec2-web-a"
  }
  user_data = data.template_file.user_data.rendered
}

I want to upload user_data to S3 and use it by calling URL.
What can I do?

ex)

resource "template_file" "userdata_sh" {
  template = "https://test.s3.ap-northeast-2.amazonaws.com/userdata.sh"
}

Body:
Not 100% clear what is to be achieved, however, if to specify userdata for EC2 instances to use, then use a sh file in S3 would not be possible.

Need to specify userdata content directly to aws_instance terraform resource.

EC2/userdata

resource "aws_instance" "this" {
  ami = "${local.ami_this_id}"
  instance_type = "${var.instance_type}"
  subnet_id = "${var.subnet_id}"
  vpc_security_group_ids = "${var.security_group_ids}"
  key_name = "${aws_key_pair.this.key_name}"
  iam_instance_profile = "${var.ec2_instance_profile_id}"

  user_data = data.template_file.user_data.rendered   # <----- Specify userdata content

  root_block_device {
    volume_type = "${var.root_volume_type}"
    volume_size = "${var.root_volume_size}"
    delete_on_termination = true
  }
}

If it is to upload to S3 and copy it into EC2 instance and run it as a shell script, then would not need to upload to S3 then copy it into EC2 instances with AWS CLI S3 commands or mounting the S3 bucket inside EC2 using e.g. S3 Fuse.

S3 upload

First, use https://www.terraform.io/docs/providers/local/r/file.html

resource "local_file" "userdata_sh" {
  content  = data.template_file.user_data.rendered
  filename = "your_local_userdata_sh_path"
}

Then use https://www.terraform.io/docs/providers/aws/r/s3_bucket_object.html to upload to S3.

resource "aws_s3_bucket_object" "object" {
  bucket = "your_s3_bucket_name"
  key    = "userdata.sh"
  source = "your_local_userdata_sh_path"

  etag = "${filemd5("your_local_userdata_sh_path")}"
}

URL in template resource

Will not be possible. Template file needs to be in your local machine. If sharing the userdata.sh is the goal, then consider mounting S3 in your machine using e.g. S3 Fuse.


问:
StackOverflowException when trying to make label scroll
When making a label scroll, when the information is to large, I get a StackOverflow Exception.

Code in question:

If anyone knows of a fix, please answer below.

```<code>private async Task LblScroll(int time)
{
    lblScroll.Location = new Point(lblScroll.Location.X - 5, lblScroll.Location.Y);
    if (lblScroll.Location.X < (-lblScroll.Width))
    {
        if (stopScroll)
            return;
        else
            lblScroll.Location = new Point(this.ClientSize.Width + lblScroll.Text.Length, lblScroll.Location.Y);
    }

    if (!stopScroll)
    {
        await Task.Delay(time);
        await LblScroll(time);
    }
    else
        return;
}
</code>```

答:
The issue has been resolved.

I had to switch from using awaits to timers. This worked like a charm.

Body:
When making a label scroll, when the information is to large, I get a StackOverflow Exception.

Code in question:

If anyone knows of a fix, please answer below.

private async Task LblScroll(int time)
{
    lblScroll.Location = new Point(lblScroll.Location.X - 5, lblScroll.Location.Y);
    if (lblScroll.Location.X < (-lblScroll.Width))
    {
        if (stopScroll)
            return;
        else
            lblScroll.Location = new Point(this.ClientSize.Width + lblScroll.Text.Length, lblScroll.Location.Y);
    }

    if (!stopScroll)
    {
        await Task.Delay(time);
        await LblScroll(time);
    }
    else
        return;
}


问:
Detect status of an input caret under any or most Linux DE's?
So I have come up with this solution for Gnome 3 w/ ibus, but I need something that also works under KDE and XFCE or not be DE dependent at all. I just need to know if a text field is currently waiting for input and this is the solution that currently works under Ubuntu 19.10.

I just need to make it more cross compatible with other DE's.

```<code>IBUSADD=$(cat ~/.config/ibus/bus/`ls ~/.config/ibus/bus -1rt | tail -n1` | awk -F'IBUS_ADDRESS=' '{print $2}' | xargs)

dbus-monitor --address $IBUSADD "path='/org/freedesktop/IBus/Panel/Extension/Emoji',interface='org.freedesktop.IBus.Panel',member='FocusOut'"
</code>```

If ibus needs to be installed then this is what I install, but under GalliumOS (xfce) I still don't have access to the org.freedesktop.ibus.panel location. I need to find another way.

```<code># Actually ibus-mozc ibus-anthy installs japanese support -
# may not need to do that just to run ibus-setup..
# unless it brings in missing dependencies for ibus-setup?
sudo apt-get install ibus-mozc ibus-anthy
ibus-setup
</code>```

I'd also be more than happy to see any solutions written in C, but a bash or scripting language solution will work just fine as that is what I currently have.

答:
Pretty sure I just found an answer that resolved this more or less. Alternatives will be appreciated, but I now realized that the other system I installed ibus on just needed to have its keyboard input moved to use ibus via the drop down menu.

The command to enable it as found elsewhere, would like to query it too, but can't seem to find a get command.

```<code>im-config -n ibus
</code>```

Additionally the above solution actually works if the filter is less specific. Removing any mention of the Emoji extension, which may or may not be enabled is sufficient and the solution then compatible with any DE that works with IBus from what I can tell.

```<code>path='/org/freedesktop/IBus/Panel
</code>```

Body:
So I have come up with this solution for Gnome 3 w/ ibus, but I need something that also works under KDE and XFCE or not be DE dependent at all. I just need to know if a text field is currently waiting for input and this is the solution that currently works under Ubuntu 19.10.

I just need to make it more cross compatible with other DE's.

IBUSADD=$(cat ~/.config/ibus/bus/`ls ~/.config/ibus/bus -1rt | tail -n1` | awk -F'IBUS_ADDRESS=' '{print $2}' | xargs)

dbus-monitor --address $IBUSADD "path='/org/freedesktop/IBus/Panel/Extension/Emoji',interface='org.freedesktop.IBus.Panel',member='FocusOut'"

If ibus needs to be installed then this is what I install, but under GalliumOS (xfce) I still don't have access to the org.freedesktop.ibus.panel location. I need to find another way.

# Actually ibus-mozc ibus-anthy installs japanese support -
# may not need to do that just to run ibus-setup..
# unless it brings in missing dependencies for ibus-setup?
sudo apt-get install ibus-mozc ibus-anthy
ibus-setup

I'd also be more than happy to see any solutions written in C, but a bash or scripting language solution will work just fine as that is what I currently have.

Body:
Pretty sure I just found an answer that resolved this more or less. Alternatives will be appreciated, but I now realized that the other system I installed ibus on just needed to have its keyboard input moved to use ibus via the drop down menu.

The command to enable it as found elsewhere, would like to query it too, but can't seem to find a get command.

im-config -n ibus

Additionally the above solution actually works if the filter is less specific. Removing any mention of the Emoji extension, which may or may not be enabled is sufficient and the solution then compatible with any DE that works with IBus from what I can tell.

path='/org/freedesktop/IBus/Panel


问:
NSURLConnection Download multiple images
I am trying to download multiple images from a URL stored in an XML feed. Getting the image urls from the XML is working correctly. However, the NSURLConnection is creating empty files, but the data is received as noted in NSLog. In connectionDidFinishLoading:(NSURLConnection *)connection, the data and correct bytes are received, the problem is how do I make the receivedData write to the correct file.

Semi-working code:

```<code>-(void)parsingComplete:(XMLDataSource*)theParser
{
    /*  iterate through the Categories and create the
        sub-directory if it does not exist
     */
    for (int i = 0; i < [categories count]; i++) {
        NSString *cat      = [NSString stringWithFormat:@"%@/%@",BASE_DIR,[[categories objectAtIndex:i] objectForKey:@"name"]];
        NSString *catName  = [[categories objectAtIndex:i] objectForKey:@"name"];
        NSArray  *catArray = [[categories objectAtIndex:i] objectForKey:@"images"];

        /*  create the sub-direcotry naming it the #category# key  */
        if (![FILEMANAGER fileExistsAtPath:cat]) {
            [FILEMANAGER createDirectoryAtPath:cat withIntermediateDirectories:NO attributes:nil error:nil];
        }

        //NSLog(@"\n\nCategory: %@",cat);
        for (int x = 0; x < [catArray count]; x++) {
            //NSLog(@"Image: %@",[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]);
            /*  download each file to the corresponding category sub-directory  */
            fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];

            NSURLRequest *imageRequest =
            [NSURLRequest requestWithURL:[NSURL URLWithString:[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]]
                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
            NSURLConnection *imageConnection = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];

            int counter = 0;
            //BOOL result = NO;
            if(imageConnection)
            {
                NSLog(@"Counter: %i",counter++);
                receivedData = [[NSMutableData data] retain];
                /*result = */[receivedData writeToFile:fileOut atomically:YES];
            }
            /*
                if (!result) NSLog(@"Failed"); else NSLog(@"Successful");
             */
        }
    }
}

#pragma mark NSURLConenction

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {
    [receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {
    [receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    // release the connection, and the data object
    //[receivedData release];
}
</code>```

答:
You have to wait until the connection tells you it has finished before you can write the data. The connection is handled on another thread; if you try to access the data immediately on the original thread as you're doing, there won't be anything in it.

You should move the writeToFile: call to the end of connectionDidFinishLoading:, or to another method that you call from there. That's the first point where you know that the data has all been collected.

I'd also suggest creating the NSMutableData instance in didRecieveResponse:, so that you know that it is available at the correct time. That will be more readable/understandable. You can think of the delegate methods as a collective "scope" -- the data is only used inside of them, so it should be created inside of one of them.

In reply to your comment:

One possibility, since you have so much that needs to be done around this one download, and don't seem to be touching the GUI, is to run the whole parsingComplete: method on a background thread, and using +[NSURLConnection sendSynchronousRequest:returningResponse:error:]. This way your code will just wait until the data comes back, in one piece, and you can write it immediately after the sendSynchronous... call returns.

```<code>NSError * err;
NSURLResponse * response;
NSData * receivedData = [NSURLConnection sendSynchronousRequest:imageRequest
                                              returningResponse:&response
                                                          error:&err];
if( !receivedData ){
    /* Handle error */
}
/* Check response */

BOOL result = [receivedData writeToFile:fileOut atomically:YES];
/* check result, etc. */
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to download multiple images from a URL stored in an XML feed. Getting the image urls from the XML is working correctly. However, the NSURLConnection is creating empty files, but the data is received as noted in NSLog. In connectionDidFinishLoading:(NSURLConnection *)connection, the data and correct bytes are received, the problem is how do I make the receivedData write to the correct file.

Semi-working code:

-(void)parsingComplete:(XMLDataSource*)theParser
{
    /*  iterate through the Categories and create the
        sub-directory if it does not exist
     */
    for (int i = 0; i < [categories count]; i++) {
        NSString *cat      = [NSString stringWithFormat:@"%@/%@",BASE_DIR,[[categories objectAtIndex:i] objectForKey:@"name"]];
        NSString *catName  = [[categories objectAtIndex:i] objectForKey:@"name"];
        NSArray  *catArray = [[categories objectAtIndex:i] objectForKey:@"images"];

        /*  create the sub-direcotry naming it the #category# key  */
        if (![FILEMANAGER fileExistsAtPath:cat]) {
            [FILEMANAGER createDirectoryAtPath:cat withIntermediateDirectories:NO attributes:nil error:nil];
        }

        //NSLog(@"\n\nCategory: %@",cat);
        for (int x = 0; x < [catArray count]; x++) {
            //NSLog(@"Image: %@",[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]);
            /*  download each file to the corresponding category sub-directory  */
            fileOut = [NSString stringWithFormat:@"%@/%@_0%i.jpg",cat,catName,x];

            NSURLRequest *imageRequest =
            [NSURLRequest requestWithURL:[NSURL URLWithString:[[catArray objectAtIndex:x] objectForKey:@"imageUrl"]]
                             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];
            NSURLConnection *imageConnection = [[NSURLConnection alloc] initWithRequest:imageRequest delegate:self];

            int counter = 0;
            //BOOL result = NO;
            if(imageConnection)
            {
                NSLog(@"Counter: %i",counter++);
                receivedData = [[NSMutableData data] retain];
                /*result = */[receivedData writeToFile:fileOut atomically:YES];
            }
            /*
                if (!result) NSLog(@"Failed"); else NSLog(@"Successful");
             */
        }
    }
}

#pragma mark NSURLConenction

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  {
    [receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  {
    [receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // release the connection, and the data object
    [connection release];
    // receivedData is declared as a method instance elsewhere
    [receivedData release];
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
    NSString *aStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    // release the connection, and the data object
    //[receivedData release];
}

Body:
You have to wait until the connection tells you it has finished before you can write the data. The connection is handled on another thread; if you try to access the data immediately on the original thread as you're doing, there won't be anything in it.

You should move the writeToFile: call to the end of connectionDidFinishLoading:, or to another method that you call from there. That's the first point where you know that the data has all been collected.

I'd also suggest creating the NSMutableData instance in didRecieveResponse:, so that you know that it is available at the correct time. That will be more readable/understandable. You can think of the delegate methods as a collective "scope" -- the data is only used inside of them, so it should be created inside of one of them.

In reply to your comment:

One possibility, since you have so much that needs to be done around this one download, and don't seem to be touching the GUI, is to run the whole parsingComplete: method on a background thread, and using +[NSURLConnection sendSynchronousRequest:returningResponse:error:]. This way your code will just wait until the data comes back, in one piece, and you can write it immediately after the sendSynchronous... call returns.

NSError * err;
NSURLResponse * response;
NSData * receivedData = [NSURLConnection sendSynchronousRequest:imageRequest
                                              returningResponse:&response
                                                          error:&err];
if( !receivedData ){
    /* Handle error */
}
/* Check response */

BOOL result = [receivedData writeToFile:fileOut atomically:YES];
/* check result, etc. */


问:
python word frequencies for dictionary with values and key
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

```<code>sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)
</code>```

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

```<code>Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}
</code>```

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

答:
Another way you could do this is to create a single list, and then count frequencies in that list:

```<code>foodList = []

#creates a single list
for idx, f in enumerate(Food):
    foodList = foodList + list(Food.values())[idx]

#makes a count in that list
words_freq ={}
for word in foodList:
    if word not in words_freq:
        words_freq[word] =1
    else:
        words_freq[word] +=1
</code>```

which yields the correct answer:

```<code>{'Apple': 3, 'Milk': 2, 'Cookie': 2, 'Banana': 2, 'Orange': 4, 'Potato': 2, 'Chocolate': 2, 'Mango': 3, 'Fish': 2, 'Beef': 1, 'Pork': 2}
</code>```

Body:
I am a first-time learner of python, I understand how to use word frequencies to count the number of each unique variable of a list, like this

sentence = ['hello', 'people', 'are', 'the', 'most', 'common', 'word', 'people', 'use', 'for', 'language ', 'learning']

words_freq ={} #dictionary for the counts
for word in sentence:
    if word not in words_freq:

        words_freq[word] =1
    else:

        words_freq[word] +=1

print (words_freq)

however, I wonder how could a word frequencies do on the dictionary by using a double for loop?

for example, I have a dictionary like this

Food = {
2015: ["Apple", "Milk", "Cookie", "Banana", "Orange" ],
2016: ["Potato", "Orange", "Chocolate", "Milk", "Mango"],
2017: ["Fish", "Potato", "Orange", "Mango", "Banana"],
2018: ["Beef", "Pork", "Fish", "Apple", "Cookie"],
2019: ["Pork", "Orange", "Apple", "Mango", "Chocolate"]
}

how to do a word frequencies/count and print something like this? Or store the highest value in list form ?
apple : 3
milk : 2
orange : 3
..
..
..

Body:
Another way you could do this is to create a single list, and then count frequencies in that list:

foodList = []

#creates a single list
for idx, f in enumerate(Food):
    foodList = foodList + list(Food.values())[idx]

#makes a count in that list
words_freq ={}
for word in foodList:
    if word not in words_freq:
        words_freq[word] =1
    else:
        words_freq[word] +=1

which yields the correct answer:

{'Apple': 3, 'Milk': 2, 'Cookie': 2, 'Banana': 2, 'Orange': 4, 'Potato': 2, 'Chocolate': 2, 'Mango': 3, 'Fish': 2, 'Beef': 1, 'Pork': 2}


问:
A collection of closest values from two arrays
I'm looking for optimization of an algorithm to solve a simple problem which may be hard to explain. I'm not looking for a speed or performance but simplicity and clarity when you read the code. Maybe someone has more clever solution than mine. I imagine one-liner would probably be an overkill.

I have two collections of cells ordered by date. Each of the cell can have a price value. We can assume that there can't be a price in two cells for the same date. I want to have one collection of dates, but where is no price for the date:

which collection have a closest price from the past

if there is no price in the past, look in the future

Here's what I have so far (it gives accurate results):

const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
];

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
];

const merged = Object.values(array1).map((element, index) => {
  let filled;
  if (element.price) {
    filled = 1;
  }
  if (array2[index].price) {
    filled = 2;
  }
  if (filled) {
    return {
      date: element.date,
      filled
    }
  } else {
    return {
      date: element.date
    }
  }
});

const first = merged.find(element => element.filled);

let currentFill = first && first.filled;

const emptyMap = merged.map((element, index, array) => {
  if (!element.filled) {
    return {
      date: element.date,
      empty: currentFill
    }
  }
  currentFill = element.filled;
  return element;
})

console.log(emptyMap);```

答:
const array1 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12' },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15', price: 10 },
  { date: '2019-11-16' },
];

const array2 = [
  { date: '2019-11-10' },
  { date: '2019-11-11' },
  { date: '2019-11-12', price: 10 },
  { date: '2019-11-13' },
  { date: '2019-11-14' },
  { date: '2019-11-15' },
  { date: '2019-11-16' },
];

function collect(collection1, collection2) {
  let firstEmptyId = null
  let currentId = null
  let indexes = [/* [1] optimization */]
  let collection = collection1.map(({ date, price }, i) => (
    ((price && (currentId = 1)) || (collection2[i].price && (currentId = 2)))
      ? ((firstEmptyId || (firstEmptyId = currentId)), { date, filled: currentId })
      : ((firstEmptyId || /*see[1]*/ indexes.push(i)), { date, empty: currentId })
  ))
  // only two iterations => index.length === 2
  indexes.forEach((i) => (collection[i].empty = firstEmptyId))
  return collection
}

console.log(collect(array1, array2))```


问:
Flex box horizontal alignment
I'm trying to get various divs to align horizontally, but they keep stacking vertically. What's the best way to fix this? My current code has other elements which aligns the flex box elements in a row, but on re-size they revert to stacking vertically and I've got a hunch it's something to do with the base code here:

CSS

```<code>.flex-container
{
    width: 100px;
    padding: 0;
    margin: 0;
    list-style: none;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    display: inline-block;
    -webkit-flex-flow: row;
    transition: opacity .2s ease-in-out;
}

.flex-item
{
    text-align: center;
    text-decoration: none;
    color: #ffffff;
    font-family: sansa_normal;

    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: calc(12px + (26 - 18) * ((100vw - 300px) / (1600 - 300)));
}

.flex-item:before
{
    content: '';
    float: left;
    padding-top: 100%;
}

.dark-box-p
{
    background: #8f6cda;
    transition: opacity .2s ease-in-out;
    opacity: 1;
}

.med-box-p
{
    background: #a68fd8;
    transition: opacity .2s ease-in-out;
    opacity: 1;
}

.light-box-p
{
    background: #b5a5d7;
    transition: opacity .2s ease-in-out;
    opacity: 1;
}
</code>```

HTML

```<code><div class="contentbox">
<div class="flex-container">
<div class="dark-box-p flex-item">
    <span>TEST</span>
</div>
</div>
</div>

<div class="contentbox">
<div class="flex-container">
<div class="med-box-p flex-item">
    <span>TEST</span>
</div>
</div>
</div>

<div class="contentbox">
<div class="flex-container">
<div class="light-box-p flex-item">
    <span>TEST</span>
</div>
</div>
</div>
</code>```

Codepen:

https://codepen.io/adms2000/pen/LYVZpey

Thanks!

答:
So you seem to be a bit confused on how flexbox works. Flex should be applied to the parent container, then the inner elements will conform to the flex alignment. Right now you don't have a parent element that all three elements have in common, you're splitting them up into individual containers.

So just remove the additional wrapping tags and have the flex-items inside a single container, then apply flex to that container. You also don't need to have flex-flow if you're doing row that's the default, and float shouldn't be in there.

.flex-container {
  width: 100px;
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  transition: opacity 0.2s ease-in-out;
}

.flex-item {
  text-align: center;
  text-decoration: none;
  color: #ffffff;
  font-family: sansa_normal;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: calc(12px + (26 - 18) * ((100vw - 300px) / (1600 - 300)));
  padding: 2rem;
}

.dark-box-p {
  background: #8f6cda;
  transition: opacity 0.2s ease-in-out;
  opacity: 1;
}

.med-box-p {
  background: #a68fd8;
  transition: opacity 0.2s ease-in-out;
  opacity: 1;
}

.light-box-p {
  background: #b5a5d7;
  transition: opacity 0.2s ease-in-out;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contentbox">
  <div class="flex-container">
    <div class="dark-box-p flex-item">
        <span>TEST</span>
    </div>
    <div class="med-box-p flex-item">
        <span>TEST</span>
    </div>
    <div class="light-box-p flex-item">
        <span>TEST</span>
    </div>
  </div>
</div></code>```

Title: Flex box horizontal alignment

Body:
I'm trying to get various divs to align horizontally, but they keep stacking vertically. What's the best way to fix this? My current code has other elements which aligns the flex box elements in a row, but on re-size they revert to stacking vertically and I've got a hunch it's something to do with the base code here:

CSS

.flex-container
{
    width: 100px;
    padding: 0;
    margin: 0;
    list-style: none;
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    display: inline-block;
    -webkit-flex-flow: row;
    transition: opacity .2s ease-in-out;
}

.flex-item
{
    text-align: center;
    text-decoration: none;
    color: #ffffff;
    font-family: sansa_normal;

    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: calc(12px + (26 - 18) * ((100vw - 300px) / (1600 - 300)));
}

.flex-item:before
{
    content: '';
    float: left;
    padding-top: 100%;
}

.dark-box-p
{
    background: #8f6cda;
    transition: opacity .2s ease-in-out;
    opacity: 1;
}

.med-box-p
{
    background: #a68fd8;
    transition: opacity .2s ease-in-out;
    opacity: 1;
}

.light-box-p
{
    background: #b5a5d7;
    transition: opacity .2s ease-in-out;
    opacity: 1;
}

HTML

    TEST

    TEST

    TEST

Codepen:

https://codepen.io/adms2000/pen/LYVZpey

Thanks!

Body:
So you seem to be a bit confused on how flexbox works. Flex should be applied to the parent container, then the inner elements will conform to the flex alignment. Right now you don't have a parent element that all three elements have in common, you're splitting them up into individual containers.

So just remove the additional wrapping tags and have the flex-items inside a single container, then apply flex to that container. You also don't need to have flex-flow if you're doing row that's the default, and float shouldn't be in there.

.flex-container {
  width: 100px;
  padding: 0;
  margin: 0;
  list-style: none;
  display: flex;
  transition: opacity 0.2s ease-in-out;
}

.flex-item {
  text-align: center;
  text-decoration: none;
  color: #ffffff;
  font-family: sansa_normal;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: calc(12px + (26 - 18) * ((100vw - 300px) / (1600 - 300)));
  padding: 2rem;
}

.dark-box-p {
  background: #8f6cda;
  transition: opacity 0.2s ease-in-out;
  opacity: 1;
}

.med-box-p {
  background: #a68fd8;
  transition: opacity 0.2s ease-in-out;
  opacity: 1;
}

.light-box-p {
  background: #b5a5d7;
  transition: opacity 0.2s ease-in-out;
  opacity: 1;
}

<div class="contentbox">
  <div class="flex-container">
    <div class="dark-box-p flex-item">
        <span>TEST</span>
    </div>
    <div class="med-box-p flex-item">
        <span>TEST</span>
    </div>
    <div class="light-box-p flex-item">
        <span>TEST</span>
    </div>
  </div>
</div>


问:
How to know the Type of a Property if it is collection in Reflection?
```<code>List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;
</code>```

Consider the MyClassPro is null. In situation of Reflection i wont be knowing the Classname or Property Name.

If i try to get the Type of property using GetType like ,

```<code>      Type t = obj.GetType();
</code>```

It is returning "System.Collections.Generic.list. But my expectation is to get the Type as MyClass.

I also tried the way like

```<code>        foreach(PropertyInfo propertyInfo in obj.GetProperties())
        {
             if(propertyInfo.IsGenericType)
             {
              Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
             }
        }
</code>```

But it is returning error because of the Value of the collection property is null so we cant get the Type.

In this situation how can i get the Type of a collection Property.

Please help me !

Thanks in Advance.

答:
Use propertyInfo.PropertyType instead of propertyInfo.GetValue(obj,null).GetType() which should give you the property type even if the property value is null.

So when you have a class like

```<code>public class Foo {
    public List<string> MyProperty { get; set; }
}
</code>```

and an instance of Foo in obj, then

```<code>var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example
var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0];
</code>```

will give you the value System.String (as a System.Type instance) in typeArg.

Body:
List<MyClass> MyClassPro
{
   get;set;
}

MyClass obj = new MyClass();

obj.MyClassPro = null;

Consider the MyClassPro is null. In situation of Reflection i wont be knowing the Classname or Property Name.

If i try to get the Type of property using GetType like ,

      Type t = obj.GetType();

It is returning "System.Collections.Generic.list. But my expectation is to get the Type as MyClass.

I also tried the way like

        foreach(PropertyInfo propertyInfo in obj.GetProperties())
        {
             if(propertyInfo.IsGenericType)
             {
              Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
             }
        }

But it is returning error because of the Value of the collection property is null so we cant get the Type.

In this situation how can i get the Type of a collection Property.

Please help me !

Thanks in Advance.

Body:
Use propertyInfo.PropertyType instead of propertyInfo.GetValue(obj,null).GetType() which should give you the property type even if the property value is null.

So when you have a class like

public class Foo {
    public List<string> MyProperty { get; set; }
}

and an instance of Foo in obj, then

var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example
var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0];

will give you the value System.String (as a System.Type instance) in typeArg.


问:
Problem with reading last line of code algorithm - c++
I found this code on Stackoverflow:

```<code>    if (file.is_open())
    {
        file.seekg(-1, std::ios_base::end);
        if (file.peek() == '\n')
        {
            //Start searching for \n occurrences
            file.seekg(-1, std::ios_base::cur);
            int i = file.tellg();
            for (i;i > 0; i--)
            {
                if (file.peek() == '\n')
                {
                    //Found
                    file.get();
                    break;
                }
                //Move one character back
                file.seekg(i, std::ios_base::beg);
            }
                string line;
                getline(file,line);
        }
</code>```

It saves the last line of file in variable 'line', and it works ok, but if the last line is the first line it doesn't read the first character of line (the rest is read). When the last line is eg.the third line everything works. What's the problem?

答:
Here follows a solution. It uses another method that requires the whole file to be read into a string. But it seems to solve your issue.
This function will return the last line of a text file.

```<code>std::string get_last_line(const std::string& s_file_name)
{
    std::ifstream file(s_file_name);

    std::string str((std::istreambuf_iterator<char>(file)),
                     std::istreambuf_iterator<char>());

    std::size_t p = str.find_last_of("\n");

    if (p != std::string::npos)
        return str.substr(p+1, str.length() - p);

    return str;
}
</code>```

Although it uses more memory, I believe this code will run faster since it does not require several calls to the OS file system.

Body:
I found this code on Stackoverflow:

    if (file.is_open())
    {
        file.seekg(-1, std::ios_base::end);
        if (file.peek() == '\n')
        {
            //Start searching for \n occurrences
            file.seekg(-1, std::ios_base::cur);
            int i = file.tellg();
            for (i;i > 0; i--)
            {
                if (file.peek() == '\n')
                {
                    //Found
                    file.get();
                    break;
                }
                //Move one character back
                file.seekg(i, std::ios_base::beg);
            }
                string line;
                getline(file,line);
        }

It saves the last line of file in variable 'line', and it works ok, but if the last line is the first line it doesn't read the first character of line (the rest is read). When the last line is eg.the third line everything works. What's the problem?

Body:
Here follows a solution. It uses another method that requires the whole file to be read into a string. But it seems to solve your issue.
This function will return the last line of a text file.

std::string get_last_line(const std::string& s_file_name)
{
    std::ifstream file(s_file_name);

    std::string str((std::istreambuf_iterator<char>(file)),
                     std::istreambuf_iterator<char>());

    std::size_t p = str.find_last_of("\n");

    if (p != std::string::npos)
        return str.substr(p+1, str.length() - p);

    return str;
}

Although it uses more memory, I believe this code will run faster since it does not require several calls to the OS file system.


问:
Global.asax is a HttpHandler or HttpModule?
I was asked in a interview about Global.asax and its functionality,and then asked me what is regarded between the HttpHandler and HttpModule? i answered HttpModule, based on my understanding that HttpModule is in request pipeline and HttpHandler is responsible for generating response.

But when i looked at Global.asax base classes i saw that its inherited from IHttpHandler .

Why Global.asax should be regarded a handler while it is not Handling requests?

答: Global.asax implements IHttpHandler (among other interfaces) but also derives from the base class HttpApplication, and yes it does handle requests as you can see from decompiling HttpApplication.</p>


问:
How can i string a single image url to my flutter app from firebase?
i'm trying to string a image url to a flutter networkimage widget from my firebase database document .

```<code>Image( image: NetworkImage('eventurl'),
</code>```

can anyone help me with this plz.

```<code>body: SafeArea(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Container (
            color: Colors.yellowAccent,
            child: Center(child: Text('FREATURED EVENT',
              style: TextStyle(
                letterSpacing: 10.5,
              ),
            ),
            ),
          ),
          Image( image: NetworkImage('eventurl'),
          ),
        ],
      ),
    ),
</code>```

答:
If I understand correctly, you already have the URL and want to show in UI, to this, use the Image widget with factory method network, like this:

```<code>...Container(child: Image.network('https://YOURURLIMAGEHERE.COM')),
</code>```

To get the image, put your code into a function that returns a Future and is async, like below:

```<code>Future<MyDocument> readDocumentFromDatabase() async {...access firebase and retrieve data }
</code>```

After that, use FutureBuilder widget to call this function, example:

```<code>@override
Widget build(BuildContext context) {
return FutureBuilder(
  future: readDocumentFromDatabase(),
  builder: (context, snapshot) {

    if(snapshot.hasData == false) { return CircularProgressIndicator(); }

    return Container(child: Image.network(snapshot.data.eventUrl));
},);
</code>```

to see how to implement readDocumentFromDatabase see https://medium.com/47billion/how-to-use-firebase-with-flutter-e4a47a7470ce

[]s

Body:
i'm trying to string a image url to a flutter networkimage widget from my firebase database document .

Image( image: NetworkImage('eventurl'),

can anyone help me with this plz.

body: SafeArea(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Container (
            color: Colors.yellowAccent,
            child: Center(child: Text('FREATURED EVENT',
              style: TextStyle(
                letterSpacing: 10.5,
              ),
            ),
            ),
          ),
          Image( image: NetworkImage('eventurl'),
          ),
        ],
      ),
    ),

Body:
If I understand correctly, you already have the URL and want to show in UI, to this, use the Image widget with factory method network, like this:

...Container(child: Image.network('https://YOURURLIMAGEHERE.COM')),

To get the image, put your code into a function that returns a Future and is async, like below:

Future<MyDocument> readDocumentFromDatabase() async {...access firebase and retrieve data }

After that, use FutureBuilder widget to call this function, example:

@override
Widget build(BuildContext context) {
return FutureBuilder(
  future: readDocumentFromDatabase(),
  builder: (context, snapshot) {

    if(snapshot.hasData == false) { return CircularProgressIndicator(); }

    return Container(child: Image.network(snapshot.data.eventUrl));
},);

to see how to implement readDocumentFromDatabase see https://medium.com/47billion/how-to-use-firebase-with-flutter-e4a47a7470ce

[]s