问:
Why is boto requests truncating my query string?
When trying to make a request from a lambda using botocore.vendored requests I am finding that my query string is being truncated.

I've tried to build it as a string, dict and even tried to just build an encoded url but they all seem to be truncated after the first query parameter

import base64
import os
import traceback
from urllib.parse import urlencode
from botocore.vendored import requests

ORIGIN = os.environ.get('ORIGIN')

def api_proxy(event, context):

    if event['queryStringParameters']:
        myParams = urlencode(event['queryStringParameters'],'utf-8')

    url = ORIGIN + event['path']

    print("URL: " + url)
    print("Params: " + myParams)

    try:
        if myParams:
            dataRequest = requests.get(url, params=myParams)
        else:
            dataRequest = requests.get(url)
        print("Requested URL: " + dataRequest.url)
    except:
        traceback.print_exc()
```

<p>I am printing three different parts of the process and this is what I am getting:</p>

```URL: https://{my_domain}/premium/data/DefinedImage/png

Params: minY=47.00&minX=-15.00&maxY=61.00&maxX=5.00&width=1000&RUN=2019-05-30T09%3A00%3A00Z&styles=&FORECAST=%2B0&height=1200

Requested URL: https://{my_domain}/premium/data/DefinedImage/png?minY=47.00
```

I would expect the requested URL to be the full URL with all params at the end but the request.get appears to be truncating my URL at the first ampersand.

答:
requests methods accept data as a dictionary or byte string. This is done in Python by beginning a string encoded as bytes with a b, for instance: b"my string"

If passing parameters in as bytes, you may want to use the bytes encoding:

```<code>urllib.parse.urlencode(event['queryStringParameters'])
</code>```

Body:
When trying to make a request from a lambda using botocore.vendored requests I am finding that my query string is being truncated.

I've tried to build it as a string, dict and even tried to just build an encoded url but they all seem to be truncated after the first query parameter

import base64
import os
import traceback
from urllib.parse import urlencode
from botocore.vendored import requests

ORIGIN = os.environ.get('ORIGIN')

def api_proxy(event, context):

    if event['queryStringParameters']:
        myParams = urlencode(event['queryStringParameters'],'utf-8')

    url = ORIGIN + event['path']

    print("URL: " + url)
    print("Params: " + myParams)

    try:
        if myParams:
            dataRequest = requests.get(url, params=myParams)
        else:
            dataRequest = requests.get(url)
        print("Requested URL: " + dataRequest.url)
    except:
        traceback.print_exc()

I am printing three different parts of the process and this is what I am getting:

URL: https://{my_domain}/premium/data/DefinedImage/png

Params: minY=47.00&minX=-15.00&maxY=61.00&maxX=5.00&width=1000&RUN=2019-05-30T09%3A00%3A00Z&styles=&FORECAST=%2B0&height=1200

Requested URL: https://{my_domain}/premium/data/DefinedImage/png?minY=47.00

I would expect the requested URL to be the full URL with all params at the end but the request.get appears to be truncating my URL at the first ampersand.

Body:
requests methods accept data as a dictionary or byte string. This is done in Python by beginning a string encoded as bytes with a b, for instance: b"my string"

If passing parameters in as bytes, you may want to use the bytes encoding:

urllib.parse.urlencode(event['queryStringParameters'])


来源: stackexchange

问:
Center align li with equal height and fixed width
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

JS Fiddle Link

答:
Try display: flex; instead of table.

With that and on the first box margin-left: auto; and on the last box margin-right: auto;, a fixed width on each box, it will stay the same everytime.

You can also play with min-width: 10% and width: min-content on the boxes for other sizings/responsiveness to the content but not filling.

Your fiddle, updated: https://jsfiddle.net/vhkw6y7o/

 .box-outer {
    text-align: center;
    display: flex;
    flex-direction: row;
    background-color: #333;
    width: 100%;
  }
  .boxes {
    border: 1px dotted red;
    padding: 4px 6px;
    width: 10%;
    margin-bottom: 0;
  }
  .boxes:first-child {
    margin-left: auto;
  }
  .boxes:last-child {
    margin-right: auto;
  }
  .field-number {
    color: #de008d;
    font-size: 48px;
    font-family: sans-serif;
  }
  .field-text {
    padding-top: 10px;
    color: #fff;
  }
```

ContentLicense: CC BY-SA 4.0

Body:
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

83

    Lorem ipsum dolor sit amet, consectetur adipiscing elit,

7,800
mod tempor incididunt ut labor

65k
ut aliquip

37k
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

£250m
veniam, quis nostrud exercitation ullamco

JS Fiddle Link


问:
How to send excel as email attachment using openpyxl without saving [On The Fly]
I have been trying to send excel as email attachment using openpyxl without saving [On The Fly] in Django</p>

答:
Here's how I did it with Django 2 , Python 3 and openxl</p>

