问:
Azure Monitor (Log Analytics) query limitation 10,000, not able to see anywhere we can configure
If there any way we can increase the page (any query in Log Analytics) from 10,000 to more than this value? its default page 10,000. I tried to understand in this link but not really getting how we can increase this count</p>

答:
service limits for Log Analytics are mentioned here: https://learn.microsoft.com/en-us/azure/azure-monitor/service-limits.

according to the documentation, you can run the query programmatically, if you need to have it return more than 10,000 records.

and:


来源: stackexchange

问:
API datetime-local input format invalid
I have a datetime-local input that defines date and time. This is supposed to be stored in backend.

Using the input I get the following string 2020-05-29T14:45, but the API is expecting the following format 2020-05-29T14:45Z - where does the Z come from and how can I add it?

答:
I've added the following snippet - you want to convert the input via the Date api and use the toISOString() method

const value = document.querySelector('input').value;
const isoString = new Date(value).toISOString()

const handleInput = (e) => {
  const value = e.target.value;

  const isoString = new Date(value).toISOString()
  console.log(isoString)
  // TODO:
  // use post request to send isoString to API here:
  // can add example if given api endpoint
  return isoString;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="meeting-time">Choose a time for your appointment:</label>

<input type="datetime-local"
       id="meeting-time"
       name="meeting-time" value="2018-06-12T19:30"
       min="2018-06-07T00:00"
       max="2018-06-14T00:00"
       onchange="handleInput(event)"
       ></code>```

ContentLicense: CC BY-SA 4.0

Title: API datetime-local input format invalid

Body:
I've added the following snippet - you want to convert the input via the Date api and use the toISOString() method

const value = document.querySelector('input').value;
const isoString = new Date(value).toISOString()

const handleInput = (e) => {
  const value = e.target.value;

  const isoString = new Date(value).toISOString()
  console.log(isoString)
  // TODO:
  // use post request to send isoString to API here:
  // can add example if given api endpoint
  return isoString;
}

<label for="meeting-time">Choose a time for your appointment:</label>

<input type="datetime-local"
       id="meeting-time"
       name="meeting-time" value="2018-06-12T19:30"
       min="2018-06-07T00:00"
       max="2018-06-14T00:00"
       onchange="handleInput(event)"
       >


问:
Not able to understand viewmodel example on android dev site
```<code>class MyViewModel : ViewModel() {
    private val users: MutableLiveData<List<User>> by lazy {
        MutableLiveData().also {
            loadUsers()
        }
    }

    fun getUsers(): LiveData<List<User>> {
        return users
    }

    private fun loadUsers() {
        // Do an asynchronous operation to fetch users.
    }
}
</code>```

Am trying to implement this way and its not compiling :

```<code>class MyViewModel : ViewModel() {
    private val users: MutableLiveData<List<String>> by lazy {
        return MutableLiveData().also {
            loadUsers()
        }
    }

    fun getUsers(): LiveData<List<String>> {
        return users
    }

    private fun loadUsers() {
        users.postValue(listOf("Tarun", "Chawla"))
    }
}
</code>```

Mostly am not understanding the by lazy here. The example on android website seems wrong as loadUsers() is not returning anything which can be a delegate for
users. can you please help me understanding above piece of code.

=======================================================

This is how I implemented:

```<code>    private val users : MutableLiveData<List<String>> by lazy {
        MutableLiveData<List<String>>().also {
            loadUsers(it)
        }
    }
    init {
        Log.e("Tarund", "View Model created")
    }

    override fun onCleared() {
        super.onCleared()
        Log.e("Tarund", "View Model deleted")
    }

    fun getUsers(): LiveData<List<String>> {
        return users
    }

    private fun loadUsers(users : MutableLiveData<List<String>>) {
        users.postValue(listOf("Tarun", "Chawla"))
    }
}
</code>```

But if anyone can confirm if first example code above which I copy pasted from : https://developer.android.com/topic/libraries/architecture/viewmodel#kotlin is wrong

答:
The code in the Android documentation is wrong.

The lazy construction itself is fine: loadUsers() doesn't need to return anything because the function also is defined as:

```<code>inline fun <T> T.also(block: (T) -> Unit): T
</code>```

that means that in here:

```<code>private val sources: String by lazy {
    String().also {
      loadSources()
    }
}
</code>```

the block also {} will return the empty String created with String() that can be assigned using lazy initialization to the val users

The error trying to compile the Android docs code is:

Type inference failed: Not enough information to infer parameter T in constructor MutableLiveData()

that means that the compiler is not able to infer the type of the MutableLiveData instance created using the constructor wihtout type.

Without the apply block the compiler will be able to compile it because it can easily infer the type from the val definition:

```<code>private val sources: MutableLiveData<List<User>> by lazy {
    MutableLiveData()
}
</code>```

but adding the apply block goes back to the generic type and the compiler cannot infer it. So the solution, as you did, is specifying the type hold in the MutableLiveData container:

```<code>private val sources: MutableLiveData<List<User>> by lazy {
    MutableLiveData<List<User>>().also {
        loadSources()
    }
}
</code>```

Body:
class MyViewModel : ViewModel() {
    private val users: MutableLiveData<List<User>> by lazy {
        MutableLiveData().also {
            loadUsers()
        }
    }

    fun getUsers(): LiveData<List<User>> {
        return users
    }

    private fun loadUsers() {
        // Do an asynchronous operation to fetch users.
    }
}

Am trying to implement this way and its not compiling :

class MyViewModel : ViewModel() {
    private val users: MutableLiveData<List<String>> by lazy {
        return MutableLiveData().also {
            loadUsers()
        }
    }

    fun getUsers(): LiveData<List<String>> {
        return users
    }

    private fun loadUsers() {
        users.postValue(listOf("Tarun", "Chawla"))
    }
}

Mostly am not understanding the by lazy here. The example on android website seems wrong as loadUsers() is not returning anything which can be a delegate for
users. can you please help me understanding above piece of code.

=======================================================

This is how I implemented:

    private val users : MutableLiveData<List<String>> by lazy {
        MutableLiveData<List<String>>().also {
            loadUsers(it)
        }
    }
    init {
        Log.e("Tarund", "View Model created")
    }

    override fun onCleared() {
        super.onCleared()
        Log.e("Tarund", "View Model deleted")
    }

    fun getUsers(): LiveData<List<String>> {
        return users
    }

    private fun loadUsers(users : MutableLiveData<List<String>>) {
        users.postValue(listOf("Tarun", "Chawla"))
    }
}

But if anyone can confirm if first example code above which I copy pasted from : https://developer.android.com/topic/libraries/architecture/viewmodel#kotlin is wrong

Body:
The code in the Android documentation is wrong.

The lazy construction itself is fine: loadUsers() doesn't need to return anything because the function also is defined as:

inline fun <T> T.also(block: (T) -> Unit): T

that means that in here:

private val sources: String by lazy {
    String().also {
      loadSources()
    }
}

the block also {} will return the empty String created with String() that can be assigned using lazy initialization to the val users

The error trying to compile the Android docs code is:

Type inference failed: Not enough information to infer parameter T in constructor MutableLiveData()

that means that the compiler is not able to infer the type of the MutableLiveData instance created using the constructor wihtout type.

Without the apply block the compiler will be able to compile it because it can easily infer the type from the val definition:

private val sources: MutableLiveData<List<User>> by lazy {
    MutableLiveData()
}

but adding the apply block goes back to the generic type and the compiler cannot infer it. So the solution, as you did, is specifying the type hold in the MutableLiveData container:

private val sources: MutableLiveData<List<User>> by lazy {
    MutableLiveData<List<User>>().also {
        loadSources()
    }
}


答:
This would be an option (create prediction dates and plot it along with the predictions stored in fore.xts):

```<code>Date <- seq(max(qxts$Date) + 1, max(qxts$Date) + 60, "day")
forecast_point <- fore.xts$mean
forecast_lower <- fore.xts$lower[,2]
forecast_upper <- fore.xts$upper[,2]

forecast_df <- tibble(Date, forecast_point, forecast_lower, forecast_upper)

#without confidence intervals
qxts %>%
  ggplot(aes(x = Date, y = y)) +
  geom_point() +
  geom_line() +
  geom_line(data = forecast_df, aes(x = Date, y = forecast_point), color = "blue")
</code>```

```<code>#with confidence intervals
qxts %>%
  ggplot(aes(x = Date, y = y)) +
  geom_point() +
  geom_line() +
  geom_smooth(data = forecast_df, aes(x = Date, y = forecast_point, ymax = forecast_upper, ymin = forecast_lower), stat = "identity")
