问:
Finding and Installing Latest file in directory with specific extension
I'm trying to search for the latest .msi file, and install it in the background.

I have tried following the help from this link but it did not help.

This is what I currently have:

```<code>  @echo off
setlocal

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::

FOR /F "eol=| delims=" %%I IN ('DIR "directory" /A-D /B /S /O-D /TW 2^>nul')
DO (
    ECHO %%~I
    SET "NewestFile=%%~I"
    GOTO FoundFile
)
ECHO No *.msi file found!
GOTO :EOF

:FoundFile
msiexec.exe /I "%NewestFile%" /Q

::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.
</code>```

I'm guessing the problem is with the :FoundFile and the execution part or finding the correct file based off of time.

I was thinking maybe I have to use:

```<code>forfiles /p "dir" /m *.msi /S /D +%Date%
</code>```

but I'm not entirely sure.

答:
```<code>@echo off
setlocal

rem Search in this directory path.
set "searchdir=%~dp0directory\"

rem Escape the directory path.
set "searchdir=%searchdir:\=\\%"

rem Display the directory path.
echo %searchdir%

rem Get the latest msi file.
for /f "usebackq tokens=1,* delims= " %%A in (`
 wmic datafile where "extension='msi' and name like '%searchdir%%%'"
 get lastmodified^, name ^| sort /r ^| findstr "\\"
`) do (
    set "NewestFile=%%~B"
    echo FoundFile: %%~B
    goto :FoundFile
)

echo No *.msi file found!
exit /b

:FoundFile
rem Install the latest msi file.
msiexec.exe /i "%NewestFile%" /q
exit /b 0
</code>```

The directory fullpath is setup as directory which
is appended to the directory of the script.
The backslashes need to be escaped for use with wmic,
so variable substition to change \ to \\ is done.
The directory path is then echoed for inspection.

The for loop uses wmic to get the lastmodified
timestamp and name which will be the fullpath
to the found msi file. sort /r will reverse the
sorted order so the latest is the first.
findstr "\\" will only output values with a path
separator \. The variable named NewestFile
stores the msi fullpath, echo outputs the msi
path to stdout for inspection, and the
goto :FoundFile event occurs.

msiexec.exe runs installation with the newest file.

Note:

NewestFile may contain a msi path with trailing spaces.
This should do no harm to leave and I chose not to trim
in case of causing harm in an unneeded trim operation.

Testing shows that wmic processes actual paths,
not reparse points i.e. symlinked paths. Ensure running
the script from an actual path else the name like ...
query of wmic may not match anything.

You can replace the code between the
::ENTER YOUR CODE BELOW:: and
::END OF YOUR CODE:: in your posted code, without the
@echo off and setlocal as you already have those lines.

Body:
I'm trying to search for the latest .msi file, and install it in the background.

I have tried following the help from this link but it did not help.

This is what I currently have:

  @echo off
setlocal

if _%1_==_payload_  goto :payload

:getadmin
    echo %~nx0: elevating self
    set vbs=%temp%\getadmin.vbs
    echo Set UAC = CreateObject^("Shell.Application"^)                >> "%vbs%"
    echo UAC.ShellExecute "%~s0", "payload %~sdp0 %*", "", "runas", 1 >> "%vbs%"
    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
goto :eof

:payload

::ENTER YOUR CODE BELOW::

FOR /F "eol=| delims=" %%I IN ('DIR "directory" /A-D /B /S /O-D /TW 2^>nul')
DO (
    ECHO %%~I
    SET "NewestFile=%%~I"
    GOTO FoundFile
)
ECHO No *.msi file found!
GOTO :EOF

:FoundFile
msiexec.exe /I "%NewestFile%" /Q

::END OF YOUR CODE::

echo.
echo...Script Complete....
echo.

I'm guessing the problem is with the :FoundFile and the execution part or finding the correct file based off of time.

I was thinking maybe I have to use:

forfiles /p "dir" /m *.msi /S /D +%Date%

but I'm not entirely sure.

Body:
@echo off
setlocal

rem Search in this directory path.
set "searchdir=%~dp0directory\"

rem Escape the directory path.
set "searchdir=%searchdir:\=\\%"

rem Display the directory path.
echo %searchdir%

rem Get the latest msi file.
for /f "usebackq tokens=1,* delims= " %%A in (`
 wmic datafile where "extension='msi' and name like '%searchdir%%%'"
 get lastmodified^, name ^| sort /r ^| findstr "\\"
`) do (
    set "NewestFile=%%~B"
    echo FoundFile: %%~B
    goto :FoundFile
)

echo No *.msi file found!
exit /b

:FoundFile
rem Install the latest msi file.
msiexec.exe /i "%NewestFile%" /q
exit /b 0

The directory fullpath is setup as directory which
is appended to the directory of the script.
The backslashes need to be escaped for use with wmic,
so variable substition to change \ to \\ is done.
The directory path is then echoed for inspection.

The for loop uses wmic to get the lastmodified
timestamp and name which will be the fullpath
to the found msi file. sort /r will reverse the
sorted order so the latest is the first.
findstr "\\" will only output values with a path
separator \. The variable named NewestFile
stores the msi fullpath, echo outputs the msi
path to stdout for inspection, and the
goto :FoundFile event occurs.

msiexec.exe runs installation with the newest file.

Note:

NewestFile may contain a msi path with trailing spaces.
This should do no harm to leave and I chose not to trim
in case of causing harm in an unneeded trim operation.

Testing shows that wmic processes actual paths,
not reparse points i.e. symlinked paths. Ensure running
the script from an actual path else the name like ...
query of wmic may not match anything.

You can replace the code between the
::ENTER YOUR CODE BELOW:: and
::END OF YOUR CODE:: in your posted code, without the
@echo off and setlocal as you already have those lines.


来源: stackexchange

问:
make radio button selected based on an event
I have several divs of class OuterDiv that contain divs of class InnerDiv that contain radio buttons.

```<code><div class="OuterDiv">
  <div class="InnerDiv">
    <input type="radio" name="TheOptions" />option 1
  </div>
</div>

<div class="OuterDiv">
  <div class="InnerDiv">
    <input type="radio" name="TheOptions" />option 2
  </div>
</div>

<div class="OuterDiv">
  <div class="InnerDiv">
    <input type="radio" name="TheOptions" />option 3
  </div>
</div>
</code>```

I'm looking to catch the event "user clicked on div" to make the corresponding radio button selected.

This is what I have so far:

```<code>$('.OuterDiv .InnerDiv').click(function {

  $(this).find('radio')....

});
</code>```

I can get to the radio button but I'm stuck on making it selected and making any of the currently selected button unselected (unless selecting one automatically unselects all others).

Thanks for your suggestions.

答:
I'm not sure why you need TWO DIVs to wrap it. One will do.

$(this).find('input').attr('checked','true')

ContentLicense: CC BY-SA 3.0

Body:
I have several divs of class OuterDiv that contain divs of class InnerDiv that contain radio buttons.

    <input type="radio" name="TheOptions" />option 1

    <input type="radio" name="TheOptions" />option 2

    <input type="radio" name="TheOptions" />option 3

I'm looking to catch the event "user clicked on div" to make the corresponding radio button selected.

This is what I have so far:

$('.OuterDiv .InnerDiv').click(function {

  $(this).find('radio')....

});

I can get to the radio button but I'm stuck on making it selected and making any of the currently selected button unselected (unless selecting one automatically unselects all others).

Thanks for your suggestions.


问:
how to specify a variable/parameter in my logic app's arm template?
I am creating an Arm template for a logic app. This logic app needs to delete some old entries in azure table (say 10 or 20 days old).

In my arm template, if I do this, it works.

```<code>"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),-31)}'"
  }
</code>```

But ideally I want to do this:

```<code>"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay'))}'"
   }
</code>```

Basically use a parameter to control the amount of days to check. I define this parameter as:

```<code> "parameters": {
    "RetainDay": {
      "type": "int"
    }
  }
</code>```

When I deploy this, the parameters('RetainDay') isn't replaced to the parameter value. Instead it just stays same as:

```<code>Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay')
</code>```

So I must be using the wrong syntax.

Can someone point it out?

答:
You need to connect the 'Logic Apps template parameter' together with the 'ARM deployment template parameter', as much as it looks like the one and same variable, it is two parameters that work together. In my solution, I have a parameter called 'CustomVariableName'

Passing the parameter

Declaring the CustomVariableName in the "logic app code" and in the ARM template

Value in parameters file

Deployed Logic App in Azure

Postman POST response from hitting the HTTP trigger(instead of value: 'DefaultValue')

ContentLicense: CC BY-SA 4.0

Body:
I am creating an Arm template for a logic app. This logic app needs to delete some old entries in azure table (say 10 or 20 days old).

In my arm template, if I do this, it works.

"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),-31)}'"
  }

But ideally I want to do this:

"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay'))}'"
   }

Basically use a parameter to control the amount of days to check. I define this parameter as:

 "parameters": {
    "RetainDay": {
      "type": "int"
    }
  }

When I deploy this, the parameters('RetainDay') isn't replaced to the parameter value. Instead it just stays same as:

Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay')

So I must be using the wrong syntax.

Can someone point it out?


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

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

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

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

def api_proxy(event, context):

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

    url = ORIGIN + event['path']

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

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

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

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

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

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

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

答:
Turns out that under the hood of the endpoint I am trying to hit there is a authentication redirect which does not encode the url and as such is truncating the query string.

I discovered this by looking at the dataRequest.history URLs.

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

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

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

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

def api_proxy(event, context):

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

    url = ORIGIN + event['path']

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

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

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

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

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

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

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


问:
How to fix 'Cannot read property 'document' of null' when trying to access window.opener.document
I'm trying to access elements in the window that opened the popup however, as the title says, I'm getting 'Cannot read property 'document' of null' when trying to access them.

I've seen a few other posts on this subject however unfortunately none of them helped in this case.

I've tried
    openerWindow = window.opener.document;
       selectedTableRow = openerWindow.querySelectorAll(".highlighted-rows");

As well as
    selectedTableRow = window.parent.document.querySelectorAll(".highlighted-rows");

The above does run, however it brings back an empty array, even though I know that there are table rows with the class .highlighted-rows

And
    selectedTableRow = window.opener.document.querySelectorAll(".highlighted-rows");

The interesting thing is, when I try running selectedTableRow = window.opener.document.querySelectorAll(".highlighted-rows"); through the Chrome console, it actually works and returns the row I was expecting, it's just running it through the code that fails.

答:
You will only have an opener if it was set.  See docs for more details, but the important bit:

When a window is opened from another window (using Window.open or a link with its target attribute set), it maintains a reference to that first window as window.opener. If the current window has no opener, this method returns null.

If you're sure the window you're trying to access should have an opener, can you post the code that spawned it?


问:
One REPL to bind them all?
I'd like to know if there is a REPL which is not language-specific.  I spend a lot of time dipping in and out of REPLs (mainly for Clojure, Scala and Haskell), and the bundled ones all frustrate me to a greater or lesser extent.  It seems like the job of a REPL is quite generic in that they:

Read: take user input

Evaluate: pass the input to some runtime for processing

Print: print the results to the screen

Loop: wait for the next user input

I don't see why there shouldn't be some language-agnostic REPL, but I have been unable to find such a thing.  Some things I would like in my ideal REPL:

Linux command-line application

Infinite history accessible through the up arrow

Ability to edit previous commands before re-running

ctrl-r for history search like bash has

Multiple sessions in one REPL, so I can switch between them easily

And more optimistically

syntax highlighting, context-aware code completion

Does this exist?

答:
Bash doesn't know anything about C-r: it uses readline, which does that, as well as up-arrow history, for it. It sounds like the REPL you're looking for is readline? Just prefix the command you want REPL-like behavior from with rlwrap (install it if you don't have it - it's great), and you should be good to go.

```<code>$ rlwrap java -jar clojure.jar
</code>```

Title: One REPL to bind them all?

Body:
Bash doesn't know anything about C-r: it uses readline, which does that, as well as up-arrow history, for it. It sounds like the REPL you're looking for is readline? Just prefix the command you want REPL-like behavior from with rlwrap (install it if you don't have it - it's great), and you should be good to go.

$ rlwrap java -jar clojure.jar


问:
Mixed format axis labels in ggplot chart
Is it possible to have a ggplot axis with date-formatted labels and text-formatted labels?

The following code produces a chart with a date formatted x axis that runs from Jan-18 to Jun-19.

```<code>#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(aes(colour = meltdf2$colour, size = 3)) +
  geom_point(data = melt_change, aes(shape = value, size = 3)) +
  scale_colour_manual(values = pal, limits = names(pal), guide_legend("Risk Level")) +
  scale_shape_manual(values = sh_pal, limits = names(sh_pal), guide_legend("Latest Change")) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"), axis.title.x=element_blank(),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.position = c(0.2,0.70),
        legend.key.size = unit(1.5,"line")) +
  guides(colour = guide_legend(override.aes = list(size = 3)), shape = guide_legend(override.aes = list(size = 5))) +
  scale_size(guide = "none")
</code>```

However, I would like the Jun-19 date label to be replaced by a text label that reads "Change". Is there a way to do this without specifying all the labels individually?

I have tried to produce a vector that can be used as a labels argument in the scale_x_date function using the following code:

```<code>x_labels <- (as.Date(unique(meltdf2$Month)))
x_labels <- sort(x_labels)
x_labels <- c(x_labels,"Change")
</code>```

But the vector does not seem to sort the dates correctly and the text "Change" value is replaced by an NA.

答:
As the example is not fully reproducible, I have created a response with fictitious data.

Note that I had to create a new column for the period (Period) under analysis, so that it is a factor and where I added the name "Change".

Later I reordered the levels using forcats, function fct_reorder, based on the dates (Dates) of interest.

```<code>library(dplyr)
library(lubridate)
library(ggplot2)
library(forcats)
set.seed(1)
Period_x <- data.frame(Period = seq(lubridate::mdy('jan-01-2018'),
                                    lubridate::mdy('may-01-2019'),
                                    by = 'month'))

Period_x <- Period_x %>%
  dplyr::mutate(Period = format(Period, '%b-%y'))
Period_x <- rbind(Period_x, "Change")

Period2 <- seq(lubridate::mdy('jan-01-2018'),
               lubridate::mdy('jun-01-2019'),
               by = 'month')

Period_x <- Period_x %>%
  dplyr::mutate(Dates = Period2,
                y = rnorm(18),
                Period = as.factor(Period),
                Period = forcats::fct_reorder(Period,
                                              Dates))

ggplot2::ggplot(Period_x) +
  geom_point(aes(x = Period, y = y))
</code>```

Body:
Is it possible to have a ggplot axis with date-formatted labels and text-formatted labels?

The following code produces a chart with a date formatted x axis that runs from Jan-18 to Jun-19.

#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
  geom_line(linetype = "dashed", colour = "grey") +
  geom_point(aes(colour = meltdf2$colour, size = 3)) +
  geom_point(data = melt_change, aes(shape = value, size = 3)) +
  scale_colour_manual(values = pal, limits = names(pal), guide_legend("Risk Level")) +
  scale_shape_manual(values = sh_pal, limits = names(sh_pal), guide_legend("Latest Change")) +
  scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
  theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
        axis.line.x = element_line(colour = "darkgrey"), axis.title.x=element_blank(),
        panel.background = element_rect(fill = "white"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.position = c(0.2,0.70),
        legend.key.size = unit(1.5,"line")) +
  guides(colour = guide_legend(override.aes = list(size = 3)), shape = guide_legend(override.aes = list(size = 5))) +
  scale_size(guide = "none")

However, I would like the Jun-19 date label to be replaced by a text label that reads "Change". Is there a way to do this without specifying all the labels individually?

I have tried to produce a vector that can be used as a labels argument in the scale_x_date function using the following code:

x_labels <- (as.Date(unique(meltdf2$Month)))
x_labels <- sort(x_labels)
x_labels <- c(x_labels,"Change")

But the vector does not seem to sort the dates correctly and the text "Change" value is replaced by an NA.

Body:
As the example is not fully reproducible, I have created a response with fictitious data.

Note that I had to create a new column for the period (Period) under analysis, so that it is a factor and where I added the name "Change".

Later I reordered the levels using forcats, function fct_reorder, based on the dates (Dates) of interest.

library(dplyr)
library(lubridate)
library(ggplot2)
library(forcats)
set.seed(1)
Period_x <- data.frame(Period = seq(lubridate::mdy('jan-01-2018'),
                                    lubridate::mdy('may-01-2019'),
                                    by = 'month'))

Period_x <- Period_x %>%
  dplyr::mutate(Period = format(Period, '%b-%y'))
Period_x <- rbind(Period_x, "Change")

Period2 <- seq(lubridate::mdy('jan-01-2018'),
               lubridate::mdy('jun-01-2019'),
               by = 'month')

Period_x <- Period_x %>%
  dplyr::mutate(Dates = Period2,
                y = rnorm(18),
                Period = as.factor(Period),
                Period = forcats::fct_reorder(Period,
                                              Dates))

ggplot2::ggplot(Period_x) +
  geom_point(aes(x = Period, y = y))


问:
how three loops are getting executed
I have a problem with this line of code:

```<code>res = [[int(i) for i in sub] for i in test_list for sub in i]
</code>```

When this line will execute int(i) will get 24 in the first iteration and then this 24 is converted into [2,4] as shown in the output listed below.
How 24 can get converted into [2,4] which is a list? To get converted into a list, numbers should be iterable, shouldn't they?

```<code>   test_list = [['24'], ['45'], ['78'], ['40']]
   print("The original list : " + str(test_list))
   res = [[int(i) for i in sub] for i in test_list for sub in i]
   print("The list after conversion : " + str(res))
</code>```

Output is:

```<code>     The original list : [['24'], ['45'], ['78'], ['40']]
     The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]
</code>```

答:
for i in test_list will iterate through the list and return you ['24'] -> ['45'] -> ['78'] -> ['40']

for sub in i will iterate through these lists. Each of them contains only one element which will be returned.

for i in sub will iterate through strings and return each char: `'24': '2' -> '4'

so

[int(i) for i in sub] will return you such lists: [[2, 4], [4, 5], [7, 8], [4, 0]]

If you want a list of integers, you can use:

res = [int(l[0]) for l in test_list]

[24, 45, 78, 40]

Title: how three loops are getting executed

Body:
I have a problem with this line of code:

res = [[int(i) for i in sub] for i in test_list for sub in i]

When this line will execute int(i) will get 24 in the first iteration and then this 24 is converted into [2,4] as shown in the output listed below.
How 24 can get converted into [2,4] which is a list? To get converted into a list, numbers should be iterable, shouldn't they?

   test_list = [['24'], ['45'], ['78'], ['40']]
   print("The original list : " + str(test_list))
   res = [[int(i) for i in sub] for i in test_list for sub in i]
   print("The list after conversion : " + str(res))

Output is:

     The original list : [['24'], ['45'], ['78'], ['40']]
     The list after conversion : [[2, 4], [4, 5], [7, 8], [4, 0]]


问:
How to update a RoR model's associations without updating the corresponding model's attributes
I have the following models (with corresponding database tables) in my Rails 3 application:

```<code>class User < ActiveRecord::Base
  has_many :service_users
  has_many :services, :through => :service_users

  attr_accessor :password

  attr_accessible :password, :password_confirmation, :service_ids

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }
  ...
end

class Service < ActiveRecord::Base
  has_many :service_users
  has_many :users, :through => :service_users
  ...
end

class ServiceUser < ActiveRecord::Base
  belongs_to :service
  belongs_to :user
end

#User Controller:

class UsersController < ApplicationController
  ...
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end
  ...
end
</code>```

I want to be able to update a User model's associated services without having to specify the password and password confirmation attributes. How can I do this?

答:
Two options...

If you have simple logic, like only validating the password when a user is created, this will work:

```<code>validates :password, :presence => true,
                     :confirmation => true,
                     :length => { :within => 6..40 },
                     :if => :new_record?
</code>```

More likely, you'll want a combination so that users can update their password:

```<code>validates :password, :presence => true,
                     :confirmation => true,
                     :length => { :within => 6..40 },
                     :if => :is_password_validation_needed?

# Protect the password attribute from writing an
# empty or nil value
def password=(pass)
  return if !pass.present?
  @password = pass
end

private

  def is_password_validation_needed?
    # Return true if the record is unsaved or there
    # is a non-nil value in self.password
    new_record? || password
  end