```<code>from io import BytesIO

output = BytesIO() # Create a file like object in memory
wb_object.save(output) # Write my workbook object into that memory

# Setup my email
msg = EmailMultiAlternatives(subject, "", from_email, to_email, cc=cc, bcc=bcc)

# Attach the excel file with a name, the actual attachment , and a MIMEtype.
msg.attach('my_invoice.xlsx', output.getvalue(), 'application/vnd.ms-excel')

#The content here is the email content in its body and its type which is just text.
msg.attach_alternative(content, "text/html")

# Now send it .
msg.send()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's how I did it with Django 2 , Python 3 and openxl

from io import BytesIO

output = BytesIO() # Create a file like object in memory
wb_object.save(output) # Write my workbook object into that memory

# Setup my email
msg = EmailMultiAlternatives(subject, "", from_email, to_email, cc=cc, bcc=bcc)

# Attach the excel file with a name, the actual attachment , and a MIMEtype.
msg.attach('my_invoice.xlsx', output.getvalue(), 'application/vnd.ms-excel')

#The content here is the email content in its body and its type which is just text.
msg.attach_alternative(content, "text/html")

# Now send it .
msg.send()


问:
Remove the scroll bar on a list box
I'm using a userForm in vba and I have a list box.  I want to remove the horoz. scroll bar from the bottom.  Is there a way to do this?  I don't see any option in the properties box.

答:
This can occur when you have the column width format property of the listbox set to something wide, then you size the control to the data, it will show the scroll bars.

To fix this, change the "Column Width" property under the format tab to something really small, then play around with this property and the size of the listbox control until you get it how you want, and no scroll bars are displayed.

Title: Remove the scroll bar on a list box


问:
Issue with linking graph and table to several inputs
I'm new to Shiny and have an issue with the responsiveness of my graph & table.

My merged dataset consists of two variables (Length and Size), each of them having two distinct categories: Length can be either Large or Small or and Size can be either Long or short. There are also two different units: in Volume and in Count. I would like to create an app with a single graph, where either Length or Size would be displayed in either Volume or Count.

When I simplify this task by using only part of the merged dataset, i.e. either the data1 or data2 dataset below, everything works well as I only have one selectInput() (to choose the Category).

Here is a working dummy code in which only data1 is used:

```<code>data1 <- data.frame(variable = rep("Size", 24), category = rep(c("Large","Small"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(0.9,2,3.1,3.7,4.7,5.9,106.6,207.3,329,450.6,513.3,610,6.5,9.2,10,10.8,10.7,13.6,802.6,765.3,996,1076.6,1151.3,1196))
data1$date <- as.yearmon(paste(data1$date),"%b %Y")
data2 <- data.frame(variable = rep("Length", 24), category = rep(c("Long","Short"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(1.8,6.8,4.3,1.6,8.4,11.8,362.4,290.2,148,811,1026.6,2074,9.1,4.1,18,21.6,36.3,19,361.1,1377.5,1992,3660.4,1611.8,538.2))
data1$date <- as.yearmon(paste(data1$date),"%b %Y")
merged <- rbind(data1, data2)

# Define UI for application that draws time-series
ui <- fluidPage(

  # Application title
  titlePanel("Dummy shiny"),

  # Create filters
  fluidRow(
    column(4,
           selectInput("unit", label = h4("Display the dummy data in:"),
                       unique(as.character(data1$unit)))
    ),
    column(4,
           sliderInput("date", label = h4("Select time range:"),
                       2000, 2000.5, value = c(2000, 2000.5), step = 0.1)
    )
  ),
  # Create a new row for the graph or the table (one in each tab)
  tabsetPanel(
    tabPanel("Graphical view", plotOutput("distPlot")),
    tabPanel("Data", dataTableOutput("distTable")))
)

# Define server logic required to draw the wanted time-series
server <- function(input, output) {
  dataInput <- reactive({
    data1[data1$unit==input$unit,]
  })
  output$distPlot <- renderPlot({
    ggplot(dataInput(), aes(x = date, y = quantity, fill = category)) +
      geom_area(position = "stack") +
      xlab("") + ylab("") +
      scale_x_continuous(limits = input$date, expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0))
  })
  output$distTable <- renderDataTable({
    dataInput()
  },
  extensions = "Buttons",
  options = list(
    scrollY = "300px", pageLength = 10, scrollX = TRUE, dom = "Bftsp",
    buttons = c("copy", "csv", "excel"))
  )
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

When trying to use the merged dataset instead of the data1 dataset, I need to add another selectInput() (to choose the Variable) but I get an error when running the code.

In the code above, I simply added that bit in fluidRow() :

```<code>column(4,
           selectInput("var", label = h4("Choose variable to display:"),
                       unique(as.character(merged$variable)))
    )
</code>```

and replaced the dataInput bit by:

```<code>reactive({
    merged[merged$unit==input$unit | merged$variable==input$var,]
  })
</code>```

It says "missing value where TRUE/FALSE needed". Do you have any idea why and how to solve this?

I also have two additional questions, which are much less annoying:

Is there a way to ensure that the table also responds to the time range?

Is there a way to keep dates as "%b %Y" instead of fractions in the table?

Thank you SO much for your help.

答:
OK, after a sleepless night I've actually found a solution, mostly thanks to @deanattali 's amazing tutorial available at: https://deanattali.com/blog/building-shiny-apps-tutorial/.

The issue had to do with the way I previously subset my data. Here is the full working code:

```<code>library(shiny)
library(DT)
library(zoo)
library(ggplot2)
library(dplyr)
data1 <- data.frame(variable = rep("Size", 24), category = rep(c("Large","Small"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(0.9,2,3.1,3.7,4.7,5.9,106.6,207.3,329,450.6,513.3,610,6.5,9.2,10,10.8,10.7,13.6,802.6,765.3,996,1076.6,1151.3,1196))
data2 <- data.frame(variable = rep("Length", 24), category = rep(c("Long","Short"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(1.8,6.8,4.3,1.6,8.4,11.8,362.4,290.2,148,811,1026.6,2074,9.1,4.1,18,21.6,36.3,19,361.1,1377.5,1992,3660.4,1611.8,538.2))
merged <- rbind(data1, data2)
merged$date <- as.yearmon(paste(merged$date),"%b %Y")

# Define UI for application that draws time-series
ui <- fluidPage(

  # Application title
  titlePanel("Dummy shiny"),

  # Create filters
  fluidRow(
    column(4,
           selectInput("variableInput", label = h4("Display the dummy data in:"),
                       unique(merged$variable))),
    column(4,
           selectInput("unitInput", label = h4("Display the dummy data in:"),
                       unique(merged$unit))),
    column(4,
           sliderInput("dateInput", label = h4("Select time range:"),
                       2000, 2000.5, value = c(2000, 2000.5), step = 0.1)
    )
  ),
  # Create a new row for the graph or the table (one in each tab)
  tabsetPanel(
    tabPanel("Graphical view", plotOutput("distPlot")),
    tabPanel("Data", dataTableOutput("distTable")))
)

# Define server logic required to draw the wanted time-series
server <- function(input, output) {
  filtered <- reactive({
    merged %>%
      filter(variable == input$variableInput,
             unit == input$unitInput,
             date >= input$dateInput[1],
             date <= input$dateInput[2]
    )%>%
    select(-c(1,3))
})
  })
  output$distPlot <- renderPlot({
    ggplot(filtered(), aes(x = date, y = quantity, fill = category)) +
      geom_area(position = "stack") +
      xlab("") + ylab("") +
      scale_x_continuous(limits = input$date, expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0))
  })
  output$distTable <- renderDataTable({
    filtered()
  },
  extensions = "Buttons",
  options = list(
    scrollY = "300px", pageLength = 10, scrollX = TRUE, dom = "Bftsp",
    buttons = c("copy", "csv", "excel"))
  )
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Body:
I'm new to Shiny and have an issue with the responsiveness of my graph & table.

My merged dataset consists of two variables (Length and Size), each of them having two distinct categories: Length can be either Large or Small or and Size can be either Long or short. There are also two different units: in Volume and in Count. I would like to create an app with a single graph, where either Length or Size would be displayed in either Volume or Count.

When I simplify this task by using only part of the merged dataset, i.e. either the data1 or data2 dataset below, everything works well as I only have one selectInput() (to choose the Category).

Here is a working dummy code in which only data1 is used:

data1 <- data.frame(variable = rep("Size", 24), category = rep(c("Large","Small"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(0.9,2,3.1,3.7,4.7,5.9,106.6,207.3,329,450.6,513.3,610,6.5,9.2,10,10.8,10.7,13.6,802.6,765.3,996,1076.6,1151.3,1196))
data1$date <- as.yearmon(paste(data1$date),"%b %Y")
data2 <- data.frame(variable = rep("Length", 24), category = rep(c("Long","Short"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(1.8,6.8,4.3,1.6,8.4,11.8,362.4,290.2,148,811,1026.6,2074,9.1,4.1,18,21.6,36.3,19,361.1,1377.5,1992,3660.4,1611.8,538.2))
data1$date <- as.yearmon(paste(data1$date),"%b %Y")
merged <- rbind(data1, data2)

# Define UI for application that draws time-series
ui <- fluidPage(

  # Application title
  titlePanel("Dummy shiny"),

  # Create filters
  fluidRow(
    column(4,
           selectInput("unit", label = h4("Display the dummy data in:"),
                       unique(as.character(data1$unit)))
    ),
    column(4,
           sliderInput("date", label = h4("Select time range:"),
                       2000, 2000.5, value = c(2000, 2000.5), step = 0.1)
    )
  ),
  # Create a new row for the graph or the table (one in each tab)
  tabsetPanel(
    tabPanel("Graphical view", plotOutput("distPlot")),
    tabPanel("Data", dataTableOutput("distTable")))
)

# Define server logic required to draw the wanted time-series
server <- function(input, output) {
  dataInput <- reactive({
    data1[data1$unit==input$unit,]
  })
  output$distPlot <- renderPlot({
    ggplot(dataInput(), aes(x = date, y = quantity, fill = category)) +
      geom_area(position = "stack") +
      xlab("") + ylab("") +
      scale_x_continuous(limits = input$date, expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0))
  })
  output$distTable <- renderDataTable({
    dataInput()
  },
  extensions = "Buttons",
  options = list(
    scrollY = "300px", pageLength = 10, scrollX = TRUE, dom = "Bftsp",
    buttons = c("copy", "csv", "excel"))
  )
}

# Run the application
shinyApp(ui = ui, server = server)

When trying to use the merged dataset instead of the data1 dataset, I need to add another selectInput() (to choose the Variable) but I get an error when running the code.

In the code above, I simply added that bit in fluidRow() :

column(4,
           selectInput("var", label = h4("Choose variable to display:"),
                       unique(as.character(merged$variable)))
    )

and replaced the dataInput bit by:

reactive({
    merged[merged$unit==input$unit | merged$variable==input$var,]
  })

It says "missing value where TRUE/FALSE needed". Do you have any idea why and how to solve this?

I also have two additional questions, which are much less annoying:

Is there a way to ensure that the table also responds to the time range?

Is there a way to keep dates as "%b %Y" instead of fractions in the table?

Thank you SO much for your help.

Body:
OK, after a sleepless night I've actually found a solution, mostly thanks to @deanattali 's amazing tutorial available at: https://deanattali.com/blog/building-shiny-apps-tutorial/.

The issue had to do with the way I previously subset my data. Here is the full working code:

library(shiny)
library(DT)
library(zoo)
library(ggplot2)
library(dplyr)
data1 <- data.frame(variable = rep("Size", 24), category = rep(c("Large","Small"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(0.9,2,3.1,3.7,4.7,5.9,106.6,207.3,329,450.6,513.3,610,6.5,9.2,10,10.8,10.7,13.6,802.6,765.3,996,1076.6,1151.3,1196))
data2 <- data.frame(variable = rep("Length", 24), category = rep(c("Long","Short"), each = 12), unit = rep(c("Volume", "Count"), each = 6), date = rep(c("Jan 2000", "Feb 2000", "Mar 2000", "Apr 2000", "May 2000", "Jun 2000"), times = 2), quantity = c(1.8,6.8,4.3,1.6,8.4,11.8,362.4,290.2,148,811,1026.6,2074,9.1,4.1,18,21.6,36.3,19,361.1,1377.5,1992,3660.4,1611.8,538.2))
merged <- rbind(data1, data2)
merged$date <- as.yearmon(paste(merged$date),"%b %Y")

# Define UI for application that draws time-series
ui <- fluidPage(

  # Application title
  titlePanel("Dummy shiny"),

  # Create filters
  fluidRow(
    column(4,
           selectInput("variableInput", label = h4("Display the dummy data in:"),
                       unique(merged$variable))),
    column(4,
           selectInput("unitInput", label = h4("Display the dummy data in:"),
                       unique(merged$unit))),
    column(4,
           sliderInput("dateInput", label = h4("Select time range:"),
                       2000, 2000.5, value = c(2000, 2000.5), step = 0.1)
    )
  ),
  # Create a new row for the graph or the table (one in each tab)
  tabsetPanel(
    tabPanel("Graphical view", plotOutput("distPlot")),
    tabPanel("Data", dataTableOutput("distTable")))
)

# Define server logic required to draw the wanted time-series
server <- function(input, output) {
  filtered <- reactive({
    merged %>%
      filter(variable == input$variableInput,
             unit == input$unitInput,
             date >= input$dateInput[1],
             date <= input$dateInput[2]
    )%>%
    select(-c(1,3))
})
  })
  output$distPlot <- renderPlot({
    ggplot(filtered(), aes(x = date, y = quantity, fill = category)) +
      geom_area(position = "stack") +
      xlab("") + ylab("") +
      scale_x_continuous(limits = input$date, expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0))
  })
  output$distTable <- renderDataTable({
    filtered()
  },
  extensions = "Buttons",
  options = list(
    scrollY = "300px", pageLength = 10, scrollX = TRUE, dom = "Bftsp",
    buttons = c("copy", "csv", "excel"))
  )
}

# Run the application
shinyApp(ui = ui, server = server)


问:
How get properties from object in Laravel
I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

```<code>NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}
</code>```

How can I get latitude and longitude from this object?

答:
Accessing attribute in Laravel Eloquent Model is pretty easy. It's same as accessing stdClass object's attributes.

Let's say you have variable $object that holds your object. You will access longitude and latitude attributes with:

```<code>$lat = $object->coordinates->latitude;
</code>```

Body:
I am beginner in Laravel. I use Laravel 5.8 in my project.

I have this object:

NominatimAddress {#1146 ▼
  -attribution: "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright"
  -category: "building"
  -displayName: "99, 9 Maja, Janowo, Olsztyn, powiat pomorski, pomorskie, "
  -osmType: "way"
  -osmId: 142789154
  -type: "yes"
  -coordinates: Coordinates {#1147 ▼
    -latitude: 51.51171143
    -longitude: 11.4023121
  }
  -bounds: Bounds {#1148 ▶}
  -adminLevels: AdminLevelCollection {#1149 ▶}
  -country: Country {#1152 ▶}
  -timezone: null
  -providedBy: "nominatim"
}

How can I get latitude and longitude from this object?

Body:
Accessing attribute in Laravel Eloquent Model is pretty easy. It's same as accessing stdClass object's attributes.

Let's say you have variable $object that holds your object. You will access longitude and latitude attributes with:

$lat = $object->coordinates->latitude;


问:
How i can fix freeze cypress with test my app
Some times when i test my app with cypress , i have freeze and memory leak its eat all my memory.
in console i have error with style component.
"Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once."
cant make screenshoot beacuse my pc frezee in this time.

my app on nodejs, test suite very simple.
how i can fix it? how i can close cypress if i have this memory leak?

```<code>cy.visit('/')
cy.scrollto(0,900)
cy.get('h1').click()
</code>```

答: This is a known bug in Cypress, it is currently being fixed: https://github.com/cypress-io/cypress/issues/2366</p>

Body:
Some times when i test my app with cypress , i have freeze and memory leak its eat all my memory.
in console i have error with style component.
"Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once."
cant make screenshoot beacuse my pc frezee in this time.

my app on nodejs, test suite very simple.
how i can fix it? how i can close cypress if i have this memory leak?

cy.visit('/')
cy.scrollto(0,900)
cy.get('h1').click()


问:
Find locations of all matches in a range
I would like to list the lines where there is a FAIL written.
As it sounds very simple in VBA it seems fairly complicated to integrate that in a cell formula.

So I wanted to know if there was a simple way of listing all thoses matches.

I have tried this =TEXTJOIN(",";TRUE;IF(Y23:Z90="FAIL";1;"")) just to try a function I saw on internet but it gives me #value! error and I don't know why.

I then wanted to do something like =TEXTJOIN(",";TRUE;IF(Y23:Z90="FAIL";ROW(Y23:Z90);"")) but I'm guessing this would definitely not work.

I saw that we could do it with index and aggregate but it seems really too complicated for such a simple problem. However if this is the only solution I will take a more serious look at it.

Does anyone has a better way to do what I want to do?
Thanks in advance!

答: Ok thanks to Peter, I solved my problem and {=TEXTJOIN(",";TRUE;IF(Y23:Z90="FAIL";ROW(Y23:Z90);""))} works and gives me a list of the lines.


问:
Is there an easier way to do this in python?
I want to try to find an easier way to do this and I haven't found any way to do it.

This is meant to be a menu that can be written in. I am trying to add personalized messages to the text to further make it human-like, however it seems very long and longer than it should be. sandwich_t is a question asking the user if they want a sandwich, beverage is asking the user if they want a beverage, etc.

if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with ", fries_selection, "fries, with no ketchup"
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, and a ", beverage_selection, "drink, with no fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with ", fries_selection, "fries, with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="Yes" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total you have so far ordered a", sandwich, "sandwich, with no drink, with no fries, with", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink with ", fries_selection, "fries with no ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink no fries and ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "Yes" and fries== "No" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with a", beverage_selection, "drink, no fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "Yes" and Ketchup== "No":
    print "Cashier: In total so far you have no sandwich with no drink, ", fries_selection, "fries with no ketchup."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "Yes":
    print "Cashier: In total so far you have no sandwich, no drink, no fries, with ", Ketchup_Selection, "ketchup packets."
    print "Cashier: In total it will be $", total, "alright?"
    print "You: Alright"
if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "No":
    print "Chasier: You ordered nothing. Why did you come here?"
```

答:
This is a great example of violating the DRY (Don't Repeat Yourself) principle.  You've alreay recognized that there's a lot of unfortunate repetition here, so great job!

There is indeed a much easier way to accomplish what you want.  As a bonus it will also be cleaner and more maintainable.

Notice that most of the string you're printing is the same, no matter what the customer selected.  We really just want to substitute the right keyphrases that correspond to their choices.  Here's one way you could do it:

```<code>if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "No":
    print("Chasier: You ordered nothing. Why did you come here?")
else:
    sandwich_message = "no sandwich"
    if sandwich_t == "Yes":
        sandwich_message = "a {sw} sandwich".format(sw=sandwich)

    beverage_message = "with no drink"
    if beverage == "Yes":
        beverage_message = "and a {bs} drink".format(bs=beverage_selection)

    fries_message = "with no fries"
    if fries == "Yes":
        fries_message = "with {fs} fries".format(fs=fries_selection)

    ketchup_message = "with no ketchup"
    if Ketchup == "Yes":
        ketchup_message = "with {ks} ketchup packets".format(ks=Ketchup_Selection)

    message = "Cashier: In total you have so far ordered {sm}, {bm}, {fm}, {km}.\n" \
              "Cashier: In total it will be ${total} alright?\n" \
              "You: Alright"

    print(message.format(
        sm=sandwich_message,
        bm=beverage_message,
        fm=fries_message,
        km=ketchup_message,
        total=total
    ))
</code>```

Edit:
One additional note:  It's best to establish a convention for variable names and stick to it as closely as you can.  In your example, you have some lowercase, underscored variable names (beverage_selection, fries_selection) which are good!

Try to avoid names like Ketchup_Selection.  Capitalized variable names are often used for constants and class names.  It would be better to use ketchup_selection.

Also keep in mind that Python 2 is the legacy version of the language, and you should really move to Python 3 if you don't have a compelling reason to keep using Python 2.

Body:
This is a great example of violating the DRY (Don't Repeat Yourself) principle.  You've alreay recognized that there's a lot of unfortunate repetition here, so great job!

There is indeed a much easier way to accomplish what you want.  As a bonus it will also be cleaner and more maintainable.

Notice that most of the string you're printing is the same, no matter what the customer selected.  We really just want to substitute the right keyphrases that correspond to their choices.  Here's one way you could do it:

if sandwich_t=="No" and beverage== "No" and fries== "No" and Ketchup== "No":
    print("Chasier: You ordered nothing. Why did you come here?")
else:
    sandwich_message = "no sandwich"
    if sandwich_t == "Yes":
        sandwich_message = "a {sw} sandwich".format(sw=sandwich)

    beverage_message = "with no drink"
    if beverage == "Yes":
        beverage_message = "and a {bs} drink".format(bs=beverage_selection)

    fries_message = "with no fries"
    if fries == "Yes":
        fries_message = "with {fs} fries".format(fs=fries_selection)

    ketchup_message = "with no ketchup"
    if Ketchup == "Yes":
        ketchup_message = "with {ks} ketchup packets".format(ks=Ketchup_Selection)

    message = "Cashier: In total you have so far ordered {sm}, {bm}, {fm}, {km}.\n" \
              "Cashier: In total it will be ${total} alright?\n" \
              "You: Alright"

    print(message.format(
        sm=sandwich_message,
        bm=beverage_message,
        fm=fries_message,
        km=ketchup_message,
        total=total
    ))

Edit:
One additional note:  It's best to establish a convention for variable names and stick to it as closely as you can.  In your example, you have some lowercase, underscored variable names (beverage_selection, fries_selection) which are good!

Try to avoid names like Ketchup_Selection.  Capitalized variable names are often used for constants and class names.  It would be better to use ketchup_selection.

Also keep in mind that Python 2 is the legacy version of the language, and you should really move to Python 3 if you don't have a compelling reason to keep using Python 2.


问:
CURL can not run with Domain name on local Server
i'm trying to use curl to run a local php file inside my centOs7 shared server, but i can not use curl method for my local files.
here are my example files :

```<code>--bg/
------back.php
------curl.php
</code>```

here is curl.php codes:

```<code><?php
function run_curl($data){
    //url-ify the data for the POST
    $fields_string = '';
    //foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = http_build_query($data);
    //open connection
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    //curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
    curl_setopt($ch, CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        )
    );
    curl_setopt($ch,CURLOPT_URL,'https://taskdan.com/bg/back.php');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,50); # timeout after 10 seconds, you can increase it
    //curl_setopt($ch,CURLOPT_HEADER,false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  # Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); # Some server may refuse your request if you dont pass user agent
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //execute post
    $result = curl_exec($ch);
    //print_r($result);
    //print_r((curl_getinfo($ch)));
    //error_log($result);
    //close connection
    curl_close($ch);
    return ($result);
}
echo " Output : </br>";
echo run_curl( [
    "ab" => "test"
]);
?>
</code>```

and the below my back.php codes:

```<code><?php
header("Content-Type:application/json");
echo json_encode([
    "a" => "test"
])
?>
</code>```

When I run this code, it looks like it converts my domain name to the server's public  IP address. Curl is working fine for outside of server scripts.

when i run curl with using SSH, i get this:

```<code>[root@??? ~]# curl https://taskdan.com -k
<html>Apache is functioning normally</html>
[root@??? ~]# curl http://171.22.27.118 -k
<html>Apache is functioning normally</html>
</code>```

i want to run some scripts in background, Are there any way to run a local php file with POST parameters by CURL?

答:
Are you sure that your Apache virtual host is configured for listening on all interfaces?
When you do a DNS lookup to a domain that is configured as 127.0.0.1 in your /etc/hosts the request is then pointed to the loopback interface.
Open your virtualhost configuration and search for:

```<code><VirtualHost ...>
</code>```

If it is configured as

```<code><VirtualHost 171.22.27.118:80>
</code>```

Change it to

```<code><VirtualHost *:80>
</code>```

..and try again

If you cannot edit the VirtualHost definition for any reason you can instruct cURL to make the request on a specific address/port and set the correct Host header:

```<code>curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Host: taskdan.com'
    )
);
curl_setopt($ch,CURLOPT_URL,'https://171.22.27.118/bg/back.php');
</code>```

This could help mitigate the issue but is not guaranteed to work as the problem is the webserver configuration not the source code per se.

Body:
i'm trying to use curl to run a local php file inside my centOs7 shared server, but i can not use curl method for my local files.
here are my example files :

--bg/
------back.php
------curl.php

here is curl.php codes:

<?php
function run_curl($data){
    //url-ify the data for the POST
    $fields_string = '';
    //foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    $fields_string = http_build_query($data);
    //open connection
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    //curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
    curl_setopt($ch, CURLOPT_POST,true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        )
    );
    curl_setopt($ch,CURLOPT_URL,'https://taskdan.com/bg/back.php');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,50); # timeout after 10 seconds, you can increase it
    //curl_setopt($ch,CURLOPT_HEADER,false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  # Set curl to return the data instead of printing it to the browser.
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); # Some server may refuse your request if you dont pass user agent
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    //execute post
    $result = curl_exec($ch);
    //print_r($result);
    //print_r((curl_getinfo($ch)));
    //error_log($result);
    //close connection
    curl_close($ch);
    return ($result);
}
echo " Output :
";
echo run_curl( [
    "ab" => "test"
]);
?>

and the below my back.php codes:

<?php
header("Content-Type:application/json");
echo json_encode([
    "a" => "test"
])
?>

When I run this code, it looks like it converts my domain name to the server's public  IP address. Curl is working fine for outside of server scripts.

when i run curl with using SSH, i get this:

[root@??? ~]# curl https://taskdan.com -k
Apache is functioning normally
[root@??? ~]# curl http://171.22.27.118 -k
Apache is functioning normally

i want to run some scripts in background, Are there any way to run a local php file with POST parameters by CURL?

Body:
Are you sure that your Apache virtual host is configured for listening on all interfaces?
When you do a DNS lookup to a domain that is configured as 127.0.0.1 in your /etc/hosts the request is then pointed to the loopback interface.
Open your virtualhost configuration and search for:

<VirtualHost ...>

If it is configured as

<VirtualHost 171.22.27.118:80>

Change it to

<VirtualHost *:80>

..and try again

If you cannot edit the VirtualHost definition for any reason you can instruct cURL to make the request on a specific address/port and set the correct Host header:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Host: taskdan.com'
    )
);
curl_setopt($ch,CURLOPT_URL,'https://171.22.27.118/bg/back.php');