</code>```

Is this what you were looking for?

Title: Convert Plotly forecasting graph to ggplot graph

Body:
I have used a forecast package and graph the data in plotly. Now I need to use ggplot instead of plotly. I found this code, which uses a function to plot the forecast in ggplot,but I couldn't make the code works. Also, I'm aware that autoplot function in forecast use ggplot, but it limits the customization.

Here is my running code of Plotly

 library(ggplot2)
    library(forecast)
    library(plotly)
    df<-structure(list(Date = structure(c(18316, 18317, 18318, 18319,
    18320, 18321, 18322, 18323, 18324, 18325, 18326, 18327, 18328,
    18329, 18330, 18331, 18332, 18333, 18334, 18335, 18336, 18337,
    18338, 18339, 18340, 18341, 18342, 18343, 18344, 18345, 18346,
    18347, 18348, 18349, 18350, 18351, 18352, 18353, 18354, 18355,
    18356, 18357, 18358, 18359, 18360, 18361, 18362, 18363, 18364,
    18365, 18366, 18367, 18368, 18369, 18370, 18371, 18372, 18373,
    18374, 18375, 18376, 18377, 18378, 18379, 18380, 18381, 18382,
    18383, 18384, 18385, 18386, 18387, 18388, 18389, 18390, 18391,
    18392, 18393, 18394, 18395, 18396, 18397, 18398, 18399, 18400,
    18401, 18402, 18403, 18404, 18405, 18406, 18407, 18408, 18409,
    18410), class = "Date"), Count = c(5L, 11L, 26L, 43L, 45L, 45L,
    46L, 56L, 56L, 56L, 57L, 57L, 60L, 63L, 63L, 67L, 67L, 75L, 95L,
    97L, 103L, 111L, 118L, 127L, 130L, 137L, 149L, 158L, 159L, 152L,
    152L, 159L, 168L, 171L, 188L, 194L, 216L, 237L, 261L, 335L, 385L,
    456L, 561L, 637L, 743L, 798L, 869L, 1020L, 1091L, 1148L, 1176L,
    1196L, 1296L, 1395L, 1465L, 1603L, 1619L, 1657L, 1792L, 1887L,
    1986L, 2217L, 2249L, 2254L, 2241L, 2327L, 2459L, 2745L, 2883L,
    3169L, 3291L, 3732L, 4028L, 4142L, 4695L, 4952L, 5901L, 6314L,
    7101L, 7683L, 8436L, 9124L, 9852L, 10645L, 11234L, 11962L, 12559L,
    13275L, 13911L, 14569L, 15029L, 15181L, 15097L, 15146L, 15229L
    )), class = "data.frame", row.names = c(NA, -95L))

    # frequency here in days
    tm<-ts(df$Count,frequency = 365.25 )

    fit.xts <- auto.arima(tm,approximation=FALSE,stepwise=FALSE)
    forecast_length <- 60
    fore.xts <- forecast(fit.xts, h=forecast_length)

   #formating the forecasting date
    fore.dates <- seq(df$Date[length(df$Date)], by=df$Date[length(df$Date)] -
    df$Date[length(df$Date)-1], len=forecast_length)

    plot_ly() %>%
      add_lines(x = df$Date, y = tm,
            color = I("black"),
            name = "Observed",
            marker=list(mode='lines')) %>%
    # this will add line of prediction, which looks linear ! strange !
    # what's the alternative of mean value?
      add_lines(x = fore.dates, y = fore.xts$mean, color = I("blue"), name =
 "Prediction") %>%
      add_ribbons(x = fore.dates,
              #this prints even negative values of prediction !
              ymin = fore.xts$lower[, 2],
              ymax = fore.xts$upper[, 2],
              color = I("gray90"),
              name = "95% confidence") %>%
       layout(legend = list(orientation = "h",   # show entries horizontally
                       xanchor = "center",  # use center of legend as anchor
                       x = 0.5))

Any suggestions!

Body:
This would be an option (create prediction dates and plot it along with the predictions stored in fore.xts):

Date <- seq(max(qxts$Date) + 1, max(qxts$Date) + 60, "day")
forecast_point <- fore.xts$mean
forecast_lower <- fore.xts$lower[,2]
forecast_upper <- fore.xts$upper[,2]

forecast_df <- tibble(Date, forecast_point, forecast_lower, forecast_upper)

#without confidence intervals
qxts %>%
  ggplot(aes(x = Date, y = y)) +
  geom_point() +
  geom_line() +
  geom_line(data = forecast_df, aes(x = Date, y = forecast_point), color = "blue")

#with confidence intervals
qxts %>%
  ggplot(aes(x = Date, y = y)) +
  geom_point() +
  geom_line() +
  geom_smooth(data = forecast_df, aes(x = Date, y = forecast_point, ymax = forecast_upper, ymin = forecast_lower), stat = "identity")

Is this what you were looking for?


问:
Laravel how can using the require file
Laravel how can I use the require file when using @section('content') method, how can I require the file into the this?

I want to using the menu bar, but I don't know how to separate it.

I have this code

```<code><div class="links">
            <a href="http://127.0.0.1:8000/aboutme">About Me</a>
            <a href="http://127.0.0.1:8000/employmenthistory">Employment History</a>
            <a href="https://laravel-news.com">News</a>
            <a href="https://blog.laravel.com">Blog</a>
            <a href="https://nova.laravel.com">Nova</a>
            <a href="https://forge.laravel.com">Forge</a>
            <a href="https://vapor.laravel.com">Vapor</a>
            <a href="https://github.com/laravel/laravel">GitHub</a>
        </div>
</code>```

can independent to menu.php

答: You can use yield() to solve the problem.</p>

Title: Laravel how can using the require file

Body:
Laravel how can I use the require file when using @section('content') method, how can I require the file into the this?

I want to using the menu bar, but I don't know how to separate it.

I have this code

            About Me
            Employment History
            News
            Blog
            Nova
            Forge
            Vapor
            GitHub

can independent to menu.php


问:
How many parameters are too many?
Routines can have parameters, that's no news. You can define as many parameters as you may need, but too many of them will make your routine difficult to understand and maintain.

Of course, you could use a structured variable as a workaround: putting all those variables in a single struct and passing it to the routine. In fact, using structures to simplify parameter lists is one of the techniques described by Steve McConnell in Code Complete. But as he says:

Careful programmers avoid bundling data any more than is logically necessary.

So if your routine has too many parameters or you use a struct to disguise a big parameter list, you're probably doing something wrong. That is, you're not keeping coupling loose.

My question is, when can I consider a parameter list too big? I think that more than 5 parameters, are too many. What do you think?

答:
97 sounds just about right.

Any less and you lose flexibility.

OwnerDisplayName: Auron

ContentLicense: CC BY-SA 2.5

Title: How many parameters are too many?

ContentLicense: CC BY-SA 3.0


问:
PowerShell | Get-ChildItem to Function via Pipeline not providing all items
Due to Azure Dev Ops converting LF to CRLF on deployment I have to create a custom function that will search for .sh files and convert them back to how they are stored in the repo (LF). That code I got down fine however I REALLY want to make a awesome function I can do a single get-childitem recursive looking for .sh files and then pipe that to my custom function that will turn them back to the correct format.

My problem is that me, get-childitem, and functions arent not getting along.

To keep this focused on just the main issue here is an over simplistic example function:

```<code>Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    Write-Output "Item Count: $($items | Measure-Object | select -ExpandProperty Count)"
    foreach ($item in $items) {
        Write-Output "Item: $($item)"
    }
}
</code>```

I call it using:

dir c:\temp\ | List-Items

Yet even though there are clearly 52 items via this command:
dir c:\temp\ | Measure-Object

The function only sees the last record of those 52. How do I access all 52 within my custom list-items function?

答:
This is expected behavior. In reality, an advanced function in PowerShell has three distinct blocks:

begin - Runs once, before the pipeline starts executing

process - Runs once for each pipeline-bound input item

end - Runs once after the upstream cmdlet is done sending input

When you don't specify any of these distinct blocks, but just have a single function body, like your example:

```<code>Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    # Do stuff with $items

}
</code>```

It's actually equivalent to:

```<code>Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    end {
        # Do stuff with $items
    }
}
</code>```

In other words, the function body defaults to act as the end block, which is why you're only seeing the last value bound to $items.

To fix this, explicitly specify a process block:

```<code>Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    process {
        foreach ($item in $items) {
            Write-Output "Item: $($item)"
        }
    }
}
</code>```

Body:
Due to Azure Dev Ops converting LF to CRLF on deployment I have to create a custom function that will search for .sh files and convert them back to how they are stored in the repo (LF). That code I got down fine however I REALLY want to make a awesome function I can do a single get-childitem recursive looking for .sh files and then pipe that to my custom function that will turn them back to the correct format.

My problem is that me, get-childitem, and functions arent not getting along.

To keep this focused on just the main issue here is an over simplistic example function:

Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    Write-Output "Item Count: $($items | Measure-Object | select -ExpandProperty Count)"
    foreach ($item in $items) {
        Write-Output "Item: $($item)"
    }
}

I call it using:

dir c:\temp\ | List-Items

Yet even though there are clearly 52 items via this command:
dir c:\temp\ | Measure-Object

The function only sees the last record of those 52. How do I access all 52 within my custom list-items function?

Body:
This is expected behavior. In reality, an advanced function in PowerShell has three distinct blocks:

begin - Runs once, before the pipeline starts executing

process - Runs once for each pipeline-bound input item

end - Runs once after the upstream cmdlet is done sending input

When you don't specify any of these distinct blocks, but just have a single function body, like your example:

Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    # Do stuff with $items

}

It's actually equivalent to:

Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    end {
        # Do stuff with $items
    }
}

In other words, the function body defaults to act as the end block, which is why you're only seeing the last value bound to $items.

To fix this, explicitly specify a process block:

Function List-Items {
    param (
        [Parameter(ValueFromPipeline = $true)]$items
    )

    process {
        foreach ($item in $items) {
            Write-Output "Item: $($item)"
        }
    }
}


问:
Check the repeated words in a string and keep a count in javascript
I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive"; ```
</div>
</div>
</p>

<p>I am looking for output like this <strong>I = 3</strong>, <strong>am = 2</strong>, <strong>not = 1</strong> and so on, also is it possible to find the individual letter as <strong>I = 3</strong>, <strong>a = 6</strong>, <strong>m = 2</strong>. </p>

<p>I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)</code>```

答:
```<code>let checkWords = "I am not gonna live forever, but I wanna live while I am alive"

const newStr = checkWords.split(' ').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