</code>```

Body:
I have the following models (with corresponding database tables) in my Rails 3 application:

class User < ActiveRecord::Base
  has_many :service_users
  has_many :services, :through => :service_users

  attr_accessor :password

  attr_accessible :password, :password_confirmation, :service_ids

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }
  ...
end

class Service < ActiveRecord::Base
  has_many :service_users
  has_many :users, :through => :service_users
  ...
end

class ServiceUser < ActiveRecord::Base
  belongs_to :service
  belongs_to :user
end

#User Controller:

class UsersController < ApplicationController
  ...
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end
  ...
end

I want to be able to update a User model's associated services without having to specify the password and password confirmation attributes. How can I do this?

Body:
Two options...

If you have simple logic, like only validating the password when a user is created, this will work:

validates :password, :presence => true,
                     :confirmation => true,
                     :length => { :within => 6..40 },
                     :if => :new_record?

More likely, you'll want a combination so that users can update their password:

validates :password, :presence => true,
                     :confirmation => true,
                     :length => { :within => 6..40 },
                     :if => :is_password_validation_needed?

# Protect the password attribute from writing an
# empty or nil value
def password=(pass)
  return if !pass.present?
  @password = pass
end

private

  def is_password_validation_needed?
    # Return true if the record is unsaved or there
    # is a non-nil value in self.password
    new_record? || password
  end


问:
Upload image to Google Cloud Storage (Java)
I want to develop a java-application (for pc) which can upload any picture to Google Cloud Storage. Although I have spent my whole evening on searching for a solution, I don't have any clue how to start. Does anyone of you have experience with uploading images to Google Cloud Storage? Are there better alternatives to Google Cloud Storage?</p>

答:
You can public your file, and then the media link of the blob can access anywhere.

https://cloud.google.com/storage/docs/access-control/making-data-public

This is my solution.

```<code>try {
    FileInputStream serviceAccount =
            new FileInputStream("firebaseKey/serviceAccountKey.json");

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://xxxxx.firebaseio.com")
            .build();
    FirebaseApp fireApp = FirebaseApp.initializeApp(options);

    StorageClient storageClient = StorageClient.getInstance(fireApp);
    InputStream testFile = new FileInputStream(file.getPath());
    String blobString = "NEW_FOLDER/" + "FILE_NAME.jpg";
    Blob blob = storageClient.bucket("xxxxxx.appspot.com")
                    .create(blobString, testFile , Bucket.BlobWriteOption.userProject("xxxxxxx"));
    blob.getStorage().createAcl(blob.getBlobId(), Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
    System.out.println(blob.getMediaLink());
} catch (Exception e){
    e.printStackTrace();
}
</code>```

Body:
You can public your file, and then the media link of the blob can access anywhere.

https://cloud.google.com/storage/docs/access-control/making-data-public

This is my solution.

try {
    FileInputStream serviceAccount =
            new FileInputStream("firebaseKey/serviceAccountKey.json");

    FirebaseOptions options = new FirebaseOptions.Builder()
            .setCredentials(GoogleCredentials.fromStream(serviceAccount))
            .setDatabaseUrl("https://xxxxx.firebaseio.com")
            .build();
    FirebaseApp fireApp = FirebaseApp.initializeApp(options);

    StorageClient storageClient = StorageClient.getInstance(fireApp);
    InputStream testFile = new FileInputStream(file.getPath());
    String blobString = "NEW_FOLDER/" + "FILE_NAME.jpg";
    Blob blob = storageClient.bucket("xxxxxx.appspot.com")
                    .create(blobString, testFile , Bucket.BlobWriteOption.userProject("xxxxxxx"));
    blob.getStorage().createAcl(blob.getBlobId(), Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER));
    System.out.println(blob.getMediaLink());
} catch (Exception e){
    e.printStackTrace();
}


问:
Running a regression of nested tibbles
I have a nested tibble which looks like the following:

```<code># A tibble: 2 x 3
  SCORE     score1_rank       score2_rank
  <chr>     <list>            <list>
1 scr_rnk_1 <tibble [54 x 5]> <tibble [54 x 5]>
2 scr_rnk_2 <tibble [46 x 5]> <tibble [46 x 5]>
</code>```

I want to construct regressions for each of the 4 tibbles. I can expand out the data by the following and run regressions individually:

```<code>    sub_data1 <- nested_df$score1_rank[[1]]
    sub_data2 <- nested_df$score1_rank[[2]]

#Reression 1
    sub_data1 <- sub_data1[!is.na(sub_data1$Y), ]
    lm(Y ~ X1 + X2, data = sub_data1)
#Regression 2
    sub_data2 <- sub_data2[!is.na(sub_data2$Y), ]
    lm(Y ~ X1 + X2, data = sub_data2)
</code>```

However I would like to try to do this for the whole nested tibble.

i.e. I am trying to map the regression over the tibbles.

Data:

```<code>nested_df <- structure(list(SCORE = c("scr_rnk_1", "scr_rnk_2"), score1_rank = list(
    structure(list(time = c("July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2016_June_2017", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2018_June_2019",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2008_June_2009", "July_2008_June_2009", "July_2008_June_2009",
    "July_2017_June_2018", "July_2017_June_2018", "July_2017_June_2018",
    "July_2009_June_2010", "July_2009_June_2010", "July_2009_June_2010",
    "July_2019_June_2020"), score1 = c(0.878385627705134, 0.829149886628575,
    0.873633400824437, 0.873191548477804, 0.833360020840671,
    0.821514348879447, 0.93893179382238, 0.902566094498171, 0.832521540654393,
    0.904546026086165, 0.944312545893212, 0.90721438246816, 0.925563285777056,
    0.837735581176652, 0.898314100598163, 0.881156591451732,
    0.927432166201199, 0.810462622843289, 0.924966424794594,
    0.54982486102469, 0.632637353015548, 0.93598101241571, 0.748712668464033,
    0.887355002120062, 0.00606213355201044, 0.66570681669867,
    0.809662797719473, 0.80883896141453, 0.410059100270974, 0.45097086832185,
    0.855118540355703, 0.73792861592456, 0.582170697766921, 0.910913548399676,
    0.909192361557635, 0.61000565934628, 0.541242004262667, 0.847840909074889,
    0.838844407944549, 0.638014235742945, 0.948686837455938,
    0.569343264654849, 0.942357992461572, 0.956483422999484,
    0.716630105733463, 0.757677906984471, 0.840660131450953,
    0.944095864840561, 0.74291963665858, 0.944596570938035, 0.916460742106468,
    0.90890022256817, 0.895889262055934, 0.886515265060623),
        Y = c(-0.0392143242061138, 0.00517332553863525, 0.0475661605596542,
        -0.0140374358743429, -0.0235463473945856, 0.0460794232785702,
        0.0647838711738586, -0.0257589742541313, 0.0539961569011211,
        -0.170428335666656, 0.0925306528806686, 0.11557175219059,
        0.0496749319136143, -0.11405622959137, 0.0666666403412819,
        -0.0189777128398418, -0.00572755141183734, 0.0277173686772585,
        -0.0241545476019383, 0.0328245237469673, 0.223529428243637,
        0.0253662765026092, 0.0394621938467026, 0.0815821811556816,
        0.0597507022321224, -0.0132956989109516, 0.0609685145318508,
        0.0393742695450783, -0.00168346334248781, -0.000859459512867033,
        0.0345749147236347, NA, 0.0327170714735985, 0.144188165664673,
        0.0415891073644161, 0.0028026478830725, -0.0840985849499702,
        0.00914959330111742, 0.0197730101644993, -0.0929021015763283,
        0.0382972247898579, NA, 0.015947800129652, 0.0136986169964075,
        -0.139593943953514, 0.113736107945442, 0.0216289088129997,
        -0.209788918495178, 0.00545153254643083, 0.126438871026039,
        0.0538020096719265, 0.0774460881948471, 0.0651820451021194,
        NA), X1 = c(0.14, 5.52, 0.14, -3.29, 1.82, -1.17, 1.93,
        2.7, -1.44, -1.74, 5.91, -2.05, 2.72, 1.86, 2.28, 1.39,
        3.49, 4.47, -1.52, 4.47, 9.85, -0.68, -2.52, 5.46, -0.43,
        -0.43, 2.3, 0.56, -8.19, 0.87, 2.53, NA, 7.32, 6.92,
        6.92, -6.18, -3.91, -6.32, 0.45, -8.88, -0.44, NA, -0.44,
        -1.11, -8.54, 7.28, -6.53, 1.93, 1.93, 1.93, 6.24, 8.62,
        6.24, NA), X2 = c(-0.5, 2.22, -0.5, 2.93, -0.17, 1.42,
        -0.53, 0.78, 1.67, -0.05, -0.39, -1.08, 0.46, 0.37, -0.62,
        0.17, 0.18, -0.69, -0.42, -0.69, 1.48, 1.32, 0.21, 0.17,
        -0.76, -0.76, 1.19, -0.66, -2.51, -0.38, -2.56, NA, -2.36,
        1.33, 1.33, 1.16, -0.25, -2.16, 0.04, -0.53, -0.46, NA,
        -0.46, 0.23, 2.23, -1.27, -0.57, -0.61, -0.61, -0.61,
        -0.19, -1.37, -0.19, NA)), class = c("tbl_df", "tbl",
    "data.frame"), row.names = c(NA, -54L)), structure(list(time = c("July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2008_June_2009", "July_2008_June_2009",
    "July_2008_June_2009", "July_2017_June_2018", "July_2017_June_2018",
    "July_2017_June_2018", "July_2009_June_2010", "July_2009_June_2010"
    ), score1 = c(0.910630243821458, 0.887211746784698, 0.920092482844549,
    0.94450683954903, 0.886972163304589, 0.991052738161695, 0.981619567238222,
    0.977490375052585, 0.961036277360393, 0.985523653404714,
    0.948091565971217, 0.959812930740014, 0.936269500157121,
    0.948541666157695, 0.939675946745415, 0.995146212267317,
    0.944554298851532, 0.982930629437269, 0.963858517802992,
    0.92872841572452, 0.968099127001545, 0.945198156814004, 0.892947157198215,
    0.906930889247629, 0.957790348580216, 0.928122479697648,
    0.953267485671018, 0.963714595673124, 0.976914001156382,
    0.973623547932495, 0.962870831719229, 0.978333062077069,
    0.958765402277667, 0.959032891808224, 0.972965648015492,
    0.982760065777063, 0.957170836537733, 0.961880715763936,
    0.975885654717621, 0.924673632533321, 0.925318007280836,
    0.987246011368269, 0.98249943727474, 0.980272445641619, 0.978206000922261,
    0.929807352926533), Y = c(0.0737265646457672, 0.0278251487761736,
    0.201131358742714, 0.125700861215591, 0.0777644738554955,
    -0.0130416098982096, -0.0990565568208694, 0.0333333089947701,
    -0.031569954007864, 0.0422280319035053, -0.0111790159717202,
    -0.278726726770401, -0.139534845948219, -0.0800638571381569,
    0.23757965862751, -0.0746169164776802, 0.0465963147580624,
    0.0337920561432838, -0.0111621227115393, -0.0133928591385484,
    0.0778210312128067, -0.0821536555886269, 0.00643268134444952,
    NA, 0.152694001793861, 0.0409262739121914, 0.0360006913542747,
    -0.0233012177050114, -0.211209982633591, -0.11425743252039,
    -0.169167995452881, 0.0282719731330872, 0.161968618631363,
    -0.0525752492249012, 0.0127659253776074, -0.0466842725872993,
    -0.115001328289509, -0.00946897640824318, 0.114568591117859,
    0.2675521671772, -0.0196253582835197, 0.123595483601093,
    NA, 0.12380950897932, -0.0350765138864517, -0.16666667163372
    ), X1 = c(2.01, 0.14, 5.06, 5.52, 1.82, 2.7, -3.09, 1.65,
    0.5, 1.93, -1.17, 2.25, 1.86, -1.88, 9.85, -3.9, 3.94, 7.6,
    4.47, -2.52, 1.32, 2.78, 0.09, NA, 0.88, 2.53, 2.53, 7.32,
    1.13, -6.18, -6.32, -0.3, 7.32, -6.18, 4.93, -1.11, -9.2,
    -7.52, 11.42, 9.96, -0.26, 1.93, NA, 0.49, 8.62, 0.49), X2 = c(2.18,
    -0.5, -1.03, 2.22, -0.17, 0.78, -2.72, -2.19, 1.22, -0.53,
    1.42, -0.51, 0.37, -1.55, 1.48, -0.22, -0.02, 2.08, -0.69,
    0.21, -1.2, -0.32, 0.35, NA, -0.57, -2.56, -2.56, -2.36,
    -3.09, 1.16, -2.16, 1.75, -2.36, 1.16, -0.77, 0.23, -1.33,
    -0.63, 1.64, 1.63, 2.85, -0.61, NA, 1.88, -1.37, 3.81)), class = c("tbl_df",
    "tbl", "data.frame"), row.names = c(NA, -46L))), score2_rank = list(
    structure(list(time = c("July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2016_June_2017", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2018_June_2019",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2008_June_2009", "July_2008_June_2009", "July_2008_June_2009",
    "July_2017_June_2018", "July_2017_June_2018", "July_2017_June_2018",
    "July_2009_June_2010", "July_2009_June_2010", "July_2009_June_2010",
    "July_2019_June_2020"), score2 = c(0.573384803196917, 0.95560973004494,
    0.936151601862601, 0.940067094946625, 0.790149367637373,
    0.885023225824309, 0.956490411723667, 0.918534374861312,
    0.9660240615445, 0.961407533200788, 0.794743982673356, 0.926614681101157,
    0.924390324452674, 0.838697174839086, 0.548480558835933,
    0.928419789574611, 0.942229561212187, 0.808215644539813,
    0.89946853678008, 0.931010276978734, 0.780385177969094, 0.945728847589739,
    0.958939314931932, 0.101395325662518, 0.0547541695358364,
    0.757995973046388, 0.815555744982054, 0.947726570770333,
    0.589921893700343, 0.924114006154793, 0.164071857964122,
    0.946752193254218, 0.801515206601873, 0.709037475517904,
    0.730962189352849, 0.872901083488831, 0.958819700206169,
    0.951829945538551, 0.924000702901887, 0.963439907199707,
    0.94482417669742, 0.817381450384857, 0.977233364779766, 0.881676744287434,
    0.820839678297149, 0.449214983785051, 0.536396658733052,
    0.756705578897905, 0.904306523171427, 0.947974271863387,
    0.947487349720247, 0.95821125132286, 0.890792036806817, 0.983129670844182
    ), Y = c(-0.0392143242061138, 0.0475661605596542, 0.0278251487761736,
    -0.0235463473945856, 0.0777644738554955, 0.0333333089947701,
    0.0460794232785702, 0.0647838711738586, -0.0257589742541313,
    -0.170428335666656, 0.0925306528806686, 0.11557175219059,
    -0.278726726770401, -0.139534845948219, -0.11405622959137,
    0.0666666403412819, -0.00572755141183734, 0.0277173686772585,
    0.23757965862751, -0.0241545476019383, 0.0465963147580624,
    0.0253662765026092, 0.0394621938467026, 0.00643268134444952,
    0.0597507022321224, -0.0132956989109516, 0.0609685145318508,
    0.0393742695450783, -0.00168346334248781, 0.0345749147236347,
    NA, 0.0360006913542747, 0.0327170714735985, -0.0233012177050114,
    0.0028026478830725, -0.0840985849499702, 0.161968618631363,
    0.00914959330111742, 0.0197730101644993, -0.0466842725872993,
    -0.0929021015763283, 0.0382972247898579, 0.015947800129652,
    0.0136986169964075, -0.139593943953514, 0.113736107945442,
    0.0216289088129997, -0.209788918495178, 0.00545153254643083,
    0.12380950897932, 0.0538020096719265, 0.0774460881948471,
    -0.16666667163372, NA), X1 = c(0.14, 0.14, 0.14, 1.82, 1.82,
    1.65, -1.17, 1.93, 2.7, -1.74, 5.91, -2.05, 2.25, 1.86, 1.86,
    2.28, 3.49, 4.47, 9.85, -1.52, 3.94, -0.68, -2.52, 0.09,
    -0.43, -0.43, 2.3, 0.56, -8.19, 2.53, NA, 2.53, 7.32, 7.32,
    -6.18, -3.91, 7.32, -6.32, 0.45, -1.11, -8.88, -0.44, -0.44,
    -1.11, -8.54, 7.28, -6.53, 1.93, 1.93, 0.49, 6.24, 8.62,
    0.49, NA), X2 = c(-0.5, -0.5, -0.5, -0.17, -0.17, -2.19,
    1.42, -0.53, 0.78, -0.05, -0.39, -1.08, -0.51, 0.37, 0.37,
    -0.62, 0.18, -0.69, 1.48, -0.42, -0.02, 1.32, 0.21, 0.35,
    -0.76, -0.76, 1.19, -0.66, -2.51, -2.56, NA, -2.56, -2.36,
    -2.36, 1.16, -0.25, -2.36, -2.16, 0.04, 0.23, -0.53, -0.46,
    -0.46, 0.23, 2.23, -1.27, -0.57, -0.61, -0.61, 1.88, -0.19,
    -1.37, 3.81, NA)), class = c("tbl_df", "tbl", "data.frame"
    ), row.names = c(NA, -54L)), structure(list(time = c("July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2008_June_2009", "July_2008_June_2009",
    "July_2008_June_2009", "July_2017_June_2018", "July_2017_June_2018",
    "July_2017_June_2018", "July_2009_June_2010", "July_2009_June_2010"
    ), score2 = c(0.977777238266838, 0.994161535248162, 0.973746623206586,
    0.959737686390477, 0.960771840809366, 0.973573416279972,
    0.971473417619078, 0.994362749200424, 0.998832204612857,
    0.969953961861552, 0.974595202023975, 0.990460167618893,
    0.977938934839813, 0.933720130788891, 0.997555980989323,
    0.983534940461115, 0.961638641355128, 0.98302503175898, 0.955924205281728,
    0.960588460795172, 0.980272014323638, 0.99319344527155, 0.990396166187007,
    0.96928405964874, 0.958824291095735, 0.94735915935544, 0.956799713877734,
    0.974313477760366, 0.959422857050319, 0.970981339110875,
    0.986720965210939, 0.988119219123952, 0.987757971968369,
    0.998331238333002, 0.985606980938901, 0.996309951852897,
    0.978123949182993, 0.980322946112709, 0.870995840583191,
    0.99620925825849, 0.952471805464684, 0.967521340577839, 0.997358168481063,
    0.954089152398106, 0.99961257213601, 0.971649355774121),
        Y = c(0.00517332553863525, 0.0737265646457672, 0.201131358742714,
        -0.0140374358743429, 0.125700861215591, -0.0130416098982096,
        -0.0990565568208694, 0.0539961569011211, -0.031569954007864,
        0.0422280319035053, -0.0111790159717202, 0.0496749319136143,
        -0.0189777128398418, -0.0800638571381569, -0.0746169164776802,
        0.0328245237469673, 0.223529428243637, 0.0337920561432838,
        -0.0111621227115393, -0.0133928591385484, 0.0815821811556816,
        0.0778210312128067, -0.0821536555886269, NA, -0.000859459512867033,
        0.152694001793861, 0.0409262739121914, -0.211209982633591,
        0.144188165664673, 0.0415891073644161, -0.11425743252039,
        -0.169167995452881, 0.0282719731330872, -0.0525752492249012,
        0.0127659253776074, -0.115001328289509, -0.00946897640824318,
        NA, 0.114568591117859, 0.2675521671772, -0.0196253582835197,
        0.123595483601093, NA, 0.126438871026039, -0.0350765138864517,
        0.0651820451021194), X1 = c(5.52, 2.01, 5.06, -3.29,
        5.52, 2.7, -3.09, -1.44, 0.5, 1.93, -1.17, 2.72, 1.39,
        -1.88, -3.9, 4.47, 9.85, 7.6, 4.47, -2.52, 5.46, 1.32,
        2.78, NA, 0.87, 0.88, 2.53, 1.13, 6.92, 6.92, -6.18,
        -6.32, -0.3, -6.18, 4.93, -9.2, -7.52, NA, 11.42, 9.96,
        -0.26, 1.93, NA, 1.93, 8.62, 6.24), X2 = c(2.22, 2.18,
        -1.03, 2.93, 2.22, 0.78, -2.72, 1.67, 1.22, -0.53, 1.42,
        0.46, 0.17, -1.55, -0.22, -0.69, 1.48, 2.08, -0.69, 0.21,
        0.17, -1.2, -0.32, NA, -0.38, -0.57, -2.56, -3.09, 1.33,
        1.33, 1.16, -2.16, 1.75, 1.16, -0.77, -1.33, -0.63, NA,
        1.64, 1.63, 2.85, -0.61, NA, -0.61, -1.37, -0.19)), class = c("tbl_df",
    "tbl", "data.frame"), row.names = c(NA, -46L)))), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

答:
Another option would be to use the tidy model approach using tidyverse and broom.

```<code>library(tidyverse)
library(broom)

nested_df %>%
  gather(key, data, -SCORE) %>%
  mutate(tidymod = map(data, ~lm(Y ~ X1 + X2, data = .) %>% tidy)) %>%
  unnest(tidymod)

# A tibble: 12 x 7
   SCORE     key         term        estimate std.error statistic   p.value
   <chr>     <chr>       <chr>          <dbl>     <dbl>     <dbl>     <dbl>
 1 scr_rnk_1 score1_rank (Intercept)  0.0105    0.00962     1.09  0.281
 2 scr_rnk_1 score1_rank X1           0.00849   0.00212     4.00  0.000219
 3 scr_rnk_1 score1_rank X2          -0.00208   0.00808    -0.258 0.798
 4 scr_rnk_2 score1_rank (Intercept) -0.0131    0.0155     -0.848 0.402
 5 scr_rnk_2 score1_rank X1           0.0131    0.00320     4.10  0.000192
 6 scr_rnk_2 score1_rank X2           0.00862   0.00894     0.965 0.340
 7 scr_rnk_1 score2_rank (Intercept) -0.00370   0.0125     -0.296 0.769
 8 scr_rnk_1 score2_rank X1           0.00749   0.00291     2.57  0.0132
 9 scr_rnk_1 score2_rank X2          -0.00968   0.00961    -1.01  0.319
10 scr_rnk_2 score2_rank (Intercept) -0.00202   0.0121     -0.166 0.869
11 scr_rnk_2 score2_rank X1           0.0121    0.00242     4.99  0.0000121
12 scr_rnk_2 score2_rank X2           0.0147    0.00774     1.91  0.0640
</code>```

Title: Running a regression of nested tibbles

Body:
I have a nested tibble which looks like the following:

# A tibble: 2 x 3
  SCORE     score1_rank       score2_rank
  <chr>     <list>            <list>
1 scr_rnk_1 <tibble [54 x 5]> <tibble [54 x 5]>
2 scr_rnk_2 <tibble [46 x 5]> <tibble [46 x 5]>

I want to construct regressions for each of the 4 tibbles. I can expand out the data by the following and run regressions individually:

    sub_data1 <- nested_df$score1_rank[[1]]
    sub_data2 <- nested_df$score1_rank[[2]]

#Reression 1
    sub_data1 <- sub_data1[!is.na(sub_data1$Y), ]
    lm(Y ~ X1 + X2, data = sub_data1)
#Regression 2
    sub_data2 <- sub_data2[!is.na(sub_data2$Y), ]
    lm(Y ~ X1 + X2, data = sub_data2)

However I would like to try to do this for the whole nested tibble.

i.e. I am trying to map the regression over the tibbles.

Data:

nested_df <- structure(list(SCORE = c("scr_rnk_1", "scr_rnk_2"), score1_rank = list(
    structure(list(time = c("July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2016_June_2017", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2018_June_2019",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2008_June_2009", "July_2008_June_2009", "July_2008_June_2009",
    "July_2017_June_2018", "July_2017_June_2018", "July_2017_June_2018",
    "July_2009_June_2010", "July_2009_June_2010", "July_2009_June_2010",
    "July_2019_June_2020"), score1 = c(0.878385627705134, 0.829149886628575,
    0.873633400824437, 0.873191548477804, 0.833360020840671,
    0.821514348879447, 0.93893179382238, 0.902566094498171, 0.832521540654393,
    0.904546026086165, 0.944312545893212, 0.90721438246816, 0.925563285777056,
    0.837735581176652, 0.898314100598163, 0.881156591451732,
    0.927432166201199, 0.810462622843289, 0.924966424794594,
    0.54982486102469, 0.632637353015548, 0.93598101241571, 0.748712668464033,
    0.887355002120062, 0.00606213355201044, 0.66570681669867,
    0.809662797719473, 0.80883896141453, 0.410059100270974, 0.45097086832185,
    0.855118540355703, 0.73792861592456, 0.582170697766921, 0.910913548399676,
    0.909192361557635, 0.61000565934628, 0.541242004262667, 0.847840909074889,
    0.838844407944549, 0.638014235742945, 0.948686837455938,
    0.569343264654849, 0.942357992461572, 0.956483422999484,
    0.716630105733463, 0.757677906984471, 0.840660131450953,
    0.944095864840561, 0.74291963665858, 0.944596570938035, 0.916460742106468,
    0.90890022256817, 0.895889262055934, 0.886515265060623),
        Y = c(-0.0392143242061138, 0.00517332553863525, 0.0475661605596542,
        -0.0140374358743429, -0.0235463473945856, 0.0460794232785702,
        0.0647838711738586, -0.0257589742541313, 0.0539961569011211,
        -0.170428335666656, 0.0925306528806686, 0.11557175219059,
        0.0496749319136143, -0.11405622959137, 0.0666666403412819,
        -0.0189777128398418, -0.00572755141183734, 0.0277173686772585,
        -0.0241545476019383, 0.0328245237469673, 0.223529428243637,
        0.0253662765026092, 0.0394621938467026, 0.0815821811556816,
        0.0597507022321224, -0.0132956989109516, 0.0609685145318508,
        0.0393742695450783, -0.00168346334248781, -0.000859459512867033,
        0.0345749147236347, NA, 0.0327170714735985, 0.144188165664673,
        0.0415891073644161, 0.0028026478830725, -0.0840985849499702,
        0.00914959330111742, 0.0197730101644993, -0.0929021015763283,
        0.0382972247898579, NA, 0.015947800129652, 0.0136986169964075,
        -0.139593943953514, 0.113736107945442, 0.0216289088129997,
        -0.209788918495178, 0.00545153254643083, 0.126438871026039,
        0.0538020096719265, 0.0774460881948471, 0.0651820451021194,
        NA), X1 = c(0.14, 5.52, 0.14, -3.29, 1.82, -1.17, 1.93,
        2.7, -1.44, -1.74, 5.91, -2.05, 2.72, 1.86, 2.28, 1.39,
        3.49, 4.47, -1.52, 4.47, 9.85, -0.68, -2.52, 5.46, -0.43,
        -0.43, 2.3, 0.56, -8.19, 0.87, 2.53, NA, 7.32, 6.92,
        6.92, -6.18, -3.91, -6.32, 0.45, -8.88, -0.44, NA, -0.44,
        -1.11, -8.54, 7.28, -6.53, 1.93, 1.93, 1.93, 6.24, 8.62,
        6.24, NA), X2 = c(-0.5, 2.22, -0.5, 2.93, -0.17, 1.42,
        -0.53, 0.78, 1.67, -0.05, -0.39, -1.08, 0.46, 0.37, -0.62,
        0.17, 0.18, -0.69, -0.42, -0.69, 1.48, 1.32, 0.21, 0.17,
        -0.76, -0.76, 1.19, -0.66, -2.51, -0.38, -2.56, NA, -2.36,
        1.33, 1.33, 1.16, -0.25, -2.16, 0.04, -0.53, -0.46, NA,
        -0.46, 0.23, 2.23, -1.27, -0.57, -0.61, -0.61, -0.61,
        -0.19, -1.37, -0.19, NA)), class = c("tbl_df", "tbl",
    "data.frame"), row.names = c(NA, -54L)), structure(list(time = c("July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2008_June_2009", "July_2008_June_2009",
    "July_2008_June_2009", "July_2017_June_2018", "July_2017_June_2018",
    "July_2017_June_2018", "July_2009_June_2010", "July_2009_June_2010"
    ), score1 = c(0.910630243821458, 0.887211746784698, 0.920092482844549,
    0.94450683954903, 0.886972163304589, 0.991052738161695, 0.981619567238222,
    0.977490375052585, 0.961036277360393, 0.985523653404714,
    0.948091565971217, 0.959812930740014, 0.936269500157121,
    0.948541666157695, 0.939675946745415, 0.995146212267317,
    0.944554298851532, 0.982930629437269, 0.963858517802992,
    0.92872841572452, 0.968099127001545, 0.945198156814004, 0.892947157198215,
    0.906930889247629, 0.957790348580216, 0.928122479697648,
    0.953267485671018, 0.963714595673124, 0.976914001156382,
    0.973623547932495, 0.962870831719229, 0.978333062077069,
    0.958765402277667, 0.959032891808224, 0.972965648015492,
    0.982760065777063, 0.957170836537733, 0.961880715763936,
    0.975885654717621, 0.924673632533321, 0.925318007280836,
    0.987246011368269, 0.98249943727474, 0.980272445641619, 0.978206000922261,
    0.929807352926533), Y = c(0.0737265646457672, 0.0278251487761736,
    0.201131358742714, 0.125700861215591, 0.0777644738554955,
    -0.0130416098982096, -0.0990565568208694, 0.0333333089947701,
    -0.031569954007864, 0.0422280319035053, -0.0111790159717202,
    -0.278726726770401, -0.139534845948219, -0.0800638571381569,
    0.23757965862751, -0.0746169164776802, 0.0465963147580624,
    0.0337920561432838, -0.0111621227115393, -0.0133928591385484,
    0.0778210312128067, -0.0821536555886269, 0.00643268134444952,
    NA, 0.152694001793861, 0.0409262739121914, 0.0360006913542747,
    -0.0233012177050114, -0.211209982633591, -0.11425743252039,
    -0.169167995452881, 0.0282719731330872, 0.161968618631363,
    -0.0525752492249012, 0.0127659253776074, -0.0466842725872993,
    -0.115001328289509, -0.00946897640824318, 0.114568591117859,
    0.2675521671772, -0.0196253582835197, 0.123595483601093,
    NA, 0.12380950897932, -0.0350765138864517, -0.16666667163372
    ), X1 = c(2.01, 0.14, 5.06, 5.52, 1.82, 2.7, -3.09, 1.65,
    0.5, 1.93, -1.17, 2.25, 1.86, -1.88, 9.85, -3.9, 3.94, 7.6,
    4.47, -2.52, 1.32, 2.78, 0.09, NA, 0.88, 2.53, 2.53, 7.32,
    1.13, -6.18, -6.32, -0.3, 7.32, -6.18, 4.93, -1.11, -9.2,
    -7.52, 11.42, 9.96, -0.26, 1.93, NA, 0.49, 8.62, 0.49), X2 = c(2.18,
    -0.5, -1.03, 2.22, -0.17, 0.78, -2.72, -2.19, 1.22, -0.53,
    1.42, -0.51, 0.37, -1.55, 1.48, -0.22, -0.02, 2.08, -0.69,
    0.21, -1.2, -0.32, 0.35, NA, -0.57, -2.56, -2.56, -2.36,
    -3.09, 1.16, -2.16, 1.75, -2.36, 1.16, -0.77, 0.23, -1.33,
    -0.63, 1.64, 1.63, 2.85, -0.61, NA, 1.88, -1.37, 3.81)), class = c("tbl_df",
    "tbl", "data.frame"), row.names = c(NA, -46L))), score2_rank = list(
    structure(list(time = c("July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2016_June_2017", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2018_June_2019",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2008_June_2009", "July_2008_June_2009", "July_2008_June_2009",
    "July_2017_June_2018", "July_2017_June_2018", "July_2017_June_2018",
    "July_2009_June_2010", "July_2009_June_2010", "July_2009_June_2010",
    "July_2019_June_2020"), score2 = c(0.573384803196917, 0.95560973004494,
    0.936151601862601, 0.940067094946625, 0.790149367637373,
    0.885023225824309, 0.956490411723667, 0.918534374861312,
    0.9660240615445, 0.961407533200788, 0.794743982673356, 0.926614681101157,
    0.924390324452674, 0.838697174839086, 0.548480558835933,
    0.928419789574611, 0.942229561212187, 0.808215644539813,
    0.89946853678008, 0.931010276978734, 0.780385177969094, 0.945728847589739,
    0.958939314931932, 0.101395325662518, 0.0547541695358364,
    0.757995973046388, 0.815555744982054, 0.947726570770333,
    0.589921893700343, 0.924114006154793, 0.164071857964122,
    0.946752193254218, 0.801515206601873, 0.709037475517904,
    0.730962189352849, 0.872901083488831, 0.958819700206169,
    0.951829945538551, 0.924000702901887, 0.963439907199707,
    0.94482417669742, 0.817381450384857, 0.977233364779766, 0.881676744287434,
    0.820839678297149, 0.449214983785051, 0.536396658733052,
    0.756705578897905, 0.904306523171427, 0.947974271863387,
    0.947487349720247, 0.95821125132286, 0.890792036806817, 0.983129670844182
    ), Y = c(-0.0392143242061138, 0.0475661605596542, 0.0278251487761736,
    -0.0235463473945856, 0.0777644738554955, 0.0333333089947701,
    0.0460794232785702, 0.0647838711738586, -0.0257589742541313,
    -0.170428335666656, 0.0925306528806686, 0.11557175219059,
    -0.278726726770401, -0.139534845948219, -0.11405622959137,
    0.0666666403412819, -0.00572755141183734, 0.0277173686772585,
    0.23757965862751, -0.0241545476019383, 0.0465963147580624,
    0.0253662765026092, 0.0394621938467026, 0.00643268134444952,
    0.0597507022321224, -0.0132956989109516, 0.0609685145318508,
    0.0393742695450783, -0.00168346334248781, 0.0345749147236347,
    NA, 0.0360006913542747, 0.0327170714735985, -0.0233012177050114,
    0.0028026478830725, -0.0840985849499702, 0.161968618631363,
    0.00914959330111742, 0.0197730101644993, -0.0466842725872993,
    -0.0929021015763283, 0.0382972247898579, 0.015947800129652,
    0.0136986169964075, -0.139593943953514, 0.113736107945442,
    0.0216289088129997, -0.209788918495178, 0.00545153254643083,
    0.12380950897932, 0.0538020096719265, 0.0774460881948471,
    -0.16666667163372, NA), X1 = c(0.14, 0.14, 0.14, 1.82, 1.82,
    1.65, -1.17, 1.93, 2.7, -1.74, 5.91, -2.05, 2.25, 1.86, 1.86,
    2.28, 3.49, 4.47, 9.85, -1.52, 3.94, -0.68, -2.52, 0.09,
    -0.43, -0.43, 2.3, 0.56, -8.19, 2.53, NA, 2.53, 7.32, 7.32,
    -6.18, -3.91, 7.32, -6.32, 0.45, -1.11, -8.88, -0.44, -0.44,
    -1.11, -8.54, 7.28, -6.53, 1.93, 1.93, 0.49, 6.24, 8.62,
    0.49, NA), X2 = c(-0.5, -0.5, -0.5, -0.17, -0.17, -2.19,
    1.42, -0.53, 0.78, -0.05, -0.39, -1.08, -0.51, 0.37, 0.37,
    -0.62, 0.18, -0.69, 1.48, -0.42, -0.02, 1.32, 0.21, 0.35,
    -0.76, -0.76, 1.19, -0.66, -2.51, -2.56, NA, -2.56, -2.36,
    -2.36, 1.16, -0.25, -2.36, -2.16, 0.04, 0.23, -0.53, -0.46,
    -0.46, 0.23, 2.23, -1.27, -0.57, -0.61, -0.61, 1.88, -0.19,
    -1.37, 3.81, NA)), class = c("tbl_df", "tbl", "data.frame"
    ), row.names = c(NA, -54L)), structure(list(time = c("July_2013_June_2014",
    "July_2013_June_2014", "July_2013_June_2014", "July_2013_June_2014",
    "July_2013_June_2014", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2014_June_2015", "July_2014_June_2015",
    "July_2014_June_2015", "July_2016_June_2017", "July_2016_June_2017",
    "July_2016_June_2017", "July_2010_June_2011", "July_2010_June_2011",
    "July_2010_June_2011", "July_2010_June_2011", "July_2010_June_2011",
    "July_2012_June_2013", "July_2012_June_2013", "July_2012_June_2013",
    "July_2012_June_2013", "July_2012_June_2013", "July_2018_June_2019",
    "July_2018_June_2019", "July_2018_June_2019", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2015_June_2016", "July_2015_June_2016", "July_2015_June_2016",
    "July_2011_June_2012", "July_2011_June_2012", "July_2011_June_2012",
    "July_2011_June_2012", "July_2008_June_2009", "July_2008_June_2009",
    "July_2008_June_2009", "July_2017_June_2018", "July_2017_June_2018",
    "July_2017_June_2018", "July_2009_June_2010", "July_2009_June_2010"
    ), score2 = c(0.977777238266838, 0.994161535248162, 0.973746623206586,
    0.959737686390477, 0.960771840809366, 0.973573416279972,
    0.971473417619078, 0.994362749200424, 0.998832204612857,
    0.969953961861552, 0.974595202023975, 0.990460167618893,
    0.977938934839813, 0.933720130788891, 0.997555980989323,
    0.983534940461115, 0.961638641355128, 0.98302503175898, 0.955924205281728,
    0.960588460795172, 0.980272014323638, 0.99319344527155, 0.990396166187007,
    0.96928405964874, 0.958824291095735, 0.94735915935544, 0.956799713877734,
    0.974313477760366, 0.959422857050319, 0.970981339110875,
    0.986720965210939, 0.988119219123952, 0.987757971968369,
    0.998331238333002, 0.985606980938901, 0.996309951852897,
    0.978123949182993, 0.980322946112709, 0.870995840583191,
    0.99620925825849, 0.952471805464684, 0.967521340577839, 0.997358168481063,
    0.954089152398106, 0.99961257213601, 0.971649355774121),
        Y = c(0.00517332553863525, 0.0737265646457672, 0.201131358742714,
        -0.0140374358743429, 0.125700861215591, -0.0130416098982096,
        -0.0990565568208694, 0.0539961569011211, -0.031569954007864,
        0.0422280319035053, -0.0111790159717202, 0.0496749319136143,
        -0.0189777128398418, -0.0800638571381569, -0.0746169164776802,
        0.0328245237469673, 0.223529428243637, 0.0337920561432838,
        -0.0111621227115393, -0.0133928591385484, 0.0815821811556816,
        0.0778210312128067, -0.0821536555886269, NA, -0.000859459512867033,
        0.152694001793861, 0.0409262739121914, -0.211209982633591,
        0.144188165664673, 0.0415891073644161, -0.11425743252039,
        -0.169167995452881, 0.0282719731330872, -0.0525752492249012,
        0.0127659253776074, -0.115001328289509, -0.00946897640824318,
        NA, 0.114568591117859, 0.2675521671772, -0.0196253582835197,
        0.123595483601093, NA, 0.126438871026039, -0.0350765138864517,
        0.0651820451021194), X1 = c(5.52, 2.01, 5.06, -3.29,
        5.52, 2.7, -3.09, -1.44, 0.5, 1.93, -1.17, 2.72, 1.39,
        -1.88, -3.9, 4.47, 9.85, 7.6, 4.47, -2.52, 5.46, 1.32,
        2.78, NA, 0.87, 0.88, 2.53, 1.13, 6.92, 6.92, -6.18,
        -6.32, -0.3, -6.18, 4.93, -9.2, -7.52, NA, 11.42, 9.96,
        -0.26, 1.93, NA, 1.93, 8.62, 6.24), X2 = c(2.22, 2.18,
        -1.03, 2.93, 2.22, 0.78, -2.72, 1.67, 1.22, -0.53, 1.42,
        0.46, 0.17, -1.55, -0.22, -0.69, 1.48, 2.08, -0.69, 0.21,
        0.17, -1.2, -0.32, NA, -0.38, -0.57, -2.56, -3.09, 1.33,
        1.33, 1.16, -2.16, 1.75, 1.16, -0.77, -1.33, -0.63, NA,
        1.64, 1.63, 2.85, -0.61, NA, -0.61, -1.37, -0.19)), class = c("tbl_df",
    "tbl", "data.frame"), row.names = c(NA, -46L)))), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"))

Body:
Another option would be to use the tidy model approach using tidyverse and broom.

library(tidyverse)
library(broom)

nested_df %>%
  gather(key, data, -SCORE) %>%
  mutate(tidymod = map(data, ~lm(Y ~ X1 + X2, data = .) %>% tidy)) %>%
  unnest(tidymod)

# A tibble: 12 x 7
   SCORE     key         term        estimate std.error statistic   p.value
   <chr>     <chr>       <chr>          <dbl>     <dbl>     <dbl>     <dbl>
 1 scr_rnk_1 score1_rank (Intercept)  0.0105    0.00962     1.09  0.281
 2 scr_rnk_1 score1_rank X1           0.00849   0.00212     4.00  0.000219
 3 scr_rnk_1 score1_rank X2          -0.00208   0.00808    -0.258 0.798
 4 scr_rnk_2 score1_rank (Intercept) -0.0131    0.0155     -0.848 0.402
 5 scr_rnk_2 score1_rank X1           0.0131    0.00320     4.10  0.000192
 6 scr_rnk_2 score1_rank X2           0.00862   0.00894     0.965 0.340
 7 scr_rnk_1 score2_rank (Intercept) -0.00370   0.0125     -0.296 0.769
 8 scr_rnk_1 score2_rank X1           0.00749   0.00291     2.57  0.0132
 9 scr_rnk_1 score2_rank X2          -0.00968   0.00961    -1.01  0.319
10 scr_rnk_2 score2_rank (Intercept) -0.00202   0.0121     -0.166 0.869
11 scr_rnk_2 score2_rank X1           0.0121    0.00242     4.99  0.0000121
12 scr_rnk_2 score2_rank X2           0.0147    0.00774     1.91  0.0640


问:
Check if property is "T" using reflection
I'm working on a project where I need to "translate" a .net class to typescript, bug I'm struggling with the following problem:

I'm trying to know at runtime if the property AnotherClass.property1.genericProperty is type T, but I'm always getting MyClass as type, what is the proper way to check it?

```<code>class MyGenericClass<T>
{
    public T genericProperty { get; set; }
}

class AnotherClass
{
    public MyGenericClass<MyClass> property1 { get; set; }
    public MyClass regularProperty { get; set; }
}
</code>```

Typescript that I expect:

```<code>interface MyGenericClass<T> {
    genericProperty: T;
}
</code>```

What I'm getting at the moment:

```<code>interface MyGenericClass<T> {
    genericProperty: MyClass;
}
</code>```

答:
Following @Mark Gravell comment I was able to solve my problem, what I did:

Used

```<code>AnotherClass.property1.PropertyType.GetGenericTypeDefinition().GetProperty("genericProperty").PropertyType.Name
</code>```

instead of

```<code>AnotherClass.property1.PropertyType.GetProperty("genericProperty").PropertyType.Name
</code>```

And now I'm getting the desired results.

Body:
I'm working on a project where I need to "translate" a .net class to typescript, bug I'm struggling with the following problem:

I'm trying to know at runtime if the property AnotherClass.property1.genericProperty is type T, but I'm always getting MyClass as type, what is the proper way to check it?

class MyGenericClass<T>
{
    public T genericProperty { get; set; }
}

class AnotherClass
{
    public MyGenericClass<MyClass> property1 { get; set; }
    public MyClass regularProperty { get; set; }
}

Typescript that I expect:

interface MyGenericClass<T> {
    genericProperty: T;
}

What I'm getting at the moment:

interface MyGenericClass<T> {
    genericProperty: MyClass;
}

Body:
Following @Mark Gravell comment I was able to solve my problem, what I did:

Used

AnotherClass.property1.PropertyType.GetGenericTypeDefinition().GetProperty("genericProperty").PropertyType.Name

instead of

AnotherClass.property1.PropertyType.GetProperty("genericProperty").PropertyType.Name

And now I'm getting the desired results.


答:
Without using any packages first convert columns 2 and 3 to numeric and then use ave and rank with the indicated ties method.  Finally order the result.

Note that the output shown in the question does not correspond to the input, e.g. there are three Mar rows in the output but only two such rows in the input so this will correspond to the input but will not be identical to the output shown.

```<code>Sampledata2 <- transform(Sampledata,
  Disch = as.numeric(as.character(Disch)),
  Months = as.numeric(format(Date, "%m")))

Rank <- function(x) rank(x, ties = "min")
Sampledata3 <- transform(Sampledata2,
  Rank = ave(Disch, Months, FUN = Rank))

o <- with(Sampledata3, order(Months, Date))
Sampledata3[o, ]
</code>```

Title: How to rearrange daily stream discharge data into monthly format and rank the discharge values for each month using R

Body:
I have a data set of daily stream discharge values from a gauging station for approximately 50 years. The data is arranged into three columns, namely, "date", "month", "discharge".(Sample data shown here)

`

 Date<- as.Date(c('1938-10-01','1954-10-27', '1967-06-16','1943-01-01','1945-01-14','1945-03-14','1954-05-04','1960-04-23','1960-05-09','1962-01-18','1968-12-19','1972-01-15','1977-08-15','1981-04-11','1986-06-20','1989-01-20','1992-03-29'))

> Months<- c('Oct','Oct','Jun','Jan','Jan','Mar','May','Apr','May','Jan','Dec','Jan','Aug','Apr','Jun','Jan','Mar')
> Dis<-c('1000','1200','400','255','450','215','360','120','145','1204','752','635','1456','154','154','1204','450')
> Sampledata<-data.frame("Date"=Date,"Months"=Months,"Disch"=Dis)
> print(Sampledata)
         Date Months Disch
1  1938-10-01    Oct  1000
2  1954-10-27    Oct  1200
3  1967-06-16    Jun   400
4  1943-01-01    Jan   255
5  1945-01-14    Jan   450
6  1945-03-14    Mar   215
7  1954-05-04    May   360
8  1960-04-23    Apr   120
9  1960-05-09    May   145
10 1962-01-18    Jan  1204
11 1968-12-19    Dec   752
12 1972-01-15    Jan   635
13 1977-08-15    Aug  1456
14 1981-04-11    Apr   154
15 1986-06-20    Jun   154
16 1989-01-20    Jan  1204
17 1992-03-29    Mar   450

I want to calculate ranks for each month separately for all the years. For example: Calculate rank in ascending order for the month of January for 50 years. With the same rank value assigned to a duplicate discharge value. Desired output shown here:

>         Date Month Disch Rank
1 1943-01-01   Jan   255    1
2 1945-01-14   Jan   450    2
3 1962-01-18   Jan  1204    4
4 1972-01-15   Jan   635    3
5 1989-01-20   Jan  1204    4
>         Date Month Disch Rank
1 1945-03-14   Mar   215    1
2 1992-03-29   Mar   450    2
3 2001-03-19   Mar   450    2

Body:
Without using any packages first convert columns 2 and 3 to numeric and then use ave and rank with the indicated ties method.  Finally order the result.

Note that the output shown in the question does not correspond to the input, e.g. there are three Mar rows in the output but only two such rows in the input so this will correspond to the input but will not be identical to the output shown.

Sampledata2 <- transform(Sampledata,
  Disch = as.numeric(as.character(Disch)),
  Months = as.numeric(format(Date, "%m")))

Rank <- function(x) rank(x, ties = "min")
Sampledata3 <- transform(Sampledata2,
  Rank = ave(Disch, Months, FUN = Rank))

o <- with(Sampledata3, order(Months, Date))
Sampledata3[o, ]


答:
Try using </p>

```<code>$(this).find('radio').attr('selected','selected');
</code>```

Title: make radio button selected based on an event

Body:
Try using

$(this).find('radio').attr('selected','selected');


问:
Specifically increase an ID value depending on A Foreign Key
I have two database tables; one named Mould, other one named MeasResult.
Mould table has MID as Primary key and MeasResult table has a Foreign Key named MoldID that references MID.
I am logging measurement to MeasResult table using this Foreign key.
MeasResult table also has a MeasID column that keeps track of measurement insert count. For every measurement i am logging 50 rows of data.
What i need to is that i need to increase this MeasID value by 1 every time a new measurement is logged with minding MoldID (Foreign Key in the table).

My current code doesn't mind the Foreign Key, it is just increases MeasResult value by one for every measurement log.

```<code>using (LinqDataClassesDataContext dataContext = new
LinqDataClassesDataContext())
            {
                var measid = dataContext.MeasResults.Select(a =>
a.MeasId).Where(p => p != null).Max() + 1;

                string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

                id = comboBMouldID.SelectedValue.ToString();
                plane = comboBSurface.SelectedItem.ToString();
                pos = Convert.ToInt32(txtTravelPos.Text);

                for (int i = 0; i < daGridMeas.Rows.Count - 1; i++)
                {
                    dist = Convert.ToInt32(daGridMeas.Rows[i].Cells[0].Value.ToString());
                    apert = Convert.ToDouble(daGridMeas.Rows[i].Cells[1].Value.ToString());

                    var st = new MeasResult();
                    {
                        st.MoldID = id;
                        st.Plane = plane;
                        st.Postn = pos;
                        st.Distnc = dist;
                        st.Apert = apert;
                        st.MeasId = measid;
                        st.Date = DateTime.Now;
                    };

                    dataContext.MeasResults.InsertOnSubmit(st);
                    dataContext.SubmitChanges();
                }
</code>```

How can i change the code so it would increase MeasID by 1 for every measurement taken for specific MoldID?

答:
Currently your code is grabbing all the MeasId and incrementing the max value. Try putting a where filter prior to the select method.

```<code>var measid = dataContext.MeasResults.Where(mr => mr.MoldID == id).Select(a => a.MeasId).Max() + 1;
</code>```

The idea here, is instead of selecting the maximum MeasId value from the entire table, you will first filter out all but the measurements for the MoldID that you are recording.

```<code>string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

id = comboBMouldID.SelectedValue.ToString();
plane = comboBSurface.SelectedItem.ToString();
pos = Convert.ToInt32(txtTravelPos.Text);

var tmpRecord = dataContext.MeasResults.Where(mr => mr.MoldID == id).OrderByDescending(mr => mr.MeasId).FirstOrDefault();
int measid = tmpRecord != null ? tmpRecord.MeasId + 1 : 1;

...
</code>```

The tmpRecord statement filters the MeasResults table for all records with MoldID equaling the selected id. Then we sort them in descending order using the MeasId as our sort column. Finally, we take the top record or a null record if none exists. The second line first checks that the record isn't null, then it will take the MeasId of that record and increment it by one. If the record is null then we will assign the value of 1.

Body:
I have two database tables; one named Mould, other one named MeasResult.
Mould table has MID as Primary key and MeasResult table has a Foreign Key named MoldID that references MID.
I am logging measurement to MeasResult table using this Foreign key.
MeasResult table also has a MeasID column that keeps track of measurement insert count. For every measurement i am logging 50 rows of data.
What i need to is that i need to increase this MeasID value by 1 every time a new measurement is logged with minding MoldID (Foreign Key in the table).

My current code doesn't mind the Foreign Key, it is just increases MeasResult value by one for every measurement log.

using (LinqDataClassesDataContext dataContext = new
LinqDataClassesDataContext())
            {
                var measid = dataContext.MeasResults.Select(a =>
a.MeasId).Where(p => p != null).Max() + 1;

                string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

                id = comboBMouldID.SelectedValue.ToString();
                plane = comboBSurface.SelectedItem.ToString();
                pos = Convert.ToInt32(txtTravelPos.Text);

                for (int i = 0; i < daGridMeas.Rows.Count - 1; i++)
                {
                    dist = Convert.ToInt32(daGridMeas.Rows[i].Cells[0].Value.ToString());
                    apert = Convert.ToDouble(daGridMeas.Rows[i].Cells[1].Value.ToString());

                    var st = new MeasResult();
                    {
                        st.MoldID = id;
                        st.Plane = plane;
                        st.Postn = pos;
                        st.Distnc = dist;
                        st.Apert = apert;
                        st.MeasId = measid;
                        st.Date = DateTime.Now;
                    };

                    dataContext.MeasResults.InsertOnSubmit(st);
                    dataContext.SubmitChanges();
                }

How can i change the code so it would increase MeasID by 1 for every measurement taken for specific MoldID?

Body:
Currently your code is grabbing all the MeasId and incrementing the max value. Try putting a where filter prior to the select method.

var measid = dataContext.MeasResults.Where(mr => mr.MoldID == id).Select(a => a.MeasId).Max() + 1;

The idea here, is instead of selecting the maximum MeasId value from the entire table, you will first filter out all but the measurements for the MoldID that you are recording.

string id = ""; string plane = ""; int pos = 0; int dist = 0; double apert = 0;

id = comboBMouldID.SelectedValue.ToString();
plane = comboBSurface.SelectedItem.ToString();
pos = Convert.ToInt32(txtTravelPos.Text);

var tmpRecord = dataContext.MeasResults.Where(mr => mr.MoldID == id).OrderByDescending(mr => mr.MeasId).FirstOrDefault();
int measid = tmpRecord != null ? tmpRecord.MeasId + 1 : 1;

...

The tmpRecord statement filters the MeasResults table for all records with MoldID equaling the selected id. Then we sort them in descending order using the MeasId as our sort column. Finally, we take the top record or a null record if none exists. The second line first checks that the record isn't null, then it will take the MeasId of that record and increment it by one. If the record is null then we will assign the value of 1.


问:
Groupby: Pandas Split-Apply-Combine
Here is a sport df where,

ID is match ID(3 mathes here)

HG and AG Home/Away goals scored

Period is the stage of the game, first quarter, second quarter,...

```<code>d = {'ID':[121,121,121,121,121,121,343,343,343,343,343,343,343,343,678,678,678,678,678,678,678], 'Period':['1Q','1Q','2Q','2Q','3Q','3Q','1Q','1Q','2Q','2Q',
     '3Q','3Q','4Q','4Q','1Q','1Q','2Q','2Q','3Q','3Q','2Q'],'HG':[0,1,2,3,3,3,0,0,1,2,3,4,4,5,0,1,2,2,3,4,5],
    'AG':[0,0,1,2,2,3,0,1,1,2,3,3,4,4,1,2,2,2,3,3,4]}
df = pd.DataFrame(d)
</code>```

I want to study the trajectory of goals scored within a sliced portion of df by simply taking the averages of goal score by either team during the selected time portion.

So I split df by row index and apply some function on it.

Let,

```<code>a = df.groupby("ID", group_keys=False).apply(lambda g: g.iloc[:2]).reset_index(drop=True)
b = df.groupby("ID", group_keys=False).apply(lambda g: g.iloc[2:5]).reset_index(drop=True)
c = df.groupby("ID", group_keys=False).apply(lambda g: g.iloc[5:]).reset_index(drop=True)
</code>```

To compute the average goal per each row (rows are some equal and fixed time interval) within each matches, where the length of matches are different, I have to sum the rows and then divide it by all df.ID.nunique().

```<code>def Goal_Avg(data):
    for i, row in data.iterrows():
        return data.loc[:, ['HG','AG']].sum()
</code>```

Then append the new average goal per row columns(for Home/Away) to df.
Here is how I tried,

First, I created a new row count for ID in df and a, b and c as follow,

```<code>a['idx'] = a.groupby(['ID']).cumcount()
</code>```

and

```<code>df['IDX'] = a.groupby(['ID']).cumcount()
</code>```

Then, create new columns with row sum for each ID and eventually obatin the desire HG_Avg and AG_Avg columns for each match. Which will be the same for same size matches.

```<code>a_sum = a[['HG','AG']].groupby(a['idx']).apply(g_per)
a_sum.rename(columns={'HG':'HG_sum','AG':'AG_sum'}, inplace=True)
a_sum['HG_Avg'] = a_sum['HG_Sum'] / df.ID.nunique()
a_sum['AG_Avg'] = a_sum['AG_Sum'] / df.ID.nunique()
</code>```

My problems are

1- Even after creating the Avg columns for a, b and c, I still  couldnt concat it to original df.

2- The above way looks extremely laborious. Mind you, my data consistes much more than 3 matches.

Here is the final output

```<code>    AG  HG  ID  Period  HG_Avg  AG_Avg  IDX
0   0   0   121     1Q  0.000   0.333   0
1   0   1   121     1Q  0.667   1.000   1
2   1   2   121     2Q  1.667   1.333   2
3   2   3   121     2Q  2.333   2.000   3
4   2   3   121     3Q  3.000   2.667   4
5   3   3   121     3Q  3.667   3.000   5
6   0   0   343     1Q  0.000   0.333   0
7   1   0   343     1Q  0.667   1.000   1
8   1   1   343     2Q  1.667   1.333   2
9   2   2   343     2Q  2.333   2.000   3
10  3   3   343     3Q  3.000   2.667   4
11  3   4   343     3Q  3.667   3.000   5
12  4   4   343     4Q  3.000   2.667   6
13  4   5   343     4Q  1.667   1.333   7
14  1   0   678     1Q  0.000   0.333   0
15  2   1   678     1Q  0.667   1.000   1
16  2   2   678     2Q  1.667   1.333   2
17  2   2   678     2Q  2.333   2.000   3
18  3   3   678     3Q  3.000   2.667   4
19  3   4   678     3Q  3.667   3.000   5
20  4   5   678     2Q  3.000   2.667   6
</code>```

答:
First create the additional key by using cumcount and cut , then you have two key for groupby

```<code>df['NewKey']=pd.cut(df.groupby('ID').cumcount(),[-1,2,5,np.inf])
df.groupby(['ID','NewKey']).apply(yourfunc here)
</code>```

Title: Groupby: Pandas Split-Apply-Combine

Body:
Here is a sport df where,

ID is match ID(3 mathes here)

HG and AG Home/Away goals scored

Period is the stage of the game, first quarter, second quarter,...

d = {'ID':[121,121,121,121,121,121,343,343,343,343,343,343,343,343,678,678,678,678,678,678,678], 'Period':['1Q','1Q','2Q','2Q','3Q','3Q','1Q','1Q','2Q','2Q',
     '3Q','3Q','4Q','4Q','1Q','1Q','2Q','2Q','3Q','3Q','2Q'],'HG':[0,1,2,3,3,3,0,0,1,2,3,4,4,5,0,1,2,2,3,4,5],
    'AG':[0,0,1,2,2,3,0,1,1,2,3,3,4,4,1,2,2,2,3,3,4]}
df = pd.DataFrame(d)

I want to study the trajectory of goals scored within a sliced portion of df by simply taking the averages of goal score by either team during the selected time portion.

So I split df by row index and apply some function on it.

Let,

a = df.groupby("ID", group_keys=False).apply(lambda g: g.iloc[:2]).reset_index(drop=True)
b = df.groupby("ID", group_keys=False).apply(lambda g: g.iloc[2:5]).reset_index(drop=True)
c = df.groupby("ID", group_keys=False).apply(lambda g: g.iloc[5:]).reset_index(drop=True)

To compute the average goal per each row (rows are some equal and fixed time interval) within each matches, where the length of matches are different, I have to sum the rows and then divide it by all df.ID.nunique().

def Goal_Avg(data):
    for i, row in data.iterrows():
        return data.loc[:, ['HG','AG']].sum()

Then append the new average goal per row columns(for Home/Away) to df.
Here is how I tried,

First, I created a new row count for ID in df and a, b and c as follow,

a['idx'] = a.groupby(['ID']).cumcount()

and

df['IDX'] = a.groupby(['ID']).cumcount()

Then, create new columns with row sum for each ID and eventually obatin the desire HG_Avg and AG_Avg columns for each match. Which will be the same for same size matches.

a_sum = a[['HG','AG']].groupby(a['idx']).apply(g_per)
a_sum.rename(columns={'HG':'HG_sum','AG':'AG_sum'}, inplace=True)
a_sum['HG_Avg'] = a_sum['HG_Sum'] / df.ID.nunique()
a_sum['AG_Avg'] = a_sum['AG_Sum'] / df.ID.nunique()

My problems are

1- Even after creating the Avg columns for a, b and c, I still  couldnt concat it to original df.

2- The above way looks extremely laborious. Mind you, my data consistes much more than 3 matches.

Here is the final output

    AG  HG  ID  Period  HG_Avg  AG_Avg  IDX
0   0   0   121     1Q  0.000   0.333   0
1   0   1   121     1Q  0.667   1.000   1
2   1   2   121     2Q  1.667   1.333   2
3   2   3   121     2Q  2.333   2.000   3
4   2   3   121     3Q  3.000   2.667   4
5   3   3   121     3Q  3.667   3.000   5
6   0   0   343     1Q  0.000   0.333   0
7   1   0   343     1Q  0.667   1.000   1
8   1   1   343     2Q  1.667   1.333   2
9   2   2   343     2Q  2.333   2.000   3
10  3   3   343     3Q  3.000   2.667   4
11  3   4   343     3Q  3.667   3.000   5
12  4   4   343     4Q  3.000   2.667   6
13  4   5   343     4Q  1.667   1.333   7
14  1   0   678     1Q  0.000   0.333   0
15  2   1   678     1Q  0.667   1.000   1
16  2   2   678     2Q  1.667   1.333   2
17  2   2   678     2Q  2.333   2.000   3
18  3   3   678     3Q  3.000   2.667   4
19  3   4   678     3Q  3.667   3.000   5
20  4   5   678     2Q  3.000   2.667   6

Body:
First create the additional key by using cumcount and cut , then you have two key for groupby

df['NewKey']=pd.cut(df.groupby('ID').cumcount(),[-1,2,5,np.inf])
df.groupby(['ID','NewKey']).apply(yourfunc here)


问:
Simulate a http request and parse route parameters in Laravel testcase
I'm trying to create unit tests to test some specific classes. I use app()->make() to instantiate the classes to test. So actually, no HTTP requests are needed.

However, some of the tested functions need information from the routing parameters so they'll make calls e.g. request()->route()->parameter('info'), and this throws an exception:

Call to a member function parameter() on null.

I've played around a lot and tried something like:

```<code>request()->attributes = new \Symfony\Component\HttpFoundation\ParameterBag(['info' => 5]);

request()->route(['info' => 5]);

request()->initialize([], [], ['info' => 5], [], [], [], null);
</code>```

but none of them worked...

How could I manually initialize the router and feed some routing parameters to it? Or simply make request()->route()->parameter() available?

Update

@Loek: You didn't understand me. Basically, I'm doing:

```<code>class SomeTest extends TestCase
{
    public function test_info()
    {
        $info = request()->route()->parameter('info');
        $this->assertEquals($info, 'hello_world');
    }
}
</code>```

No "requests" involved. The request()->route()->parameter() call is actually located in a service provider in my real code. This test case is specifically used to test that service provider. There isn't a route which will print the returning value from the methods in that provider.

答:
Since route is implemented as a closure, you can access a route parameter directly in the route, without explicitly calling parameter('info'). These two calls returns the same:

```<code>$info = $request->route()->parameter('info');
$info = $request->route('info');
</code>```

The second way, makes mocking the 'info' parameter very easy:

```<code>$request = $this->createMock(Request::class);
$request->expects($this->once())->method('route')->willReturn('HelloWorld');
$info = $request->route('info');
$this->assertEquals($info, 'HelloWorld');
</code>```

Of course to exploit this method in your tests, you should inject the Request object in your class under test, instead of using the Laravel global request object through the request() method.

Body:
I'm trying to create unit tests to test some specific classes. I use app()->make() to instantiate the classes to test. So actually, no HTTP requests are needed.

However, some of the tested functions need information from the routing parameters so they'll make calls e.g. request()->route()->parameter('info'), and this throws an exception:

Call to a member function parameter() on null.

I've played around a lot and tried something like:

request()->attributes = new \Symfony\Component\HttpFoundation\ParameterBag(['info' => 5]);

request()->route(['info' => 5]);

request()->initialize([], [], ['info' => 5], [], [], [], null);

but none of them worked...

How could I manually initialize the router and feed some routing parameters to it? Or simply make request()->route()->parameter() available?

Update

@Loek: You didn't understand me. Basically, I'm doing:

class SomeTest extends TestCase
{
    public function test_info()
    {
        $info = request()->route()->parameter('info');
        $this->assertEquals($info, 'hello_world');
    }
}

No "requests" involved. The request()->route()->parameter() call is actually located in a service provider in my real code. This test case is specifically used to test that service provider. There isn't a route which will print the returning value from the methods in that provider.

Body:
Since route is implemented as a closure, you can access a route parameter directly in the route, without explicitly calling parameter('info'). These two calls returns the same:

$info = $request->route()->parameter('info');
$info = $request->route('info');

The second way, makes mocking the 'info' parameter very easy:

$request = $this->createMock(Request::class);
$request->expects($this->once())->method('route')->willReturn('HelloWorld');
$info = $request->route('info');
$this->assertEquals($info, 'HelloWorld');

Of course to exploit this method in your tests, you should inject the Request object in your class under test, instead of using the Laravel global request object through the request() method.


问:
Grafana Prometheus wrong default query
Hi f I have metrics like envoy_cluster_cluster_service1_upstream_rq_time and  envoy_cluster_cluster_service2_upstream_rq_time up to 100 how to sum them all ?

答:
sum({__name__=~"envoy_cluster_cluster_service[0-9]+_upstream_rq_time"})

Or better yet, relabel your metrics.

Title: Grafana Prometheus wrong default query