This could help mitigate the issue but is not guaranteed to work as the problem is the webserver configuration not the source code per se.


问:
Translate one concave polygon to fit into another
I need a fast and robust way to fit one concave polygon into another.

Polygons are presented as lists of points.
Niether rotations nor scaling are allowed. Only translation. Also I'm not seeking for algorithm to find optimal emplacement.

Under the word "fast" I suppose computational complexity. I guess, assuming adjusted polygon has N vertices and destination one contains M vertices, algorithm that works for O(M*N) would be a nice one.

Or is it unreachable?

Any ideas or proofs of higher complexity are appreciated.

答:
Well, finally dyukha's comment was very useful.

For each vertex in adjusted polygon you have to find sets of vectors that make this vertex fit into destination polygon. Actually, this set of vectors can be represented on surface as: destination polygon shifted by -coordinates of this vertex

All you have to do next is to find intersection of all this polygons. I used Clipper library for this purposes. Then, choose any point from the intersection set and translate the adjusted polygon by its coordinates.

Complexity of this algorithm would be about: O(NMlog(M)) (Assuming we do not care about number of intersections between translation set polygons)

Advancement: What more, you can use the same algorithm for fitting polygon into another polygon optimally (in terms of cutting stock problem). Just iterate through interesting rotation angles (for my case I used just all possible angles between edges of polygons), apply the algorithm described above to all rotated figures and select from all possible translations one that moves adjusted polygon's gravity center to the farest position from destination polygon's gravity center.