const newStr2 = checkWords.split('').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})
</code>```

<p>{newStr} for counter words
{newStr2} for counter letters</p>

Body:
I am trying to find repeated words in a string and keep a count of how many times it was repeated.
How do I do it in javascript.

 let checkWords = "I am not gonna live forever, but I wanna live while I am alive";

I am looking for output like this I = 3, am = 2, not = 1 and so on, also is it possible to find the individual letter as I = 3, a = 6, m = 2.

I found a similar answer which I tried to use in my string, which works too but can anyone explain me why is the obj and undefined used here

let str = "I am not gonna live forever, but I wanna live while I am alive",
    split = str.split(" "),
    obj = {};

for (let i = 0; i < split.length; i++) {
  if (obj[split[i]] === undefined) {
    obj[split[i]] = 1;
  } else {
    obj[split[i]]++;
  }
}

console.log(obj)

Body:
let checkWords = "I am not gonna live forever, but I wanna live while I am alive"

const newStr = checkWords.split(' ').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

const newStr2 = checkWords.split('').reduce((acc,rec) => {
  return ({ ...acc, [rec]: (acc[rec] || 0) + 1 })
},{})

{newStr} for counter words
{newStr2} for counter letters


问:
Scaffold-DbContext ignores host IP from connection string
I'm trying to generate models from an existing PostgreSQL database using this command:

```<code>Scaffold-DbContext "Host=52.0.0.0;Database=my-db;Username=postgres;Password=password" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models
</code>```

It "worked" once by trying to connect to the host but failed because the port 5432 was not accessible.

I fixed the network issue, now the port is opened but the Host from the connection string is ignored and the errors I get is:

28000: no pg_hba.conf entry for host "my.public.ip.address", user
  "postgres", database "my-db", SSL off

I don't know why my public address is even mentionned in there, of course I don't have a pg_hba.conf file. I'm not the server.

Any ideas ?

答:
So the message wasn't saying that "my.public.address" does not have a pg_hba.conf file, but that there is no configuration in the server for my IP.

```<code>host    all all     my.public.ip/32     md5
</code>```

This solved it.

Body:
I'm trying to generate models from an existing PostgreSQL database using this command:

Scaffold-DbContext "Host=52.0.0.0;Database=my-db;Username=postgres;Password=password" Npgsql.EntityFrameworkCore.PostgreSQL -OutputDir Models

It "worked" once by trying to connect to the host but failed because the port 5432 was not accessible.

I fixed the network issue, now the port is opened but the Host from the connection string is ignored and the errors I get is:

28000: no pg_hba.conf entry for host "my.public.ip.address", user
  "postgres", database "my-db", SSL off

I don't know why my public address is even mentionned in there, of course I don't have a pg_hba.conf file. I'm not the server.

Any ideas ?

Body:
So the message wasn't saying that "my.public.address" does not have a pg_hba.conf file, but that there is no configuration in the server for my IP.

host    all all     my.public.ip/32     md5

This solved it.


问:
Python Pandas Period Date difference is in * MonthEnds>, how to convert it into INT value
I am trying to find Period date difference. Per Pandas 0.24+ : Subtraction of a Period from another Period will give a DateOffset. instead of an integer (GH21314). But how to get INT results. I have look into similar query: Why can't I subtract one date period from the next and convert to an integer?
It says adding ".n" will give results, but that didn't work for me.

I also tried converting both into INT using .astype(int), but getting error: 'Period' object has no attribute 'astype'. I must be missing something, not sure what!

I am using Pandas Version: '1.0.1'.

DDL to generate Dataframe:

```<code>import pandas as pd

date_start = pd.Period('10/2018',freq='M')

df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
                  'date_end': ['2017-01', '2018-08', '2019-04','2018-06',
                               '2018-12', '2018-10']})
df['date_end'] = pd.PeriodIndex(pd.to_datetime(df['date_end'], format='%Y-%m'),
                                freq='M')

df['diff'] = date_start - df['date_end']
</code>```

Thanks!

答:
You need to access the individual Period[M] objects, not the series:

```<code>df['diff'].n
AttributeError: 'Series' object has no attribute 'n'

df['diff'].apply(lambda x: x.n)

0    21
1     2
2    -6
3     4
4    -2
5     0
</code>```

Body:
I am trying to find Period date difference. Per Pandas 0.24+ : Subtraction of a Period from another Period will give a DateOffset. instead of an integer (GH21314). But how to get INT results. I have look into similar query: Why can't I subtract one date period from the next and convert to an integer?
It says adding ".n" will give results, but that didn't work for me.

I also tried converting both into INT using .astype(int), but getting error: 'Period' object has no attribute 'astype'. I must be missing something, not sure what!

I am using Pandas Version: '1.0.1'.

DDL to generate Dataframe:

import pandas as pd

date_start = pd.Period('10/2018',freq='M')

df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
                  'date_end': ['2017-01', '2018-08', '2019-04','2018-06',
                               '2018-12', '2018-10']})
df['date_end'] = pd.PeriodIndex(pd.to_datetime(df['date_end'], format='%Y-%m'),
                                freq='M')

df['diff'] = date_start - df['date_end']

Thanks!

Body:
You need to access the individual Period[M] objects, not the series:

df['diff'].n
AttributeError: 'Series' object has no attribute 'n'

df['diff'].apply(lambda x: x.n)

0    21
1     2
2    -6
3     4
4    -2
5     0


问:
Video not loading with VueJS
I am working with Vue.js 2 and Laravel and have been trying to load a video from a local folder of my project without success.

Vue-loader plugin is correctly installed and added in my webpack.config.js as specified on the docs: https://vue-loader.vuejs.org/guide/#manual-setup

I have tried the most simple way.

```<code><template>
  <div>
    <video autoplay muted loop id="myVideo">
      <source src="/storage/videos/landing.mp4" type="video/mp4" />
    </video>
  </div>
</template>
</code>```

I have also tried with a different approach as suggested on another stackoverflow question by dinamically updating the src attribute when the component is mounted.

```<code><template>
  <div>
    <video ref="videoRef" src="" autoplay muted loop id="myVideo"></video>
  </div>
</template>

<script>
export default {
  mounted: function() {
    this.$refs.videoRef.src =
      "/storage/videos/landing.mp4";
  }
};
</script>
</code>```

None of those have worked tho.

Im quite sure the problem lies in Vue not resolving the video route properly since I have tried to use a dummy video link from the web and it is working absolutely fine.

Firefox is also giving me some clues.

However, Im not sure about what the problem is or how to solve it. Thanks in advance.

PS: I have triple checked the route specified and it definitely exists in my project.

答:
Either you load your video with an es module import, your loader has to be able to import mp4, and you put that in the src

```<code>import video from 'path/to/video/a.mp4'
</code>```

and in your component you do

```<code><video :src="video">
</code>```

PS make sure that the imported video is then defined in your data function.

Or you can use it like your doing with src="path/to/folder" and try to understand where that path is pointing at through your network tab, and put the video in the right folder based on that.

Title: Video not loading with VueJS

Body:
I am working with Vue.js 2 and Laravel and have been trying to load a video from a local folder of my project without success.

Vue-loader plugin is correctly installed and added in my webpack.config.js as specified on the docs: https://vue-loader.vuejs.org/guide/#manual-setup

I have tried the most simple way.

<template>

    <video autoplay muted loop id="myVideo">
      <source src="/storage/videos/landing.mp4" type="video/mp4" />
    </video>

</template>

I have also tried with a different approach as suggested on another stackoverflow question by dinamically updating the src attribute when the component is mounted.

<template>

    <video ref="videoRef" src="" autoplay muted loop id="myVideo"></video>

</template>

None of those have worked tho.

Im quite sure the problem lies in Vue not resolving the video route properly since I have tried to use a dummy video link from the web and it is working absolutely fine.

Firefox is also giving me some clues.

However, Im not sure about what the problem is or how to solve it. Thanks in advance.

PS: I have triple checked the route specified and it definitely exists in my project.

Body:
Either you load your video with an es module import, your loader has to be able to import mp4, and you put that in the src

import video from 'path/to/video/a.mp4'

and in your component you do

<video :src="video">

PS make sure that the imported video is then defined in your data function.

Or you can use it like your doing with src="path/to/folder" and try to understand where that path is pointing at through your network tab, and put the video in the right folder based on that.


问:
Pass Symfony project to developer
I have moved my symfony website to production but I need to pass it back to developer. Someone could help me?

I have tried putting app_dev.php but I don't really know how.

I also have .env like this

###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=****************
#TRUSTED_PROXIES=127.0.0.0/8,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
#TRUSTED_HOSTS='^(localhost|example\.com)$'
###< symfony/framework-bundle ###
```

答:
For any URL in your app, let's say something like https://url.com/page1, you can try instead to visit https://url.com/app_dev.php/page1 and your dev toolbar should now appear.

Hope this helps !

Title: Pass Symfony project to developer


问:
I cannot type in dat.gui in JSFiddle
I have written code that works perfectly when i run it locally on my system.

This is the link:
https://jsfiddle.net/rand0mus3r/L3j7kz5a/

When you click the mesh, a dat.gui instance appears. However, when i use backspace or try to input something in the textbox, it doesn't work.

It works fine in my system though.

This is the code:

```<code><!DOCTYPE html>

<html>

<head>
    <title>Example 01.02 - First Scene</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/three@0.101.1/examples/js/controls/OrbitControls.js"></script>
    <style>
        body {
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- Div which will hold the Output -->
<div id="WebGL-output">
</div>

</body>
</html>

window.onload = init();
    animate(); //calling function that does all the rendering

    //GLOBAL VARS
    var scene, camera, renderer;
    var cube;
    var raycaster, mouse;
    var INTERSECTED;

    //global flag
    var isClicked = false;

    //for the camera
    var controls;

//creating and rendering the GUI
params = {
  yAxis: "0.00001"
}
var gui = new dat.GUI();
gui.add(params, "yAxis").onFinishChange(val => {
  cube.scale.y = parseFloat(val);
});

//we make sure to make it hidden
 let vis = gui.domElement.style.visibility;
 gui.domElement.style.visibility = vis == "" ? "hidden" : "";

    // once everything is loaded, we run our Three.js stuff.
    function init() {

        // create a scene, that will hold all our elements such as objects, cameras and lights.
        scene = new THREE.Scene();

        //SET CAMERA
        camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
        camera.position.z = 5;

        // create a render and set the size
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setClearColor("#e5e5e5"); //background color
        renderer.setSize(window.innerWidth,window.innerHeight); //size of renderer

        //bind rendered to the dom element
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        //RAYCASTER
        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2(1,1);

        // create a cube
        var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00 }); //0xF7F7F7 = gray
        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.scale.y = 0.00001;
        cube.userData.originalColor = 0xffff00;

        // position the cube
        cube.position.x = 0;
        cube.position.y = 3;
        cube.position.z = 0;
        /*
        //USEFUL METHODS
        cube.rotation.x +=0.5
        cube.scale.x +=0.5
        */
        // add the cube to the scene
        scene.add(cube);

        /*  RENDERING A PLANE
        var geometry = new THREE.PlaneGeometry( 20, 20);
        var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
        var plane = new THREE.Mesh( geometry, material );
        plane.rotation.set(80,0,0);
        scene.add( plane );
        //plane.position.x = 2;
        */

        //ADDING LIGHTS
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        //camera
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.minDistance = 1;
        controls.maxDistance = 1000;

        // when the mouse moves, call the given function
        document.addEventListener('mousemove', onDocumentMouseMove, false);

        //when the mouse is clicked, call the given function
        document.addEventListener('click', onDocumentMouseClick, false);
    }

    function onDocumentMouseMove(event)
    {
      // the following line would stop any other event handler from firing
      // (such as the mouse's TrackballControls)
      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //TRY THIS
        // intersects = raycaster.intersectObject(cube); // to get the cube only

        //if the mouse hovers over the cube mesh, change its color to red
        //when mouse leaves the mesh, change it back to its original color
        //ONLY MAKE THESE MODIFICATION IF THE MESH IS NOT CLICKED
        //BECAUSE IF IT IS CLICKED, YOU HAVE TO PAINT THE MESH ACCORDING TO THE onDocumentMouseClick()
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xF7F7F7 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

    }

    // 0xff0000 red
    //0xF7F7F7 = gray

    function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xff0000);

/*
            var params = {
                textField: "Enter value:"
            }

                 var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                //console.log(value);
                cube.scale.y +=value;
            });

*/

//when its clicked, change the visibily of the GUI
 vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
            //when its clicked, change the visibily of the GUI
            vis = gui.domElement.style.visibility;
            gui.domElement.style.visibility = vis == "" ? "hidden" : "";
   //         gui.__proto__.constructor.toggleHide()
            //dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }

    function render()
    {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera( mouse, camera );
        renderer.render(scene, camera); //render the scene
    }

    function animate()
    {
        requestAnimationFrame( animate ); //pauses when user switches tab
        controls.update();
        render();
    }
</code>```

答:
This problem is related to a bug in OrbitControls which was fixed with r110. Upgrading OrbitControls to r110 solves the issue.

window.onload = init();
    animate(); //calling function that does all the rendering

    //GLOBAL VARS
    var scene, camera, renderer;
    var cube;
    var raycaster, mouse;
    var INTERSECTED;

    //global flag
    var isClicked = false;

    //for the camera
    var controls;

//creating and rendering the GUI
params = {
  yAxis: 0.00001
}
var gui = new dat.GUI();
gui.add(params, "yAxis").onFinishChange(val => {
  cube.scale.y = val;
});

//we make sure to make it hidden
 let vis = gui.domElement.style.visibility;
 gui.domElement.style.visibility = vis == "" ? "hidden" : "";

    // once everything is loaded, we run our Three.js stuff.
    function init() {

        // create a scene, that will hold all our elements such as objects, cameras and lights.
        scene = new THREE.Scene();

        //SET CAMERA
        camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
        camera.position.z = 5;

        // create a render and set the size
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setClearColor("#e5e5e5"); //background color
        renderer.setSize(window.innerWidth,window.innerHeight); //size of renderer

        //bind rendered to the dom element
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        //RAYCASTER
        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2(1,1);

        // create a cube
        var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00 }); //0xF7F7F7 = gray
        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.scale.y = 0.00001;
        cube.userData.originalColor = 0xffff00;

        // position the cube
        cube.position.x = 0;
        cube.position.y = 3;
        cube.position.z = 0;
        /*
        //USEFUL METHODS
        cube.rotation.x +=0.5
        cube.scale.x +=0.5
        */
        // add the cube to the scene
        scene.add(cube);

        /*  RENDERING A PLANE
        var geometry = new THREE.PlaneGeometry( 20, 20);
        var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
        var plane = new THREE.Mesh( geometry, material );
        plane.rotation.set(80,0,0);
        scene.add( plane );
        //plane.position.x = 2;
        */

        //ADDING LIGHTS
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        //camera
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.minDistance = 1;
        controls.maxDistance = 1000;

        // when the mouse moves, call the given function
        document.addEventListener('mousemove', onDocumentMouseMove, false);

        //when the mouse is clicked, call the given function
        document.addEventListener('click', onDocumentMouseClick, false);
    }

    function onDocumentMouseMove(event)
    {
      // the following line would stop any other event handler from firing
      // (such as the mouse's TrackballControls)
      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //TRY THIS
        // intersects = raycaster.intersectObject(cube); // to get the cube only

        //if the mouse hovers over the cube mesh, change its color to red
        //when mouse leaves the mesh, change it back to its original color
        //ONLY MAKE THESE MODIFICATION IF THE MESH IS NOT CLICKED
        //BECAUSE IF IT IS CLICKED, YOU HAVE TO PAINT THE MESH ACCORDING TO THE onDocumentMouseClick()
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xF7F7F7 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

    }

    // 0xff0000 red
    //0xF7F7F7 = gray

    function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xff0000);

/*
            var params = {
                textField: "Enter value:"
            }

                 var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                //console.log(value);
                cube.scale.y +=value;
            });

*/

//when its clicked, change the visibily of the GUI
 vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
            //when its clicked, change the visibily of the GUI
            vis = gui.domElement.style.visibility;
            gui.domElement.style.visibility = vis == "" ? "hidden" : "";
   //         gui.__proto__.constructor.toggleHide()
            //dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }

    function render()
    {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera( mouse, camera );
        renderer.render(scene, camera); //render the scene
    }

    function animate()
    {
        requestAnimationFrame( animate ); //pauses when user switches tab
        controls.update();
        render();
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
}
canvas {
  display: block;

}</code>```

```

BTW: Please always ensure to use three.js files from the same release. In your demo, three.js is from r110 whereas OrbitControls is from 101.1. Such configurations are not supported and can produce undefined behavior.

Title: I cannot type in dat.gui in JSFiddle

Body:
I have written code that works perfectly when i run it locally on my system.

This is the link:
https://jsfiddle.net/rand0mus3r/L3j7kz5a/

When you click the mesh, a dat.gui instance appears. However, when i use backspace or try to input something in the textbox, it doesn't work.

It works fine in my system though.

This is the code:

<!DOCTYPE html>

    <title>Example 01.02 - First Scene</title>

window.onload = init();
    animate(); //calling function that does all the rendering

    //GLOBAL VARS
    var scene, camera, renderer;
    var cube;
    var raycaster, mouse;
    var INTERSECTED;

    //global flag
    var isClicked = false;

    //for the camera
    var controls;

//creating and rendering the GUI
params = {
  yAxis: "0.00001"
}
var gui = new dat.GUI();
gui.add(params, "yAxis").onFinishChange(val => {
  cube.scale.y = parseFloat(val);
});

//we make sure to make it hidden
 let vis = gui.domElement.style.visibility;
 gui.domElement.style.visibility = vis == "" ? "hidden" : "";

    // once everything is loaded, we run our Three.js stuff.
    function init() {

        // create a scene, that will hold all our elements such as objects, cameras and lights.
        scene = new THREE.Scene();

        //SET CAMERA
        camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
        camera.position.z = 5;

        // create a render and set the size
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setClearColor("#e5e5e5"); //background color
        renderer.setSize(window.innerWidth,window.innerHeight); //size of renderer

        //bind rendered to the dom element
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        //RAYCASTER
        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2(1,1);

        // create a cube
        var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00 }); //0xF7F7F7 = gray
        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.scale.y = 0.00001;
        cube.userData.originalColor = 0xffff00;

        // position the cube
        cube.position.x = 0;
        cube.position.y = 3;
        cube.position.z = 0;
        /*
        //USEFUL METHODS
        cube.rotation.x +=0.5
        cube.scale.x +=0.5
        */
        // add the cube to the scene
        scene.add(cube);

        /*  RENDERING A PLANE
        var geometry = new THREE.PlaneGeometry( 20, 20);
        var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
        var plane = new THREE.Mesh( geometry, material );
        plane.rotation.set(80,0,0);
        scene.add( plane );
        //plane.position.x = 2;
        */

        //ADDING LIGHTS
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        //camera
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.minDistance = 1;
        controls.maxDistance = 1000;

        // when the mouse moves, call the given function
        document.addEventListener('mousemove', onDocumentMouseMove, false);

        //when the mouse is clicked, call the given function
        document.addEventListener('click', onDocumentMouseClick, false);
    }

    function onDocumentMouseMove(event)
    {
      // the following line would stop any other event handler from firing
      // (such as the mouse's TrackballControls)
      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //TRY THIS
        // intersects = raycaster.intersectObject(cube); // to get the cube only

        //if the mouse hovers over the cube mesh, change its color to red
        //when mouse leaves the mesh, change it back to its original color
        //ONLY MAKE THESE MODIFICATION IF THE MESH IS NOT CLICKED
        //BECAUSE IF IT IS CLICKED, YOU HAVE TO PAINT THE MESH ACCORDING TO THE onDocumentMouseClick()
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xF7F7F7 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

    }

    // 0xff0000 red
    //0xF7F7F7 = gray

    function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xff0000);

/*
            var params = {
                textField: "Enter value:"
            }

                 var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                //console.log(value);
                cube.scale.y +=value;
            });

*/

//when its clicked, change the visibily of the GUI
 vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
            //when its clicked, change the visibily of the GUI
            vis = gui.domElement.style.visibility;
            gui.domElement.style.visibility = vis == "" ? "hidden" : "";
   //         gui.__proto__.constructor.toggleHide()
            //dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }

    function render()
    {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera( mouse, camera );
        renderer.render(scene, camera); //render the scene
    }

    function animate()
    {
        requestAnimationFrame( animate ); //pauses when user switches tab
        controls.update();
        render();
    }

Body:
This problem is related to a bug in OrbitControls which was fixed with r110. Upgrading OrbitControls to r110 solves the issue.

window.onload = init();
    animate(); //calling function that does all the rendering

    //GLOBAL VARS
    var scene, camera, renderer;
    var cube;
    var raycaster, mouse;
    var INTERSECTED;

    //global flag
    var isClicked = false;

    //for the camera
    var controls;

//creating and rendering the GUI
params = {
  yAxis: 0.00001
}
var gui = new dat.GUI();
gui.add(params, "yAxis").onFinishChange(val => {
  cube.scale.y = val;
});

//we make sure to make it hidden
 let vis = gui.domElement.style.visibility;
 gui.domElement.style.visibility = vis == "" ? "hidden" : "";

    // once everything is loaded, we run our Three.js stuff.
    function init() {

        // create a scene, that will hold all our elements such as objects, cameras and lights.
        scene = new THREE.Scene();

        //SET CAMERA
        camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
        camera.position.z = 5;

        // create a render and set the size
        renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setClearColor("#e5e5e5"); //background color
        renderer.setSize(window.innerWidth,window.innerHeight); //size of renderer

        //bind rendered to the dom element
        document.getElementById("WebGL-output").appendChild(renderer.domElement);

        //RAYCASTER
        raycaster = new THREE.Raycaster();
        mouse = new THREE.Vector2(1,1);

        // create a cube
        var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
        var cubeMaterial = new THREE.MeshLambertMaterial({color: 0xffff00 }); //0xF7F7F7 = gray
        cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.scale.y = 0.00001;
        cube.userData.originalColor = 0xffff00;

        // position the cube
        cube.position.x = 0;
        cube.position.y = 3;
        cube.position.z = 0;
        /*
        //USEFUL METHODS
        cube.rotation.x +=0.5
        cube.scale.x +=0.5
        */
        // add the cube to the scene
        scene.add(cube);

        /*  RENDERING A PLANE
        var geometry = new THREE.PlaneGeometry( 20, 20);
        var material = new THREE.MeshBasicMaterial( {color: 0xffff00, side: THREE.DoubleSide} );
        var plane = new THREE.Mesh( geometry, material );
        plane.rotation.set(80,0,0);
        scene.add( plane );
        //plane.position.x = 2;
        */

        //ADDING LIGHTS
        var ambientLight = new THREE.AmbientLight(0x0c0c0c);
        scene.add(ambientLight);
        var spotLight = new THREE.SpotLight(0xffffff);
        spotLight.position.set(-40, 60, -10);
        spotLight.castShadow = true;
        scene.add(spotLight);

        // position and point the camera to the center of the scene
        camera.position.x = -30;
        camera.position.y = 40;
        camera.position.z = 30;
        camera.lookAt(scene.position);

        //camera
        controls = new THREE.OrbitControls(camera, renderer.domElement);
        controls.minDistance = 1;
        controls.maxDistance = 1000;

        // when the mouse moves, call the given function
        document.addEventListener('mousemove', onDocumentMouseMove, false);

        //when the mouse is clicked, call the given function
        document.addEventListener('click', onDocumentMouseClick, false);
    }

    function onDocumentMouseMove(event)
    {
      // the following line would stop any other event handler from firing
      // (such as the mouse's TrackballControls)
      event.preventDefault();

      // update the mouse variable
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //TRY THIS
        // intersects = raycaster.intersectObject(cube); // to get the cube only

        //if the mouse hovers over the cube mesh, change its color to red
        //when mouse leaves the mesh, change it back to its original color
        //ONLY MAKE THESE MODIFICATION IF THE MESH IS NOT CLICKED
        //BECAUSE IF IT IS CLICKED, YOU HAVE TO PAINT THE MESH ACCORDING TO THE onDocumentMouseClick()
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            cube.material.color.set( 0xF7F7F7 );
        }
        else if (isClicked === false)
        {
            cube.material.color.set( cube.userData.originalColor );
        }

    }

    // 0xff0000 red
    //0xF7F7F7 = gray

    function onDocumentMouseClick(event) //if we detect a click event
    {
        // the following line would stop any other event handler from firing
        // (such as the mouse's TrackballControls)
        event.preventDefault();

        // update the mouse variable
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // calculate objects intersecting the picking ray
        var intersects = raycaster.intersectObjects( scene.children );

        //if mouse is on top of the mesh when the click occurs, change color of mesh and render GUI
        if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === false)
        {
            isClicked = true;
            cube.material.color.set( 0xff0000);

/*
            var params = {
                textField: "Enter value:"
            }

                 var item =  gui.add(params, "textField").onFinishChange(function (value) {
                //Do something with the new value
                //console.log(value);
                cube.scale.y +=value;
            });

*/

//when its clicked, change the visibily of the GUI
 vis = gui.domElement.style.visibility;
    gui.domElement.style.visibility = vis == "" ? "hidden" : "";

        }
        //if mouse is on top of the mesh when the click occurs, but it already marked as 'clicked', now mark it as 'unclicked'
        else if ( intersects.length > 0 && intersects[ 0 ].object === cube && isClicked === true)
        {
            isClicked = false;
            cube.material.color.set( cube.userData.originalColor );
            //when its clicked, change the visibily of the GUI
            vis = gui.domElement.style.visibility;
            gui.domElement.style.visibility = vis == "" ? "hidden" : "";
   //         gui.__proto__.constructor.toggleHide()
            //dat.GUI.toggleHide();
            //gui.toggleHide()
        }

    }

    function render()
    {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera( mouse, camera );
        renderer.render(scene, camera); //render the scene
    }

    function animate()
    {
        requestAnimationFrame( animate ); //pauses when user switches tab
        controls.update();
        render();
    }

body {
  margin: 0;
}
canvas {
  display: block;

}

<script src="https://cdn.jsdelivr.net/npm/three@0.110/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.110/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
<div id="WebGL-output">
</div>

BTW: Please always ensure to use three.js files from the same release. In your demo, three.js is from r110 whereas OrbitControls is from 101.1. Such configurations are not supported and can produce undefined behavior.


问:
Typescript for AWS HTTP API Gateway Lambda Handlers
Currently I use the following to type the lambda functions for RestApi:

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {}
```

This doesn't correctly work with the new AWS Gateway HTTP API, where the HTTP method can be fetched using event.requestContext.http.method.

Are there other types that I should use?

答:
Are there other types that I should use?

I do not think so.
The types are available via DefinitelyTyped. [1]
Looking through some of the issues regarding the "aws-lambda" types, you will notice that the API Gateway types are not updated frequently. [2]

Furthermore, the payload format version changed for API Gateway, see [3]:

The payload format version specifies the format of the data that API Gateway sends to a Lambda integration, and how API Gateway interprets the response from Lambda. If you don't specify a payload format version, the AWS Management Console uses the latest version by default. If you create a Lambda integration by using the AWS CLI, AWS CloudFormation, or an SDK, you must specify a payloadFormatVersion. The supported values are 1.0 and 2.0.

I guess you are using the latest version which is 2.0.
Version 2.0 provides the HTTP method as property requestContext.http.method.

Version 1.0 provides the HTTP method as property requestContext.httpMethod.

Solution

You can either 1.) write typings for the new payload format version and submit them to DefinitelyTyped via PR for package "@types/aws-lambda" or 2.) set your API Gateway to use version 1.0.

Honestly, I do not know if using the payload version 1.0 is possible for HTTP APIs. Maybe AWS is enforcing the latest version on the new APIs since there is no need to support the older format.

References

[1] https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/aws-lambda/trigger/api-gateway-proxy.d.ts

[2] https://github.com/DefinitelyTyped/DefinitelyTyped/issues/38720#issuecomment-586051966

[3] https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html

Body:
Currently I use the following to type the lambda functions for RestApi:

import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {}

This doesn't correctly work with the new AWS Gateway HTTP API, where the HTTP method can be fetched using event.requestContext.http.method.

Are there other types that I should use?


问:
SQL Server stored procedure not executing correctly
I have a stored procedure in SQL Server.

Based on a parameter @hasLocationChanged, part of the stored procedure should be run (or not):

```<code>IF NOT EXISTS (SELECT 1 FROM PF_Condition WHERE SegmentId = @routeId)
    SET @isUpdate = 0