Hope that could help anybody!

Edit: Forgot to mention. Fitting vertices is not a guarantee that edges do not cross. So on the second step you should choose the translation vector that does not result into intersecting adjusted polygon's edges with edges of the destination contour.

In my solution I used comparing square of intersection of both polygons with square of the destination contour. If they are equal, then don't care. Else choose another point.

Of course, this checks spoil performance a little bit, but it not so meaningful while finding best position of the polygon. As far as my experience says :).

Thanks Yves Daoust for amendment.


问:
Can I secure my cloud function using Firebase Auth, but without using callable cloud functions. (HTTP request only)
In my project I use a bunch of GCP services, including Firestore, Cloud Functions and Firebase auth.

Taking the fact that users are able to login via Firebase auth service, I assume that it should be possible to check and authenticate users calling my cloud function. Issue is that I can not find any docs or example of how to do that.

I understand that there are special callable functions but it doesn't suit me. I am using express for handling requests.

Is it possible to retrieve some kind of JWT token from user logged in on client side (firebase auth) then send it with request to my cloud function and then check it somehow there? Or is there any other mechanism to achieve CF protection described above?

P.S.
I saw this question, but it is not about what I am asking, because it is related to Firebase Functions and I am talking about Cloud Functions which is very similar but not exact same thing.