ELSE
    SET @isUpdate = 1

IF @hasLocationChanged = 1
BEGIN
    EXEC fnUpdateConditionDataByRouteId @routeId, @isUpdate
    EXEC fnUpdateTrafficDataByRouteId @routeId, @isUpdate
    EXEC dbo.InsertmappedConsPlanningandConsHistory @routeId, @AgencyId, @LastSurfType, @LPDepth
END
</code>```

When I am passing value 1 for @hasLocationChanged from the application it is getting accepted since the third stored procedure within the second IF condition block of code is running but the first two aren't. Is there any way I can understand what is causing the problem. Since I am trying to run this stored procedure using an application it is not returning me with any kind of error.

答: The stored procedure which I thought wasn't running had a block of code commented out which shouldn't</p>

Body:
I have a stored procedure in SQL Server.

Based on a parameter @hasLocationChanged, part of the stored procedure should be run (or not):

IF NOT EXISTS (SELECT 1 FROM PF_Condition WHERE SegmentId = @routeId)
    SET @isUpdate = 0
ELSE
    SET @isUpdate = 1

IF @hasLocationChanged = 1
BEGIN
    EXEC fnUpdateConditionDataByRouteId @routeId, @isUpdate
    EXEC fnUpdateTrafficDataByRouteId @routeId, @isUpdate
    EXEC dbo.InsertmappedConsPlanningandConsHistory @routeId, @AgencyId, @LastSurfType, @LPDepth
END

When I am passing value 1 for @hasLocationChanged from the application it is getting accepted since the third stored procedure within the second IF condition block of code is running but the first two aren't. Is there any way I can understand what is causing the problem. Since I am trying to run this stored procedure using an application it is not returning me with any kind of error.


问:
In Visual Studio is it possible to see what the name of a bookmark is within the code window? (eg hovering your mouse over it to the left of the code)
In Visual Studio is it possible to see what the name of a bookmark is?
Quite often I put in bookmark to remind me about a piece of code I need to get back to, then later when I do something else I come across the bookmark. (Which is often one amongst many) However if I hover the mouse over the bookmark it doesn't tell me which one it is. Can this be switched on? </p>

答: It cannot be switched on, and left-clicking in the gutter is just going to toggle a breakpoint. The closest you can get without venturing into third-party add-ons is to keep the Visual Studio Bookmarks window pinned to your workspace--or within easy reach. To open that window, hit [Ctrl]-grave accent and it will highlight any bookmark you navigate to using [Ctrl]K, [Ctrl]N or [Ctrl]P (next/previous bookmark) or [Shift][Ctrl]K, [Shift][Ctrl]N or [Shift][Ctrl]P (next/previous bookmark in the current folder).


问:
Migration from ASP.NET MVC to ASP.NET Core MVC - action model binding resulting null
While migrating from ASP.NET MVC to ASP.NET Core MVC, I faced binding behavior troubles which I couldn't overcome.

I have this controller (for Razor, not API):

```<code>public class SomeController : Controller
{
    [HttpPost]
    public IActionResult SomeAction([FromBody] SomeModel model)
    {
        return Ok(model?.SomeValue);
    }
}

public class SomeModel
{
    public int SomeValue { get; set; }
}
</code>```

If I make a request to /some/someAction with a body of { "SomeValue": "6970" }, I get a model equals null.

If I remove quotes { "SomeValue": 6970 } I receive what I need, the model isn't null.

The project is big and I cant change all the js code to ints, also it could be a problem to change all models which expect int.

How I can let it work easily?

答: Try to change your model from int to string and check if it works </p>

Body:
While migrating from ASP.NET MVC to ASP.NET Core MVC, I faced binding behavior troubles which I couldn't overcome.

I have this controller (for Razor, not API):

public class SomeController : Controller
{
    [HttpPost]
    public IActionResult SomeAction([FromBody] SomeModel model)
    {
        return Ok(model?.SomeValue);
    }
}

public class SomeModel
{
    public int SomeValue { get; set; }
}

If I make a request to /some/someAction with a body of { "SomeValue": "6970" }, I get a model equals null.

If I remove quotes { "SomeValue": 6970 } I receive what I need, the model isn't null.

The project is big and I cant change all the js code to ints, also it could be a problem to change all models which expect int.

How I can let it work easily?


问:
How to get checked button position in Android MaterialButtonToggleGroup
I have defined an MaterialButtonToggleGroup with 2 MaterialButton in my xml, in this way:

<com.google.android.material.button.MaterialButtonToggleGroup
    ...
    app:checkedButton="@+id/favorite_color1"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color1"
        ... />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color2"
        ... />

</com.google.android.material.button.MaterialButtonToggleGroup>
```

I found getCheckedButtonIds() method (that returns a List of Ids) and OnButtonCheckedListener (that returns an Integer Id), but the get(int index) method returns the View at the index position, not the View with a certain id.

How Can I get (programmatically) the View of the checked button in a given moment?
There is a method returns the current checked position (or index)?

答:
Since you are using app:singleSelection="true" you can use thegetCheckedButtonId() method to get the unique id of the selected MaterialButton in this group.

You can use something like:

```<code>MaterialButtonToggleGroup materialButtonToggleGroup =
         findViewById(R.id.toggle_button_group);
int buttonId = materialButtonToggleGroup.getCheckedButtonId();
MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);
</code>```

You can also use getCheckedButtonIds() and cycle over the ids.

```<code>List<Integer> ids = materialButtonToggleGroup.getCheckedButtonIds();
for (Integer id:ids){
      MaterialButton materialButton = materialButtonToggleGroup.findViewById(id);
      //....
}
</code>```

Body:
I have defined an MaterialButtonToggleGroup with 2 MaterialButton in my xml, in this way:

<com.google.android.material.button.MaterialButtonToggleGroup
    ...
    app:checkedButton="@+id/favorite_color1"
    app:singleSelection="true">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color1"
        ... />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/favorite_color2"
        ... />

</com.google.android.material.button.MaterialButtonToggleGroup>

I found getCheckedButtonIds() method (that returns a List of Ids) and OnButtonCheckedListener (that returns an Integer Id), but the get(int index) method returns the View at the index position, not the View with a certain id.

How Can I get (programmatically) the View of the checked button in a given moment?
There is a method returns the current checked position (or index)?

Body:
Since you are using app:singleSelection="true" you can use thegetCheckedButtonId() method to get the unique id of the selected MaterialButton in this group.

You can use something like:

MaterialButtonToggleGroup materialButtonToggleGroup =
         findViewById(R.id.toggle_button_group);
int buttonId = materialButtonToggleGroup.getCheckedButtonId();
MaterialButton button = materialButtonToggleGroup.findViewById(buttonId);

You can also use getCheckedButtonIds() and cycle over the ids.

List<Integer> ids = materialButtonToggleGroup.getCheckedButtonIds();
for (Integer id:ids){
      MaterialButton materialButton = materialButtonToggleGroup.findViewById(id);
      //....
}


问:
How to search a value in the middle of excel for a changing value?
I am looking to create a formula in excel to find a file path value. an example is:

```<code>C:\Users\User\Desktop\Folder\x1234_namezo_ect.ext
C:\Users\User\Desktop\Folder\x1235_nameon_ect.ext
C:\Users\User\Desktop\Folder\x1233_nametw_ect.ext
C:\Users\User\Desktop\Folder\x1237_namethr_ect.ext
C:\Users\User\Desktop\Folder\x1240_namefour_ect.ext
</code>```

I am looking to get the x1234,x1235 ect. The length to the value will change over time and the file name is not always the same length. The only thing that will stay the same is the length of the x####.

Is there a formula that can be flexible and be able to find the x#### regardless of the length of either side?

答:
I found the answer through trial and error:

```<code>=left(right(A1,Len(A1)-search("\x",A1)),6)
</code>```

This looks for the \x and gets the next 4 (6 adding the \x) text after.

Body:
I am looking to create a formula in excel to find a file path value. an example is:

C:\Users\User\Desktop\Folder\x1234_namezo_ect.ext
C:\Users\User\Desktop\Folder\x1235_nameon_ect.ext
C:\Users\User\Desktop\Folder\x1233_nametw_ect.ext
C:\Users\User\Desktop\Folder\x1237_namethr_ect.ext
C:\Users\User\Desktop\Folder\x1240_namefour_ect.ext

I am looking to get the x1234,x1235 ect. The length to the value will change over time and the file name is not always the same length. The only thing that will stay the same is the length of the x####.

Is there a formula that can be flexible and be able to find the x#### regardless of the length of either side?

Body:
I found the answer through trial and error:

=left(right(A1,Len(A1)-search("\x",A1)),6)

This looks for the \x and gets the next 4 (6 adding the \x) text after.


问:
UITableView Header shows content behind it
I have a UITableView with headings on top of a textured background.  I want the header to stick at the top, which they do, but I don't want the cells to show behind it as they go by.  Here is an example:

New Content is the header.  You can see the rows of data under it as they scroll by.  I can't set the background of the header because it has to show the texture from the window behind it.  How can I not show the rows underneath the header?

答:
It's works for me.

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // bring first cell to front
        if indexPath.row == 0 {
            tableView.bringSubviewToFront(cell)
        }
    }

```


问:
How to save a Matplotlib figure in a HTML file?
So I know that i can save my diagramm with

plt.savefig('/home/pi/test.png')

But I don't really know how to save and display my diagramm with a HTML file.
For my website it would be easier use a HTML file to display my data. So is it possible to save my diagramm in HTML and how?

If it helps here is my code:

```<code>from pandas import DataFrame
import sqlite3
import matplotlib.pyplot as plt
import pandas as pd

con = sqlite3.connect("/home/pi/test2.db")
df = pd.read_sql_query("SELECT * from data4 limit 79;",con)

df.plot(x = 'zeit', y = 'temp', kind ='line')
plt.savefig('/home/pi/test.png')
#plt.show()
</code>```

I'm sorry if I did some mistakes I'm a beginner:)

答:
As far as I know that is not possible with matplotlib But it is possible with https://mpld3.github.io/ and specifically this function: https://mpld3.github.io/modules/API.html#mpld3.fig_to_html </p>

```<code>mpld3.fig_to_html(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type='general', figid=None, use_http=False, **kwargs)
Output html representation of the figure
</code>```

Body:
So I know that i can save my diagramm with

plt.savefig('/home/pi/test.png')

But I don't really know how to save and display my diagramm with a HTML file.
For my website it would be easier use a HTML file to display my data. So is it possible to save my diagramm in HTML and how?

If it helps here is my code:

from pandas import DataFrame
import sqlite3
import matplotlib.pyplot as plt
import pandas as pd

con = sqlite3.connect("/home/pi/test2.db")
df = pd.read_sql_query("SELECT * from data4 limit 79;",con)

df.plot(x = 'zeit', y = 'temp', kind ='line')
plt.savefig('/home/pi/test.png')
#plt.show()

I'm sorry if I did some mistakes I'm a beginner:)

Body:
As far as I know that is not possible with matplotlib But it is possible with https://mpld3.github.io/ and specifically this function: https://mpld3.github.io/modules/API.html#mpld3.fig_to_html

mpld3.fig_to_html(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type='general', figid=None, use_http=False, **kwargs)
Output html representation of the figure


问:
NetoworkX set edge widths according to weights
I have a numpy array:

```<code>[[12,  1,  5,  2,  2,  2,  1,  3,  1,  2],
   [ 1, 10,  3,  2,  1,  7,  2,  6,  1,  0],
   [ 5,  3, 26,  5,  1,  5,  2, 11,  3,  5],
   [ 2,  2,  5, 11,  1,  2,  1,  7,  2,  4],
   [ 2,  1,  1,  1, 17,  2,  1,  6,  2,  2],
   [ 2,  7,  5,  2,  2, 22, 12,  8,  1,  0],
   [ 1,  2,  2,  1,  1, 12, 21,  7,  0,  1],
   [ 3,  6, 11,  7,  6,  8,  7, 23,  0,  5],
   [ 1,  1,  3,  2,  2,  1,  0,  0,  3,  1],
   [ 2,  0,  5,  4,  2,  0,  1,  5,  1,  4]]
</code>```

I am trying to create a 2D network graph such as this - at the bottom of the page (just 2D).

I found a library called networkx that has a pretty simple function to create a 2D graph from a numpy array:

```<code>import networkx as nx
G = nx.from_numpy_matrix(array)
nx.draw(G, with_labels=1)
</code>```

But it's not interactive.

I'm also trying to replace the labels on the graph with the actual labels of the array (which are strings- say, 'one', 'two'... 'ten').
Lastly, the goal is for the graph to have edges where the width of the edge is the number in the array.

答:
Through nx.draw you can customise the visualisation to fit most of the mentioned requirements. Though in some cases you might need to use other options available in Drawing such as nx. draw_networkx_nodes etc. for further customisation.

In this case, and assuming you have an arraylike with the label names you want to set, you can use nx.draw_networkx_labels and specify the mapping of the labels with a dictionary, which you could define as:

```<code>G = nx.from_numpy_matrix(a)

nodelist = G.nodes()
num_words = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
d_labels = dict(zip(nodelist, num_words))
</code>```

Note that by using nx.from_numpy_matrix the actual values in the array are set as edge weights, so you can use nx.get_edge_attributes to obtain the corresponding edge widths.

```<code>widths = nx.get_edge_attributes(G, 'weight')
</code>```

The widths can be later set in nx.draw_networkx_edges through the width parameter. Finally, in regards to making the graph interactive, you may look into node_picking.

Putting it all together, we can plot the graph as:

```<code>plt.figure(figsize=(18,13))

pos = nx.spring_layout(G, scale=0.2)
nx.draw_networkx_nodes(G,pos,
                       nodelist=nodelist,
                       with_labels=True,
                       node_size=1500,
                       node_color='black',
                       font_color='white',
                       alpha=0.7)
nx.draw_networkx_edges(G,pos,
                       edgelist = widths.keys(),
                       width=list(widths.values()),
                       edge_color='orange',
                       alpha=0.6)
nx.draw_networkx_labels(G, pos=pos,
                        labels=d_labels,
                        font_color='white')
plt.box(False)
plt.show()
</code>```

Body:
I have a numpy array:

[[12,  1,  5,  2,  2,  2,  1,  3,  1,  2],
   [ 1, 10,  3,  2,  1,  7,  2,  6,  1,  0],
   [ 5,  3, 26,  5,  1,  5,  2, 11,  3,  5],
   [ 2,  2,  5, 11,  1,  2,  1,  7,  2,  4],
   [ 2,  1,  1,  1, 17,  2,  1,  6,  2,  2],
   [ 2,  7,  5,  2,  2, 22, 12,  8,  1,  0],
   [ 1,  2,  2,  1,  1, 12, 21,  7,  0,  1],
   [ 3,  6, 11,  7,  6,  8,  7, 23,  0,  5],
   [ 1,  1,  3,  2,  2,  1,  0,  0,  3,  1],
   [ 2,  0,  5,  4,  2,  0,  1,  5,  1,  4]]

I am trying to create a 2D network graph such as this - at the bottom of the page (just 2D).

I found a library called networkx that has a pretty simple function to create a 2D graph from a numpy array:

import networkx as nx
G = nx.from_numpy_matrix(array)
nx.draw(G, with_labels=1)

But it's not interactive.

I'm also trying to replace the labels on the graph with the actual labels of the array (which are strings- say, 'one', 'two'... 'ten').
Lastly, the goal is for the graph to have edges where the width of the edge is the number in the array.

Body:
Through nx.draw you can customise the visualisation to fit most of the mentioned requirements. Though in some cases you might need to use other options available in Drawing such as nx. draw_networkx_nodes etc. for further customisation.

In this case, and assuming you have an arraylike with the label names you want to set, you can use nx.draw_networkx_labels and specify the mapping of the labels with a dictionary, which you could define as:

G = nx.from_numpy_matrix(a)

nodelist = G.nodes()
num_words = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
d_labels = dict(zip(nodelist, num_words))

Note that by using nx.from_numpy_matrix the actual values in the array are set as edge weights, so you can use nx.get_edge_attributes to obtain the corresponding edge widths.

widths = nx.get_edge_attributes(G, 'weight')

The widths can be later set in nx.draw_networkx_edges through the width parameter. Finally, in regards to making the graph interactive, you may look into node_picking.

Putting it all together, we can plot the graph as:

plt.figure(figsize=(18,13))

pos = nx.spring_layout(G, scale=0.2)
nx.draw_networkx_nodes(G,pos,
                       nodelist=nodelist,
                       with_labels=True,
                       node_size=1500,
                       node_color='black',
                       font_color='white',
                       alpha=0.7)
nx.draw_networkx_edges(G,pos,
                       edgelist = widths.keys(),
                       width=list(widths.values()),
                       edge_color='orange',
                       alpha=0.6)
nx.draw_networkx_labels(G, pos=pos,
                        labels=d_labels,
                        font_color='white')
plt.box(False)
plt.show()


问:
How to create a has_many relation record in rails?`
I have a user model with some relations, and I want the user to be able to make Posts. So I set up a post model. The models are as shown below:

```<code>User.rb
belongs_to :plan

  has_one :profile

  has_many :posts

  has_many :follower_relationships, class_name: "Follow", foreign_key: "following_id"
  has_many :followers, through: :follower_relationships, source: :follower

  has_many :following_relationships, class_name: "Follow", foreign_key: "user_id"
  has_many :following, through: :following_relationships, source: :following

Post.rb
belongs_to :User
</code>```

So my attempt to create a record:

```<code>def new
    @post = Post.new(user: current_user.id)
  end

  def create
    @post = @user.posts.create(post_params.merge(user_id: @user))

    if @post.save
      flash[:success] = "Post successfully created"
      redirect_to @post
    else
      flash[:danger] = @post.errors.messages.inspect
      render 'new'
    end
  end
</code>```

However, it returns the error {:User=>["must exist"]}. But the User does exist and is being passed in to the form.Then decided to try and create a post in the rails console.

```<code> o = User.first.posts.build(image_url: "https://images.pexels.com/photos/188777/pexels-photo-188777.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", title: "some", subtitle: "thing", body: "body")
o.save!
</code>```

and it returned ActiveRecord::RecordInvalid (Validation failed: User must exist)

Why does rails think the user does not exist??

答:
A user is a record, a user_id is an integer field. You're confusing them.

So this doesn't work...

```<code>@post = Post.new(user: current_user.id)
</code>```

Instead do...

```<code>@post = Post.new(user_id: current_user.id)
</code>```

or better...

```<code>@post = Post.new(user: current_user)
</code>```

same goes for where you set user_id: @user ... you probably want user_id: @user.id

Body:
I have a user model with some relations, and I want the user to be able to make Posts. So I set up a post model. The models are as shown below:

User.rb
belongs_to :plan

  has_one :profile

  has_many :posts

  has_many :follower_relationships, class_name: "Follow", foreign_key: "following_id"
  has_many :followers, through: :follower_relationships, source: :follower

  has_many :following_relationships, class_name: "Follow", foreign_key: "user_id"
  has_many :following, through: :following_relationships, source: :following