答:
You can very easily duplicate the effect of callable functions by mimicking the protocol that is uses.  Just send the user's token in the header of the client request, and parse that out of the headers in your function.

Callable functions use the header Authorization: Bearer <token>, but you are free to do whatever you want.  You are just passing data into the function like any other piece of data.


问:
Colour the x-values and show in legend instead of as ticks, in matplotlib (or seaborn)
I have a large df which I've grouped to plot in a bar chart.
I made this mock df to show what I mean. (And I had way too much fun creating it...)

```<code>my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my
</code>```

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True)

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

答:
Another alternative solution using matplotlib could look something like

```<code>import matplotlib.patches as mpatches

fig, ax = plt.subplots(figsize=(8, 6))

# Your dataframe "my" here

ax_ = my.groupby('tv-show').sum().plot(kind='bar', stacked=True, legend=False, ax=ax)

colors = ['r', 'g', 'b']
handles = []
for col, lab, patch in zip(colors, np.unique(my['tv-show']), ax_.axes.patches):
    patch.set_color(col)
    handles.append(mpatches.Patch(color=col, label=lab))

ax_.legend(handles=handles)
ax_.set_xticklabels([])
</code>```

Body:
I have a large df which I've grouped to plot in a bar chart.
I made this mock df to show what I mean. (And I had way too much fun creating it...)

my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True)

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

Body:
Another alternative solution using matplotlib could look something like

import matplotlib.patches as mpatches

fig, ax = plt.subplots(figsize=(8, 6))

# Your dataframe "my" here

ax_ = my.groupby('tv-show').sum().plot(kind='bar', stacked=True, legend=False, ax=ax)

colors = ['r', 'g', 'b']
handles = []
for col, lab, patch in zip(colors, np.unique(my['tv-show']), ax_.axes.patches):
    patch.set_color(col)
    handles.append(mpatches.Patch(color=col, label=lab))

ax_.legend(handles=handles)
ax_.set_xticklabels([])


问:
How can I get informations about my string using JSON?
Hello I have this string using Python :

```<code>a = '{"test0": [{"test1": [{"test2": 0, "test3": "a", "test4": "test5",
"test6": "b", "test7": {"test8": [{"test9": "", "test10": [""]}],
"test11": [{"test12": "", "test12": []}], "test13": [{"test14": "",
"test15": []}]}, "test16": 0, "test17": 0}], "test18": "", "test19": "",
"test20": 0, "test21": 0}], "test22": ""}'
</code>```

But when I try this a["test0"] it does not work... Do you have any ideas to make workable this ?

Thank you !

Body:
Hello I have this string using Python :

a = '{"test0": [{"test1": [{"test2": 0, "test3": "a", "test4": "test5",
"test6": "b", "test7": {"test8": [{"test9": "", "test10": [""]}],
"test11": [{"test12": "", "test12": []}], "test13": [{"test14": "",
"test15": []}]}, "test16": 0, "test17": 0}], "test18": "", "test19": "",
"test20": 0, "test21": 0}], "test22": ""}'

But when I try this a["test0"] it does not work... Do you have any ideas to make workable this ?

Thank you !

Body:
I'm not sure what your actual code is, but if I were to guess I would write this:

a = '{"test0": [{"test1": [{"test2": 0, "test3": "a", "test4": "test5", "test6": "b", "test7": {"test8": [{"test9": "", "test10": [""]}], "test11": [{"test12": "", "test12": []}], "test13": [{"test14": "", "test15": []}]}, "test16": 0, "test17": 0}], "test18": "", "test19": "", "test20": 0, "test21": 0}], "test22": ""}'

d = json.loads(a)

print(d['test0'])

Output:

[{'test1': [{'test2': 0, 'test3': 'a', 'test4': 'test5', 'test6': 'b', 'test7': {'test8': [{'test9': '', 'test10': ['']}], 'test11': [{'test12': []}], 'test13': [{'test14': '', 'test15': []}]}, 'test16': 0, 'test17': 0}], 'test18': '', 'test19': '', 'test20': 0, 'test21': 0}]


问:
Tensorflow giving random answers on a regression problem
I am trying to reproduce a Python exercise with Node.js using Tensorflow.js.

The objective is to simply convert Celsius to Fahrenheit using machine learning.

However, I am a noob with Tensorflow.js and it keeps giving me random answers.

I have tried multiple things like many different shapes.
I have checked that both Python and Node.js have the same models. They both have the following model :

```<code>Layer (type)                 Output shape              Param #
=================================================================
dense_Dense1 (Dense)         [null,1]                  2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0
</code>```

```<code>const tf = require("@tensorflow/tfjs-node")

function convert(c){
    return (c*1.8)+32 // Convert celsius to fahrenheit
}

var celsius = []
var fahrenheit = []

for (let i = 0; i < 20; i++) {
    var r = 100; // Keeping this only value to ensure that Tf knows the answer I also have tried with 20 different values but doesn't work
    celsius.push([r]) // Shape [20,1]
    fahrenheit.push([convert(r)]) // Push the answer (212) to the fahrenheit array
}

var model = tf.sequential();
model.add(tf.layers.dense({inputShape:[1], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['accuracy'], // Accuracy = 0
    });

    model.summary();

    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      batchSize: 20,
      verbose: false // Nothing interesting with verbose
    });
  }

c = tf.tensor(celsius)
f = tf.tensor(fahrenheit)

var training = trainModel(model, c, f)

training.then(function(args){
    var prediction = model.predict(tf.tensor([[100]]));
    prediction.print(); // Prints a random number
    console.log("Real answer = "+convert(100))
})

</code>```

The output tensor value is randomly changing every time.
Here is an example :

```<code>Tensor
     [[65.9411697],]
Real answer = 212
</code>```

答:
Adam optimizer works when i added another 3 dense more layers to the the model. but i got it to work on adam on python with just one layer.</p>

```<code>xs = []
ys = []

for (var i = -100; i < 100; i++) {
  xs.push(i)
  ys.push( i*1.8 + 32)
}

console.log(xs,ys)

model = tf.sequential({
  layers: [
    tf.layers.dense({
            units: 4,
            inputShape: [1]
        }),
        tf.layers.dense({
            units: 4,
            inputShape: [4]
        }),
        tf.layers.dense({
            units: 4,
            inputShape: [4]
        }),
        tf.layers.dense({
            units: 1,
            inputShape: [4]
        })
  ]
})

model.compile({
  loss: 'meanSquaredError',
  optimizer: 'adam'
})

var tfxs = tf.tensor2d(xs,[xs.length,1])
var tfys = tf.tensor2d(ys,[xs.length,1])

model.fit(tfxs, tfys,{epochs: 500}).then(function() {
  model.predict(tfxs).print()
})
</code>```

Body:
I am trying to reproduce a Python exercise with Node.js using Tensorflow.js.

The objective is to simply convert Celsius to Fahrenheit using machine learning.

However, I am a noob with Tensorflow.js and it keeps giving me random answers.

I have tried multiple things like many different shapes.
I have checked that both Python and Node.js have the same models. They both have the following model :

Layer (type)                 Output shape              Param #
=================================================================
dense_Dense1 (Dense)         [null,1]                  2
=================================================================
Total params: 2
Trainable params: 2
Non-trainable params: 0

const tf = require("@tensorflow/tfjs-node")

function convert(c){
    return (c*1.8)+32 // Convert celsius to fahrenheit
}

var celsius = []
var fahrenheit = []

for (let i = 0; i < 20; i++) {
    var r = 100; // Keeping this only value to ensure that Tf knows the answer I also have tried with 20 different values but doesn't work
    celsius.push([r]) // Shape [20,1]
    fahrenheit.push([convert(r)]) // Push the answer (212) to the fahrenheit array
}

var model = tf.sequential();
model.add(tf.layers.dense({inputShape:[1], units: 1}))

async function trainModel(model, inputs, labels) {
    // Prepare the model for training.
    model.compile({
      optimizer: tf.train.adam(),
      loss: tf.losses.meanSquaredError,
      metrics: ['accuracy'], // Accuracy = 0
    });

    model.summary();

    const epochs = 500;

    return await model.fit(inputs, labels, {
      epochs,
      batchSize: 20,
      verbose: false // Nothing interesting with verbose
    });
  }

c = tf.tensor(celsius)
f = tf.tensor(fahrenheit)

var training = trainModel(model, c, f)

training.then(function(args){
    var prediction = model.predict(tf.tensor([[100]]));
    prediction.print(); // Prints a random number
    console.log("Real answer = "+convert(100))
})

The output tensor value is randomly changing every time.
Here is an example :

Tensor
     [[65.9411697],]
Real answer = 212

Body:
Adam optimizer works when i added another 3 dense more layers to the the model. but i got it to work on adam on python with just one layer.

xs = []
ys = []

for (var i = -100; i < 100; i++) {
  xs.push(i)
  ys.push( i*1.8 + 32)
}

console.log(xs,ys)

model = tf.sequential({
  layers: [
    tf.layers.dense({
            units: 4,
            inputShape: [1]
        }),
        tf.layers.dense({
            units: 4,
            inputShape: [4]
        }),
        tf.layers.dense({
            units: 4,
            inputShape: [4]
        }),
        tf.layers.dense({
            units: 1,
            inputShape: [4]
        })
  ]
})

model.compile({
  loss: 'meanSquaredError',
  optimizer: 'adam'
})

var tfxs = tf.tensor2d(xs,[xs.length,1])
var tfys = tf.tensor2d(ys,[xs.length,1])

model.fit(tfxs, tfys,{epochs: 500}).then(function() {
  model.predict(tfxs).print()
})


问:
Saving preferences of document when it is a txt file
I wonder how can I save preferences of a document such as window size, position in the screen, etc when this document is just a simple txt file. (My app is a Text Editor)

I thought of NSUserDefaults and save file path but what would happen if file is moved later when the app is closed? Using NSUserDefaults is really a good idea?
I am looking for advice

Thanks

EDIT:
I added these two methods to MyDocument.m (Thanks to @somegeekintn @Black Frog)

```<code>//helper method that set NSWindow frame string in file system attributes
- (BOOL) _savePreferencesInFileAtURL:(NSURL *)absoluteURL{

    const char *path = [[absoluteURL path] fileSystemRepresentation];
    const char *name = [@"NSWindow frame" cStringUsingEncoding:NSUTF8StringEncoding];
    const char *frameCString = [NSStringFromRect([window frame]) cStringUsingEncoding:NSUTF8StringEncoding];

    int result = setxattr(path , name, frameCString, strlen(frameCString) + 1, 0, 0);
    return (result<0)? NO: YES;
}

//helper method that reads NSWindow frame string from file system attributes
- (BOOL) _readPreferencesInFileAtURL:(NSURL *)absoluteURL{

    const char *path = [[absoluteURL path] fileSystemRepresentation];
    const char *name = [@"NSWindow frame" cStringUsingEncoding:NSUTF8StringEncoding];
    char frameCString [50];

    ssize_t bytesRetrieved = getxattr(path, name, frameCString, 50, 0, 0);
    //use frameCString...

    return (bytesRetrieved<0)? NO: YES;
}
</code>```

答:
You may want to take a look at setxattr and getxattr to write and read a file's extended attributes respectively. You can put pretty much whatever you like in these attributes.

```<code>int setxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);
ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);
</code>```

setxattr man page

Body:
I wonder how can I save preferences of a document such as window size, position in the screen, etc when this document is just a simple txt file. (My app is a Text Editor)

I thought of NSUserDefaults and save file path but what would happen if file is moved later when the app is closed? Using NSUserDefaults is really a good idea?
I am looking for advice

Thanks

EDIT:
I added these two methods to MyDocument.m (Thanks to @somegeekintn @Black Frog)

//helper method that set NSWindow frame string in file system attributes
- (BOOL) _savePreferencesInFileAtURL:(NSURL *)absoluteURL{

    const char *path = [[absoluteURL path] fileSystemRepresentation];
    const char *name = [@"NSWindow frame" cStringUsingEncoding:NSUTF8StringEncoding];
    const char *frameCString = [NSStringFromRect([window frame]) cStringUsingEncoding:NSUTF8StringEncoding];

    int result = setxattr(path , name, frameCString, strlen(frameCString) + 1, 0, 0);
    return (result<0)? NO: YES;
}

//helper method that reads NSWindow frame string from file system attributes
- (BOOL) _readPreferencesInFileAtURL:(NSURL *)absoluteURL{

    const char *path = [[absoluteURL path] fileSystemRepresentation];
    const char *name = [@"NSWindow frame" cStringUsingEncoding:NSUTF8StringEncoding];
    char frameCString [50];

    ssize_t bytesRetrieved = getxattr(path, name, frameCString, 50, 0, 0);
    //use frameCString...

    return (bytesRetrieved<0)? NO: YES;
}

Body:
You may want to take a look at setxattr and getxattr to write and read a file's extended attributes respectively. You can put pretty much whatever you like in these attributes.

int setxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);
ssize_t getxattr(const char *path, const char *name, void *value, size_t size, u_int32_t position, int options);

setxattr man page


问:
Using Typescript Definitions Files from Definitely Typed with Older Version of Typescript
I've been working on a project using Typescript 1.8.10 with React and Redux. I've been trying to incorporate a couple of third party React component libraries, like React Date Picker, but I keep running into the issue that the typings files on DefinitelyTyped are created for Typescript 2.1. I would expect there to be a 1.8 branch, but I have yet to find one. Does anyone know where to find older typings files that work with TS 1.8? Do they even exist? Thanks!</p>

答:
You can also do this:
"The @types publisher tool actually tags releases based on compatibility.

To be able to install declaration files that are compatible with TypeScript 2.2, you can write

```<code>npm install @types/body-parser@ts2.2
</code>```

It's not always perfect, but it'll usually get the job done."

From this answer here

Body:
You can also do this:
"The @types publisher tool actually tags releases based on compatibility.

To be able to install declaration files that are compatible with TypeScript 2.2, you can write

npm install @types/body-parser@ts2.2

It's not always perfect, but it'll usually get the job done."

From this answer here


问:
d3/html simple div tooltip location
It's a simple test to understand a way to make a tooltip using div. I'm struggling to locate the tooltip div into where the circle is.