Post.rb
belongs_to :User

So my attempt to create a record:

def new
    @post = Post.new(user: current_user.id)
  end

  def create
    @post = @user.posts.create(post_params.merge(user_id: @user))

    if @post.save
      flash[:success] = "Post successfully created"
      redirect_to @post
    else
      flash[:danger] = @post.errors.messages.inspect
      render 'new'
    end
  end

However, it returns the error {:User=>["must exist"]}. But the User does exist and is being passed in to the form.Then decided to try and create a post in the rails console.

 o = User.first.posts.build(image_url: "https://images.pexels.com/photos/188777/pexels-photo-188777.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940", title: "some", subtitle: "thing", body: "body")
o.save!

and it returned ActiveRecord::RecordInvalid (Validation failed: User must exist)

Why does rails think the user does not exist??

Body:
A user is a record, a user_id is an integer field. You're confusing them.

So this doesn't work...

@post = Post.new(user: current_user.id)

Instead do...

@post = Post.new(user_id: current_user.id)

or better...

@post = Post.new(user: current_user)

same goes for where you set user_id: @user ... you probably want user_id: @user.id


问:
Drupal 8 Access Denied
I've just taken a copy of my drupal 8 database from staging and loaded this on my development enviroment.

I now get access denied when I try to login /admin

Can't find any information on why.

Update

Seems to be something to do with a twig service where the urlGenerator is not being implemented. Still no luck fixing this.

答: In hoster`s panel try find "IP address:" settings and change it from "Dedicated IP" (this option can have dependant "This site processes direct requests to a dedicated IP address" tick) to "Shared IP".</p>

Title: Drupal 8 Access Denied


问:
Get a line of space-separated integers from stdio without knowing how much they are (C++)
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:

```<code>int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];
</code>```

In case I don't have 'n', how would I achieve the same thing?

答:
std::vector<int> is basically a dynamically-sized array of ints. You can keep adding stuff to it and it will grow as necessary.  If you are given a number of elements as the first input, you can do something like:

```<code>std::vector<int> items;

int count;
std::cin >> count;

// Preallocates room for the items. This is not necessary, it's just an optimization.
items.reserve(count);

while (count > 0) {
    int item;
    std::cin >> item;
    items.push_back(item);
    --count;
}
</code>```

If you are not given the number of items, just read until reading fails:

```<code>std::vector<int> items;
int item;

while (std::cin >> item) {
    items.push_back(item);
}
</code>```

Body:
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:

int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];

In case I don't have 'n', how would I achieve the same thing?

Body:
std::vector<int> is basically a dynamically-sized array of ints. You can keep adding stuff to it and it will grow as necessary.  If you are given a number of elements as the first input, you can do something like:

std::vector<int> items;

int count;
std::cin >> count;

// Preallocates room for the items. This is not necessary, it's just an optimization.
items.reserve(count);

while (count > 0) {
    int item;
    std::cin >> item;
    items.push_back(item);
    --count;
}

If you are not given the number of items, just read until reading fails:

std::vector<int> items;
int item;

while (std::cin >> item) {
    items.push_back(item);
}


问:
Android-CameraX: Switch between multiple front cameras
I´m trying to write my first Android Camera App, but it always selects the zoom camera instead of the main camera. (I tested it on a Huawei P30 Pro)

And the code is based on the offical camerax sample application (https://github.com/android/camera-samples/tree/master/CameraXBasic)

The relevant code:

```<code>/** Declare and bind preview, capture and analysis use cases */
private fun bindCameraUseCases() {

    // Get screen metrics used to setup camera for full screen resolution
    val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
    Log.d(TAG, "Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}")

    val screenAspectRatio = aspectRatio(metrics.widthPixels, metrics.heightPixels)
    Log.d(TAG, "Preview aspect ratio: $screenAspectRatio")

    val rotation = viewFinder.display.rotation

    // Bind the CameraProvider to the LifeCycleOwner

    val cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build()

    val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
    cameraProviderFuture.addListener(Runnable {

        // CameraProvider
        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

        // Preview
        preview = Preview.Builder()
            // We request aspect ratio but no resolution
            .setTargetAspectRatio(screenAspectRatio)
            // Set initial target rotation
            .setTargetRotation(rotation)
            .build()

        // ImageCapture
        imageCapture = ImageCapture.Builder()
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
            // We request aspect ratio but no resolution to match preview config, but letting
            // CameraX optimize for whatever specific resolution best fits our use cases
            .setTargetAspectRatio(screenAspectRatio)
            // Set initial target rotation, we will have to call this again if rotation changes
            // during the lifecycle of this use case
            .setTargetRotation(rotation)
            .build()

        // Must unbind the use-cases before rebinding them
        cameraProvider.unbindAll()

        try {
            // A variable number of use-cases can be passed here -
            // camera provides access to CameraControl & CameraInfo
            camera = cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview, imageCapture /**, imageAnalyzer*/)

            // Attach the viewfinder's surface provider to preview use case
            preview?.setSurfaceProvider(viewFinder.createSurfaceProvider(camera?.cameraInfo))
        } catch(exc: Exception) {
            Log.e(TAG, "Use case binding failed", exc)
        }

    }, ContextCompat.getMainExecutor(requireContext()))
}
</code>```

答:
I have a similar issue but with the back camera. I checked some devices and found that on all my tested device I can select the camera id and get the right camera:

Camera ID "0" -> Normal/default back facing camera

Camera ID "1" ->    Normal/default front facing camera

So I created a custom CameraFilter where I filter for camera id "0":

```<code>class CameraIdFilter(private val cameraId: String) : CameraFilter {

override fun filterCameras(cameras: Set<CameraInternal>): Set<CameraInternal> {
    val resultCameras: MutableSet<CameraInternal> = LinkedHashSet()
    for (camera in cameras) {
        val cameraId = camera.cameraInfoInternal.cameraId
        if (cameraId == this.cameraId) {
            resultCameras.add(camera)
        }
    }
    return resultCameras
}
</code>```

}

And append the filter to the camera selector:

```<code>        val cameraSelectorBuilder = CameraSelector.Builder()
            .requireLensFacing(lensFacing)
            .appendFilter(CameraIdFilter("0"))
</code>```

I don't recommend using this in a production app, because I'm sure there are some devices that don't follow this convention/pattern. But you can use it for an internal app where you know which devices your users use

Body:
I´m trying to write my first Android Camera App, but it always selects the zoom camera instead of the main camera. (I tested it on a Huawei P30 Pro)

And the code is based on the offical camerax sample application (https://github.com/android/camera-samples/tree/master/CameraXBasic)

The relevant code:

/** Declare and bind preview, capture and analysis use cases */
private fun bindCameraUseCases() {

    // Get screen metrics used to setup camera for full screen resolution
    val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
    Log.d(TAG, "Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}")

    val screenAspectRatio = aspectRatio(metrics.widthPixels, metrics.heightPixels)
    Log.d(TAG, "Preview aspect ratio: $screenAspectRatio")

    val rotation = viewFinder.display.rotation

    // Bind the CameraProvider to the LifeCycleOwner

    val cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build()

    val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
    cameraProviderFuture.addListener(Runnable {

        // CameraProvider
        val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

        // Preview
        preview = Preview.Builder()
            // We request aspect ratio but no resolution
            .setTargetAspectRatio(screenAspectRatio)
            // Set initial target rotation
            .setTargetRotation(rotation)
            .build()

        // ImageCapture
        imageCapture = ImageCapture.Builder()
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
            // We request aspect ratio but no resolution to match preview config, but letting
            // CameraX optimize for whatever specific resolution best fits our use cases
            .setTargetAspectRatio(screenAspectRatio)
            // Set initial target rotation, we will have to call this again if rotation changes
            // during the lifecycle of this use case
            .setTargetRotation(rotation)
            .build()

        // Must unbind the use-cases before rebinding them
        cameraProvider.unbindAll()

        try {
            // A variable number of use-cases can be passed here -
            // camera provides access to CameraControl & CameraInfo
            camera = cameraProvider.bindToLifecycle(
                    this, cameraSelector, preview, imageCapture /**, imageAnalyzer*/)

            // Attach the viewfinder's surface provider to preview use case
            preview?.setSurfaceProvider(viewFinder.createSurfaceProvider(camera?.cameraInfo))
        } catch(exc: Exception) {
            Log.e(TAG, "Use case binding failed", exc)
        }

    }, ContextCompat.getMainExecutor(requireContext()))
}

Body:
I have a similar issue but with the back camera. I checked some devices and found that on all my tested device I can select the camera id and get the right camera:

Camera ID "0" -> Normal/default back facing camera

Camera ID "1" ->    Normal/default front facing camera

So I created a custom CameraFilter where I filter for camera id "0":

class CameraIdFilter(private val cameraId: String) : CameraFilter {

override fun filterCameras(cameras: Set<CameraInternal>): Set<CameraInternal> {
    val resultCameras: MutableSet<CameraInternal> = LinkedHashSet()
    for (camera in cameras) {
        val cameraId = camera.cameraInfoInternal.cameraId
        if (cameraId == this.cameraId) {
            resultCameras.add(camera)
        }
    }
    return resultCameras
}

}

And append the filter to the camera selector:

        val cameraSelectorBuilder = CameraSelector.Builder()
            .requireLensFacing(lensFacing)
            .appendFilter(CameraIdFilter("0"))

I don't recommend using this in a production app, because I'm sure there are some devices that don't follow this convention/pattern. But you can use it for an internal app where you know which devices your users use