Instead of "d3.select(this).attr("cx")" in the div attribute, I tried
"d3.mouse(this)" and "event.pageX" but the div stays below svg regardless.

Here is the code snapshot.

```<code>var margin = {top:20, right: 20, bottom: 20, left: 20};

var svg = d3.select("#visualisation")
            .append("svg")
            .attr("width", 960)
            .attr("height", 600);

var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

g.append("circle")
    .attr("class", "circle")
    .attr("cx", 200)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "red")
    .style("opacity", 0.5);

var tooltip = d3.select("#visualisation")
            .append("div")
            .style("visibility", "hidden");

d3.select(".circle")
    .on("mouseover", mouseover)
    .on("mousemove", mousemove)
    .on("mouseout", mouseout)

function mouseover() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", "1");

    tooltip
        .style("visibility", "visible")
        // .style("opacity", 1)
}

function mousemove() {

    tooltip.html("is it visible?")
        .style("left", (d3.select(this).attr("cx")) + "px")
        .style("top", (d3.select(this).attr("cy")) + "px")

}

function mouseout() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", 0.5);

    tooltip
        .style("visibility", "hidden")
        // .style("opacity", 0);
}
</code>```

Can anyone let me know what I'm missing?

答:
You're missing the necessary CSS to position the
. Just adding position: absolute; (docs) will position the tooltip div as desired.

I know this doesn't require so much of explanation but I haven't been on SO since a while so just trying to getting back into the groove. :p

Anyway, if you're positioning the div by d3.event.pageX and d3.event.pageY, here's how it'll look:

var margin = {top:20, right: 20, bottom: 20, left: 20};

var svg = d3.select("#visualisation")
            .append("svg")
            .attr("width", 960)
            .attr("height", 600);

var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

g.append("circle")
    .attr("class", "circle")
    .attr("cx", 200)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "red")
    .style("opacity", 0.5);

var tooltip = d3.select("#visualisation")
            .append("div").classed('tooltip', true)
            .style("visibility", "hidden");

d3.select(".circle")
    .on("mouseover", mouseover)
    .on("mousemove", mousemove)
    .on("mouseout", mouseout)

function mouseover() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", "1");

    tooltip
        .style("visibility", "visible")
        // .style("opacity", 1)
}

function mousemove() {

    tooltip.html("is it visible?")
        .style("left", d3.event.pageX+'px')//(d3.select(this).attr("cx")) + "px")
        .style("top", d3.event.pageY+'px') //(d3.select(this).attr("cy")) + "px")

}

function mouseout() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", 0.5);

    tooltip
        .style("visibility", "hidden")
        // .style("opacity", 0);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#visualisation div.tooltip {
  position: absolute;
  pointer-events: none;
}</code>```

```
</div>
</div>
</p>

<p>If you're positioning it at a particular x,y (as in your snippet), it'll look like the following snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var margin = {top:20, right: 20, bottom: 20, left: 20};

var svg = d3.select("#visualisation")
            .append("svg")
            .attr("width", 960)
            .attr("height", 600);

var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

g.append("circle")
    .attr("class", "circle")
    .attr("cx", 200)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "red")
    .style("opacity", 0.5);

var tooltip = d3.select("#visualisation")
            .append("div").classed('tooltip', true)
            .style("visibility", "hidden");

d3.select(".circle")
    .on("mouseover", mouseover)
    .on("mousemove", mousemove)
    .on("mouseout", mouseout)

function mouseover() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", "1");

    tooltip
        .style("visibility", "visible")
        // .style("opacity", 1)
}

function mousemove() {

    tooltip.html("is it visible?")
        .style("left", (d3.select(this).attr("cx")) + "px")
        .style("top", (d3.select(this).attr("cy")) + "px")

}

function mouseout() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", 0.5);

    tooltip
        .style("visibility", "hidden")
        // .style("opacity", 0);
}</code>```

div#visualisation div.tooltip {
  position: absolute;
  pointer-events: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="visualisation">

</div></code>```

Additions:

Added a class 'tooltip' to this tooltip div.

Added pointer-events: none; to avoid flickering of the tooltip (take it out and you'll notice the difference)

Hope this helps.

Title: d3/html simple div tooltip location

Body:
It's a simple test to understand a way to make a tooltip using div. I'm struggling to locate the tooltip div into where the circle is.

Instead of "d3.select(this).attr("cx")" in the div attribute, I tried
"d3.mouse(this)" and "event.pageX" but the div stays below svg regardless.

Here is the code snapshot.

var margin = {top:20, right: 20, bottom: 20, left: 20};

var svg = d3.select("#visualisation")
            .append("svg")
            .attr("width", 960)
            .attr("height", 600);

var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

g.append("circle")
    .attr("class", "circle")
    .attr("cx", 200)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "red")
    .style("opacity", 0.5);

var tooltip = d3.select("#visualisation")
            .append("div")
            .style("visibility", "hidden");

d3.select(".circle")
    .on("mouseover", mouseover)
    .on("mousemove", mousemove)
    .on("mouseout", mouseout)

function mouseover() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", "1");

    tooltip
        .style("visibility", "visible")
        // .style("opacity", 1)
}

function mousemove() {

    tooltip.html("is it visible?")
        .style("left", (d3.select(this).attr("cx")) + "px")
        .style("top", (d3.select(this).attr("cy")) + "px")

}

function mouseout() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", 0.5);

    tooltip
        .style("visibility", "hidden")
        // .style("opacity", 0);
}

Can anyone let me know what I'm missing?

Body:
You're missing the necessary CSS to position the <div>. Just adding position: absolute; (docs) will position the tooltip div as desired.

I know this doesn't require so much of explanation but I haven't been on SO since a while so just trying to getting back into the groove. :p

Anyway, if you're positioning the div by d3.event.pageX and d3.event.pageY, here's how it'll look:

var margin = {top:20, right: 20, bottom: 20, left: 20};

var svg = d3.select("#visualisation")
            .append("svg")
            .attr("width", 960)
            .attr("height", 600);

var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

g.append("circle")
    .attr("class", "circle")
    .attr("cx", 200)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "red")
    .style("opacity", 0.5);

var tooltip = d3.select("#visualisation")
            .append("div").classed('tooltip', true)
            .style("visibility", "hidden");

d3.select(".circle")
    .on("mouseover", mouseover)
    .on("mousemove", mousemove)
    .on("mouseout", mouseout)

function mouseover() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", "1");

    tooltip
        .style("visibility", "visible")
        // .style("opacity", 1)
}

function mousemove() {

    tooltip.html("is it visible?")
        .style("left", d3.event.pageX+'px')//(d3.select(this).attr("cx")) + "px")
        .style("top", d3.event.pageY+'px') //(d3.select(this).attr("cy")) + "px")

}

function mouseout() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", 0.5);

    tooltip
        .style("visibility", "hidden")
        // .style("opacity", 0);
}

div#visualisation div.tooltip {
  position: absolute;
  pointer-events: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="visualisation">

</div>

If you're positioning it at a particular x,y (as in your snippet), it'll look like the following snippet:

var margin = {top:20, right: 20, bottom: 20, left: 20};

var svg = d3.select("#visualisation")
            .append("svg")
            .attr("width", 960)
            .attr("height", 600);

var g = svg.append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

g.append("circle")
    .attr("class", "circle")
    .attr("cx", 200)
    .attr("cy", 100)
    .attr("r", 50)
    .attr("fill", "red")
    .style("opacity", 0.5);

var tooltip = d3.select("#visualisation")
            .append("div").classed('tooltip', true)
            .style("visibility", "hidden");

d3.select(".circle")
    .on("mouseover", mouseover)
    .on("mousemove", mousemove)
    .on("mouseout", mouseout)

function mouseover() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", "1");

    tooltip
        .style("visibility", "visible")
        // .style("opacity", 1)
}

function mousemove() {

    tooltip.html("is it visible?")
        .style("left", (d3.select(this).attr("cx")) + "px")
        .style("top", (d3.select(this).attr("cy")) + "px")

}

function mouseout() {

    d3.select(this)
        .transition()
        .duration(500)
        .style("opacity", 0.5);

    tooltip
        .style("visibility", "hidden")
        // .style("opacity", 0);
}

div#visualisation div.tooltip {
  position: absolute;
  pointer-events: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="visualisation">

</div>

Additions:

Added a class 'tooltip' to this tooltip div.

Added pointer-events: none; to avoid flickering of the tooltip (take it out and you'll notice the difference)

Hope this helps.


问:
Pandas SettingWithCopyWarning for fillna with MultiIndex DataFrame
The line with fillna() raises the warning even though it is not performed inplace. Why is that?

import pandas as pd
import numpy as np

tuples = [('foo', 1), ('foo', 2), ('bar', 1), ('bar', 2)]
index = pd.MultiIndex.from_tuples(tuples)

df = pd.DataFrame(np.random.randn(2, 4), columns=index)
df.loc[0, ('foo', 1)] = np.nan

# this works without warning
# df = pd.DataFrame({'foo': [1, np.nan, 3], 'bar': [np.nan, 22, 33]]})

df1 = df[['foo', 'bar']]
# df1 = df[['foo', 'bar']].copy()  # this does not help
filled = df1.fillna({'foo': 100, 'bar': 200}, inplace=False)
```

The problem does not appear if foo and bar are ordinary columns, not multiindexed.

答:
This is a false positive, the warning is not supposed to be raised here. I think the issue is that fillna doesn't understand that "foo" and "bar" apply to specific levels of your MultiIndex columns.

I would recommend calling fillna inside GroupBy as a workaround until this functionality is implemented.

```<code>fill = {'foo': 100, 'bar': 200}
df1.groupby(level=0, axis=1).apply(lambda x: x.fillna(fill[x.name]))

          foo                 bar
            1         2         1         2
0  100.000000  1.040531 -1.516983 -0.866276
1   -0.055035 -0.107310  1.365467 -0.097696
</code>```

Alternatively, to use fillna directly, specify a dict of tuples (because, MultiIndex),

```<code>df1.fillna({('foo', 1): 100, ('foo', 2): 100})

          foo                 bar
            1         2         1         2
0  100.000000  1.040531 -1.516983 -0.866276
1   -0.055035 -0.107310  1.365467 -0.097696
</code>```

Body:
The line with fillna() raises the warning even though it is not performed inplace. Why is that?

import pandas as pd
import numpy as np

tuples = [('foo', 1), ('foo', 2), ('bar', 1), ('bar', 2)]
index = pd.MultiIndex.from_tuples(tuples)

df = pd.DataFrame(np.random.randn(2, 4), columns=index)
df.loc[0, ('foo', 1)] = np.nan

# this works without warning
# df = pd.DataFrame({'foo': [1, np.nan, 3], 'bar': [np.nan, 22, 33]]})

df1 = df[['foo', 'bar']]
# df1 = df[['foo', 'bar']].copy()  # this does not help
filled = df1.fillna({'foo': 100, 'bar': 200}, inplace=False)

The problem does not appear if foo and bar are ordinary columns, not multiindexed.

Body:
This is a false positive, the warning is not supposed to be raised here. I think the issue is that fillna doesn't understand that "foo" and "bar" apply to specific levels of your MultiIndex columns.

I would recommend calling fillna inside GroupBy as a workaround until this functionality is implemented.

fill = {'foo': 100, 'bar': 200}
df1.groupby(level=0, axis=1).apply(lambda x: x.fillna(fill[x.name]))

          foo                 bar
            1         2         1         2
0  100.000000  1.040531 -1.516983 -0.866276
1   -0.055035 -0.107310  1.365467 -0.097696

Alternatively, to use fillna directly, specify a dict of tuples (because, MultiIndex),

df1.fillna({('foo', 1): 100, ('foo', 2): 100})

          foo                 bar
            1         2         1         2
0  100.000000  1.040531 -1.516983 -0.866276
1   -0.055035 -0.107310  1.365467 -0.097696


问:
Store integers as integers and not as floats
I do the following:

```<code>import pandas as pd

df_texts = pd.read_csv('data_texts.csv', keep_default_na=True)

for index, row in df_texts.iterrows():

    list_of_words = row['text'].split()

    df_texts.loc[index, '#_words'] = len(list_of_words)

    list_of_unique_words = set(list_of_words)

    df_texts.loc[index, '#_unique_words'] = len(list_of_unique_words)
</code>```

The problem is that the numbers at the #_words and at the #_unique_words columns are stored as floats even though they are integers.

Just to clarify that these two columns do not pre-exist in the .csv which I read (pd.read_csv) but I create them in the for loop.

How can I directly store them as integers?

答:
If you create the column by assigning a value to a single row, all the other rows are implicitly initialized to NaN, which is a floating point value. This forces the entire column to float.

(You will also notice this if you try to convert the column using df_texts['#_words'] = df_texts['#_words'].astype(int) before all values have been set. It will fail because NaN cannot be converted to int.)

Therefore, the column can't become an integer column until all values are set. The problem goes away if you initialize the entire column with df_texts['#_words'] = 0 before the loop.

Edit: Also, as the other answers have pointed out, this assignment can be done without using a loop in the first place.

Body:
I do the following:

import pandas as pd

df_texts = pd.read_csv('data_texts.csv', keep_default_na=True)

for index, row in df_texts.iterrows():

    list_of_words = row['text'].split()

    df_texts.loc[index, '#_words'] = len(list_of_words)

    list_of_unique_words = set(list_of_words)

    df_texts.loc[index, '#_unique_words'] = len(list_of_unique_words)

The problem is that the numbers at the #_words and at the #_unique_words columns are stored as floats even though they are integers.

Just to clarify that these two columns do not pre-exist in the .csv which I read (pd.read_csv) but I create them in the for loop.

How can I directly store them as integers?


问:
JSON format is not recognized when I create an array with more than one element
I want to create a JSON array which includes two elements.
I wrote the following code:

```<code>  var myArray2 = [
      {
        "nome": "Aldo Maria",
        "indirizzo": "Viale Europa 1",
        "telefono": "3397889034"
      },
      {
        nome: "Maria13",
        indirizzo: "Viale Europa 1",
        telefono: "3397889034"
      }
    ];
</code>```

I'm trying to parse it by using the Chrome extension Json Viewer Awesome but I get the error

Failed to parse invalid JSON format

On the other hand, I don't get this error while inserting a single element in the array, as in the snippet below:

```<code>{
    "myArray2": [
        {
            "message": "Welcome to Awesome JSON Viewer.",
            "status_code": 200
        }
    ]
}
</code>```

答:
Yes because your keys doesn't contains double quotes ("") for the part of json.
The valid JSON would be

In JSON, keys must be strings, written with double quotes.

```<code>[{
        "nome": "Aldo Maria",
        "indirizzo": "Viale Europa 1",
        "telefono": "3397889034"
    },
    {
        "nome": " Maria13",
        "indirizzo": "Viale Europa 1",
        "telefono": "3397889034"
    }
]
</code>```

In JavaScript, keys can be strings, numbers, or identifier names.See example

```<code>{ name:"John" }
</code>```

For reference look

Here

Body:
I want to create a JSON array which includes two elements.
I wrote the following code:

  var myArray2 = [
      {
        "nome": "Aldo Maria",
        "indirizzo": "Viale Europa 1",
        "telefono": "3397889034"
      },
      {
        nome: "Maria13",
        indirizzo: "Viale Europa 1",
        telefono: "3397889034"
      }
    ];

I'm trying to parse it by using the Chrome extension Json Viewer Awesome but I get the error

Failed to parse invalid JSON format

On the other hand, I don't get this error while inserting a single element in the array, as in the snippet below:

{
    "myArray2": [
        {
            "message": "Welcome to Awesome JSON Viewer.",
            "status_code": 200
        }
    ]
}

Body:
Yes because your keys doesn't contains double quotes ("") for the part of json.
The valid JSON would be

In JSON, keys must be strings, written with double quotes.

[{
        "nome": "Aldo Maria",
        "indirizzo": "Viale Europa 1",
        "telefono": "3397889034"
    },
    {
        "nome": " Maria13",
        "indirizzo": "Viale Europa 1",
        "telefono": "3397889034"
    }
]

In JavaScript, keys can be strings, numbers, or identifier names.See example

{ name:"John" }

For reference look

Here