问:
error calling tpl: error during tpl function execution for "configuration.yaml.default (home assistant helm upgrade on truenas scale)
I'm having trouble trying to update my home assistant with truecharts.

```<code>[EFAULT] Failed to upgrade chart release:
Error: UPGRADE FAILED:
template: commonloader.apply" at :
error calling include:
template: home-assistant/charts/common/templates/spawner/_configmap.tpl:16:10:
executing "tc.common.spawner.configmap" at :
error calling include: template: home-assistant/charts/common/templates/class/_configmap.tpl:33:6: executing "tc.common.class.configmap" at :
error calling tpl: error during tpl function execution for "configuration.yaml.default:
{{- if hasKey .Values \"ixChartContext\" }}
 - {{ .Values.ixChartContext.kubernetes_config.cluster_cidr }}
 {{- else }}
 {{- range .Values.homeassistant.trusted_proxies }}
 - {{ . }}
 {{- end }}
 {{- end }}
init.sh: |-
 #!/bin/sh
 if test -f \"/config/configuration.yaml\"; then
 echo \"configuration.yaml exists.\"
 if grep -q recorder: \"/config/configuration.yaml\"; then
 echo \"configuration.yaml already contains recorder\"
 else
 cat /config/init/recorder.default >> /config/configuration.yaml
 fi
 if grep -q http: \"/config/configuration.yaml\"; then
 echo \"configuration.yaml already contains http section\"
 else
 cat /config/init/http.default >> /config/configuration.yaml
 fi
 else
 echo \"configuration.yaml does NOT exist.\"
 cp /config/init/configuration.yaml.default /config/configuration.yaml
 cat /config/init/recorder.default >> /config/configuration.yaml
 cat /config/init/http.default >> /config/configuration.yaml
 fi
 echo \"Creating include files...\"
 for include_file in groups.yaml automations.yaml scripts.yaml scenes.yaml; do
 if test -f \"/config/$include_file\"; then
 echo \"$include_file exists.\"
 else
 echo \"$include_file does NOT exist.\"
 touch \"/config/$include_file\"
 fi
 done
 cd \"/config\" || echo \"Could not change path to /config\"
 echo \"Creating custom_components directory...\"
 mkdir \"/config/custom_components\" || echo \"custom_components directory already exists\"
 echo \"Changing to the custom_components directory...\"
 cd \"/config/custom_components\" || echo \"Could not change path to /config/custom_components\"
 echo \"Downloading HACS\"
 wget \"https://github.com/hacs/integration/releases/latest/download/hacs.zip\" || exit 0
 if [ -d \"/config/custom_components/hacs\" ]; then
 echo \"HACS directory already exist, cleaning up...\"
 rm -R \"/config/custom_components/hacs\"
 fi
 echo \"Creating HACS directory...\"
 mkdir \"/config/custom_components/hacs\"
 echo \"Unpacking HACS...\"
 unzip \"/config/custom_components/hacs.zip\" -d \"/config/custom_components/hacs\" >/dev
ull 2>&1
 echo \"Removing HACS zip file...\"
 rm \"/config/custom_components/hacs.zip\"
 echo \"Installation complete.\"
recorder.default: |2-
 recorder:
 purge_keep_days: 30
 commit_interval: 3
 db_url: {{ ( printf \"%s?client_encoding=utf8\" ( .Values.postgresql.url.complete | trimAll \"\\\"\" ) ) | quote }}": template: home-assistant/templates/common.yaml:19:18: executing "home-assistant/templates/common.yaml" at <.Values.ixChartContext.kubernetes_config.cluster_cidr>: nil pointer evaluating interface {}.cluster_cidr

</code>```

I tried chmod 755 on the custom_components directory and also tried to use the bare minimum for the configuration.yaml.  Still got the same error. Is there a way I can run a debug on this?  Anyone have any ideas?

Body:
I'm having trouble trying to update my home assistant with truecharts.

[EFAULT] Failed to upgrade chart release:
Error: UPGRADE FAILED:
template: commonloader.apply" at :
error calling include:
template: home-assistant/charts/common/templates/spawner/_configmap.tpl:16:10:
executing "tc.common.spawner.configmap" at :
error calling include: template: home-assistant/charts/common/templates/class/_configmap.tpl:33:6: executing "tc.common.class.configmap" at :
error calling tpl: error during tpl function execution for "configuration.yaml.default:
{{- if hasKey .Values \"ixChartContext\" }}
 - {{ .Values.ixChartContext.kubernetes_config.cluster_cidr }}
 {{- else }}
 {{- range .Values.homeassistant.trusted_proxies }}
 - {{ . }}
 {{- end }}
 {{- end }}
init.sh: |-
 #!/bin/sh
 if test -f \"/config/configuration.yaml\"; then
 echo \"configuration.yaml exists.\"
 if grep -q recorder: \"/config/configuration.yaml\"; then
 echo \"configuration.yaml already contains recorder\"
 else
 cat /config/init/recorder.default >> /config/configuration.yaml
 fi
 if grep -q http: \"/config/configuration.yaml\"; then
 echo \"configuration.yaml already contains http section\"
 else
 cat /config/init/http.default >> /config/configuration.yaml
 fi
 else
 echo \"configuration.yaml does NOT exist.\"
 cp /config/init/configuration.yaml.default /config/configuration.yaml
 cat /config/init/recorder.default >> /config/configuration.yaml
 cat /config/init/http.default >> /config/configuration.yaml
 fi
 echo \"Creating include files...\"
 for include_file in groups.yaml automations.yaml scripts.yaml scenes.yaml; do
 if test -f \"/config/$include_file\"; then
 echo \"$include_file exists.\"
 else
 echo \"$include_file does NOT exist.\"
 touch \"/config/$include_file\"
 fi
 done
 cd \"/config\" || echo \"Could not change path to /config\"
 echo \"Creating custom_components directory...\"
 mkdir \"/config/custom_components\" || echo \"custom_components directory already exists\"
 echo \"Changing to the custom_components directory...\"
 cd \"/config/custom_components\" || echo \"Could not change path to /config/custom_components\"
 echo \"Downloading HACS\"
 wget \"https://github.com/hacs/integration/releases/latest/download/hacs.zip\" || exit 0
 if [ -d \"/config/custom_components/hacs\" ]; then
 echo \"HACS directory already exist, cleaning up...\"
 rm -R \"/config/custom_components/hacs\"
 fi
 echo \"Creating HACS directory...\"
 mkdir \"/config/custom_components/hacs\"
 echo \"Unpacking HACS...\"
 unzip \"/config/custom_components/hacs.zip\" -d \"/config/custom_components/hacs\" >/dev
ull 2>&1
 echo \"Removing HACS zip file...\"
 rm \"/config/custom_components/hacs.zip\"
 echo \"Installation complete.\"
recorder.default: |2-
 recorder:
 purge_keep_days: 30
 commit_interval: 3
 db_url: {{ ( printf \"%s?client_encoding=utf8\" ( .Values.postgresql.url.complete | trimAll \"\\\"\" ) ) | quote }}": template: home-assistant/templates/common.yaml:19:18: executing "home-assistant/templates/common.yaml" at <.Values.ixChartContext.kubernetes_config.cluster_cidr>: nil pointer evaluating interface {}.cluster_cidr

I tried chmod 755 on the custom_components directory and also tried to use the bare minimum for the configuration.yaml.  Still got the same error. Is there a way I can run a debug on this?  Anyone have any ideas?


来源: stackexchange

问:
How to create a new variable conditioning on another variable in R?
Consider the following data:

```<code>df <- data.frame(id=c(1,2,3,4,5),
                 v1=c(2020,2020,2021,2021,2022),
                 v2=c(12,5,66,17,17))
</code>```

I need the output of the form (just averaging v2 based on v1):

```<code>id  v1     v2   avg_by_yr
 1  2020   12    8.5
 2  2020    5    8.5
 3  2021   66    41.5
 4  2021   17    41.5
 5  2022   17     17
</code>```

Thanks!

ContentLicense: CC BY-SA 4.0

Body:
Consider the following data:

df <- data.frame(id=c(1,2,3,4,5),
                 v1=c(2020,2020,2021,2021,2022),
                 v2=c(12,5,66,17,17))

I need the output of the form (just averaging v2 based on v1):

id  v1     v2   avg_by_yr
 1  2020   12    8.5
 2  2020    5    8.5
 3  2021   66    41.5
 4  2021   17    41.5
 5  2022   17     17

Thanks!


问:
Reduce the number of labels on Axis
I am creating a series of plots like so:

```<code>data_subset <- df_order

#Hier wird eine Spalte hinzugefügt die sich nur auf das Jahr bezieht, damit werden die Daten dann auf der X-Achse abgebildet
data_subset$Year <- format(data_subset$DateAsDate, "%Y")
plotdf <- ddply(data_subset,.(Year, Sex),
      function(zz){
        #Sämtliche Daten hier werden pro Jahr und Geschlecht aufgetragen.
        data.frame(
          rownum=nrow(zz)
          )
        }
      )

library(reshape2)
library(reshape)

meltdf <- melt(plotdf, id=c("Year", "Sex"))

meltdf$Dicipline <- substr(meltdf$variable, 1, nchar(as.character(meltdf$variable))-3)
meltdf$variable <- substr(meltdf$variable, nchar(as.character(meltdf$variable))-2, nchar(as.character(meltdf$variable)))

meltdf %>% ggplot(aes(x = Year, y = value, colour = variable, group = variable)) +
  geom_line() + facet_grid(Sex~Dicipline) + labs(x="Jahr", y="Anzahl Teilnahmen")

#ggplot(plotdf, aes(x = Year)) + geom_line(aes(y = xmin)) + geom_line(aes(y = xmed)) + labs(x="Jahr", y="Gewichtswerte")

</code>```

It plots the number of values of my data frame per year separated by Sex, and it works fine, but the x-Axis looks very crammed, since I have data from the 1960s until today.

How can I reduce the number of labels on the x-Axis, so that e.g. only every 10th year is printed below the axis?

Title: Reduce the number of labels on Axis

Body:
I am creating a series of plots like so:

data_subset <- df_order

#Hier wird eine Spalte hinzugefügt die sich nur auf das Jahr bezieht, damit werden die Daten dann auf der X-Achse abgebildet
data_subset$Year <- format(data_subset$DateAsDate, "%Y")
plotdf <- ddply(data_subset,.(Year, Sex),
      function(zz){
        #Sämtliche Daten hier werden pro Jahr und Geschlecht aufgetragen.
        data.frame(
          rownum=nrow(zz)
          )
        }
      )

library(reshape2)
library(reshape)

meltdf <- melt(plotdf, id=c("Year", "Sex"))

meltdf$Dicipline <- substr(meltdf$variable, 1, nchar(as.character(meltdf$variable))-3)
meltdf$variable <- substr(meltdf$variable, nchar(as.character(meltdf$variable))-2, nchar(as.character(meltdf$variable)))

meltdf %>% ggplot(aes(x = Year, y = value, colour = variable, group = variable)) +
  geom_line() + facet_grid(Sex~Dicipline) + labs(x="Jahr", y="Anzahl Teilnahmen")

#ggplot(plotdf, aes(x = Year)) + geom_line(aes(y = xmin)) + geom_line(aes(y = xmed)) + labs(x="Jahr", y="Gewichtswerte")

It plots the number of values of my data frame per year separated by Sex, and it works fine, but the x-Axis looks very crammed, since I have data from the 1960s until today.

How can I reduce the number of labels on the x-Axis, so that e.g. only every 10th year is printed below the axis?


问:
How to run migrations on a private RDS instance using Prisma?
I have a Node project which is using terraform for  provisioning and resource creation while serverless is used to deploy the functions. I'm using Prisma as the ORM with graphql. My problem is that I have a private RDS instance which is created through terraform and provisioned. Now I want to run the
npx prisma migrate
command but i'm not sure where do I run it as it is a private RDS instance and I can't run the migration command before terraform creates the resource.

I have tried codebuild as a build solution but unfortunately that requires a NAT gateway which I can't use as I need to work with public subnets.


问:
Create a virtual column in Slick that is a combination of two?
Say I have a table names like so:

```<code>id | first_name | last_name
===========================
1  | Cory       |
2  |            | Smith
3  | Rebecca    | Random
</code>```

And its corresponding Slick model looks about like this:

```<code>class NamesRow(tag: Tag) extends Table[Name](tag, "names") {
  def id: Rep[Long] = column[Long]("id")
  def firstName: Rep[Option[String]] = column[Option[String]]("first_name")
  def lastName: Rep[Option[String]] = column[Option[String]]("last_name")
  def virtualName: Rep[Option[String]] = firstName orElse lastName

  def * = ...
}
</code>```

I'd like to create virtualName as shown above, which effectively would be the individual's first name if available, falling back to their last name. I know how to do this at query time using the regular Slick facilities, but I'm wondering if it's possible to define this as a sort of "virtual column" directly on NamesRow in this way such that it could be queried as if the column actually existed in the database, in the same way I might create a virtual view in Postgres.

The problem is that firstName orElse lastName is not valid code because Rep does not provide an orElse method.

How can I define virtualName to be a combination of other pre-existing columns?

Body:
Say I have a table names like so:

id | first_name | last_name
===========================
1  | Cory       |
2  |            | Smith
3  | Rebecca    | Random

And its corresponding Slick model looks about like this:

class NamesRow(tag: Tag) extends Table[Name](tag, "names") {
  def id: Rep[Long] = column[Long]("id")
  def firstName: Rep[Option[String]] = column[Option[String]]("first_name")
  def lastName: Rep[Option[String]] = column[Option[String]]("last_name")
  def virtualName: Rep[Option[String]] = firstName orElse lastName

  def * = ...
}

I'd like to create virtualName as shown above, which effectively would be the individual's first name if available, falling back to their last name. I know how to do this at query time using the regular Slick facilities, but I'm wondering if it's possible to define this as a sort of "virtual column" directly on NamesRow in this way such that it could be queried as if the column actually existed in the database, in the same way I might create a virtual view in Postgres.

The problem is that firstName orElse lastName is not valid code because Rep does not provide an orElse method.

How can I define virtualName to be a combination of other pre-existing columns?


问:
use txt ids to build string
I want to extract ids from a text file and build a string for a curl request
I tried this

```<code>#!/bin/bash
for ids in `cat numbers.txt`
do
    echo "hi/$ids/oo"
done
echo "ALL DONE"
</code>```

But this gives me the wrong output. It prints

```<code>/oo12341
/oo56z49
/oo60272347
/oo2347
/oo12312356
hi/124556616/oo
ALL DONE
</code>```

instead of:

```<code> hi/12341/oo
 hi/56z49/oo
 hi/60272347/oo
 hi/2347/oo
 hi/12312356/oo
 hi/124556616/oo
</code>```

Title: use txt ids to build string

Body:
I want to extract ids from a text file and build a string for a curl request
I tried this

#!/bin/bash
for ids in `cat numbers.txt`
do
    echo "hi/$ids/oo"
done
echo "ALL DONE"

But this gives me the wrong output. It prints

/oo12341
/oo56z49
/oo60272347
/oo2347
/oo12312356
hi/124556616/oo
ALL DONE

instead of:

 hi/12341/oo
 hi/56z49/oo
 hi/60272347/oo
 hi/2347/oo
 hi/12312356/oo
 hi/124556616/oo


问:
Could not find method ndkVersion() for arguments [25.1.8937393]
I am opening a dart/flutter, Android app that was shelved some years ago and slowly working through the deprecated items, which I believe I have fixed. However, when I try to run the app in either Android Studio or via VSCode extension I get the above error.

I have updated the android/app/build.gradle file to have:

```<code>android {
compileSdkVersion flutter.compileSdkVersion
ndkVersion "25.1.8937393"
</code>```

However, the error persists.
I would appreciate some help resolving this.

Sid

Body:
I am opening a dart/flutter, Android app that was shelved some years ago and slowly working through the deprecated items, which I believe I have fixed. However, when I try to run the app in either Android Studio or via VSCode extension I get the above error.

I have updated the android/app/build.gradle file to have:

android {
compileSdkVersion flutter.compileSdkVersion
ndkVersion "25.1.8937393"

However, the error persists.
I would appreciate some help resolving this.

Sid


问:
how to mock flutter_logs in flutter
I am testing repo method

```<code>@override
  Future<DataState<bool>> login(String email, String password) async {
    FlutterLogs.logInfo(TAG, ACTION_TAG, 'login');
    return await doSafeApiCall<bool, JwtResponse>(
        () async => await _appApiService.signIn(SignInRequest(email: email, password: password)),
        (responseData) => true,
        extraSuccessAction: (responseData) => _actionAfterEnter(responseData));
  }
</code>```

but i have error

```<code>package:flutter/src/services/platform_channel.dart 294:7                                         MethodChannel._invokeMethod
===== asynchronous gap ===========================
dart:async                                                                                _CustomZone.registerBinaryCallback
test/unit/repository_test/repository_helpers.dart 37:18                                          testingRepoCall
test/unit/repository_test/authorization_repository/authorization_repositpry_impl_test.dart 61:6  main.<fn>
This test failed after it had already completed. Make sure to use [expectAsync]
or the [completes] matcher when testing async code.
package:flutter/src/services/platform_channel.dart 294:7                                         MethodChannel._invokeMethod
===== asynchronous gap ===========================
dart:async                                                                                _CustomZone.registerBinaryCallback
test/unit/repository_test/repository_helpers.dart 37:18                                          testingRepoCall
test/unit/repository_test/authorization_repository/authorization_repositpry_impl_test.dart 61:6  main.<fn>

MissingPluginException(No implementation found for method logThis on channel flutter_logs)
</code>```

with FlutterLogs.logInfo(TAG, ACTION_TAG, 'login');
Hove can i mock or stub FlutterLogs.logInfo?I use package called flutter_logs.Could you help me?

Title: how to mock flutter_logs in flutter

Body:
I am testing repo method

@override
  Future<DataState<bool>> login(String email, String password) async {
    FlutterLogs.logInfo(TAG, ACTION_TAG, 'login');
    return await doSafeApiCall<bool, JwtResponse>(
        () async => await _appApiService.signIn(SignInRequest(email: email, password: password)),
        (responseData) => true,
        extraSuccessAction: (responseData) => _actionAfterEnter(responseData));
  }

but i have error

package:flutter/src/services/platform_channel.dart 294:7                                         MethodChannel._invokeMethod
===== asynchronous gap ===========================
dart:async                                                                                _CustomZone.registerBinaryCallback
test/unit/repository_test/repository_helpers.dart 37:18                                          testingRepoCall
test/unit/repository_test/authorization_repository/authorization_repositpry_impl_test.dart 61:6  main.<fn>
This test failed after it had already completed. Make sure to use [expectAsync]
or the [completes] matcher when testing async code.
package:flutter/src/services/platform_channel.dart 294:7                                         MethodChannel._invokeMethod
===== asynchronous gap ===========================
dart:async                                                                                _CustomZone.registerBinaryCallback
test/unit/repository_test/repository_helpers.dart 37:18                                          testingRepoCall
test/unit/repository_test/authorization_repository/authorization_repositpry_impl_test.dart 61:6  main.<fn>

MissingPluginException(No implementation found for method logThis on channel flutter_logs)

with FlutterLogs.logInfo(TAG, ACTION_TAG, 'login');
Hove can i mock or stub FlutterLogs.logInfo?I use package called flutter_logs.Could you help me?


问:
Panel state space Statsmodels : 'value' must be an instance of str or bytes, not a tuple"
I'm attempting to set up a panel TVPVAR using statistics models.
I'm going through Chad Fulton's steps 1 through 3.
Link
https://www.statsmodels.org/devel/examples/notebooks/generated/statespace_tvpvar_mcmc_cfa.html

Coming from Stata, I set up the panel framework as follows:

```<code>#  Panel data settings
year = dta.year
year = pd.Categorical(dta.year)
dta = dta.set_index([ "country", "year"])
dta["year"] = year
</code>```

Now, when I try to run the locale model, I reach the point  #4 where I get the following error:

```<code>Traceback

Traceback (most recent call last):

  File "/var/folders/m6/68zljfsj2t9_dzgpwwslj29r0000gp/T/ipykernel_2096/947403769.py", line 103, in <module>
    ax.plot(dta.index, sim_kfs.simulated_state[0],

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1632, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 312, in __call__
    yield from self._plot_args(this, kwargs)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 493, in _plot_args
    self.axes.xaxis.update_units(x)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axis.py", line 1449, in update_units
    default = self.converter.default_units(data, self)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/category.py", line 116, in default_units
    axis.set_units(UnitData(data))

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/category.py", line 192, in __init__
    self.update(data)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/category.py", line 227, in update
    _api.check_isinstance((str, bytes), value=val)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/_api/__init__.py", line 93, in check_isinstance
    raise TypeError(

TypeError: 'value' must be an instance of str or bytes, not a tuple
</code>```

Additionally, the panel is composed of about 80 countries; nonetheless, only a few appear in the same graph. I get the following graph, which worries me because it shows countries and time instead of a single time series line.

The following image is the  second one produce in point #4 Simulations based on CFA approach, MLE parameters'

The error appears in the third image of point #4

enter image description here
enter image description hereCould anyone suggest how to solve this and how to proceed up to the point 18 of his code?
Full code  is

```<code>%matplotlib inline

from importlib import reload
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt

from scipy.stats import invwishart, invgamma

#1

import pyreadstat

dtafile = 'TVP.dta'
dta, meta = pyreadstat.read_dta(dtafile)
dta.tail()

labels=list(meta.column_labels)
column=list(meta.column_names)

#  Panel data settings
year = dta.year
year = pd.Categorical(dta.year)
dta = dta.set_index([ "country", "year"])
dta["year"] = year

dta.head()

#2
# Construct a local level model for Growth rate of labor productivity
mod = sm.tsa.UnobservedComponents(dta.lp, 'llevel')

# Fit the model's parameters (sigma2_varepsilon and sigma2_eta)
# via maximum likelihood
res = mod.fit()
print(res.params)

# Create simulation smoother objects
sim_kfs = mod.simulation_smoother()              # default method is KFS
sim_cfa = mod.simulation_smoother(method='cfa')  # can specify CFA method
fa = mod.simulation_smoother(method='cfa')  # can specify CFA method

#3
nsimulations = 20
simulated_state_kfs = pd.DataFrame(
    np.zeros((mod.nobs, nsimulations)), index=dta.index)
simulated_state_cfa = pd.DataFrame(
    np.zeros((mod.nobs, nsimulations)), index=dta.index)

for i in range(nsimulations):
    # Apply KFS simulation smoothing
    sim_kfs.simulate()
    # Save the KFS simulated state
    simulated_state_kfs.iloc[:, i] = sim_kfs.simulated_state[0]

    # Apply CFA simulation smoothing
    sim_cfa.simulate()
    # Save the CFA simulated state
    simulated_state_cfa.iloc[:, i] = sim_cfa.simulated_state[0]

#4
# Plot the Growth rate of labor productivity data along with simulated trends
fig, axes = plt.subplots(2, figsize=(15, 6))

# Plot data and KFS simulations
dta.lp.plot(ax=axes[0], color='k')
axes[0].set_title('Simulations based on KFS approach, MLE parameters')
simulated_state_kfs.plot(ax=axes[0], color='C0', alpha=0.25, legend=False)

# Plot data and CFA simulations
dta.lp.plot(ax=axes[1], color='k')
axes[1].set_title('Simulations based on CFA approach, MLE parameters')
simulated_state_cfa.plot(ax=axes[1], color='C0', alpha=0.25, legend=False)

# Add a legend, clean up layout
handles, labels = axes[0].get_legend_handles_labels()
axes[0].legend(handles[:2], ['Data', 'Simulated state'])
fig.tight_layout();

#5
fig, ax = plt.subplots(figsize=(15, 3))

# Update the model's parameterization to one that attributes more
# variation in productivity growth to the observation error and so has less
# variation in the trend component
mod.update([4, 0.05])

# Plot simulations
for i in range(nsimulations):
    sim_kfs.simulate()
    ax.plot(dta.index, sim_kfs.simulated_state[0],
            color='C0', alpha=0.25, label='Simulated state')

# Plot data
dta.lp.plot(ax=ax, color='k', label='Data', zorder=-1)

# Add title, legend, clean up layout
ax.set_title('Simulations with alternative parameterization yielding a smoother trend')
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:])
fig.tight_layout();

#6
# Subset to the four variables of interest
y = dta[['lp', 'tf', 'prices', 'u', 'bu', 'ip', 'tra',
        'ext', 'dom', 'la', 'gr', 'sd', 'de',
        'fd', 'ka',]].copy()
y.columns = ['lp', 'tf', 'prices', 'u', 'bu', 'ip', 'tra',
        'ext', 'dom', 'la', 'gr', 'sd', 'de',
        'fd', 'ka',]].]

fig, ax = plt.subplots(figsize=(15, 5))
y.plot(ax=ax)
ax.set_title('Evolution of macroeconomic variables included in TVP-VAR exercise');

#7
# 1. Create a new TVPVAR class as a subclass of sm.tsa.statespace.MLEModel
class TVPVAR(sm.tsa.statespace.MLEModel):
    # Steps 2-3 are best done in the class "constructor", i.e. the __init__ method
    def __init__(self, y):
        # Create a matrix with [y_t' : y_{t-1}'] for t = 2, ..., T
        augmented = sm.tsa.lagmat(y, 1, trim='both', original='in', use_pandas=True)
        # Separate into y_t and z_t = [1 : y_{t-1}']
        p = y.shape[1]
        y_t = augmented.iloc[:, :p]
        z_t = sm.add_constant(augmented.iloc[:, p:])

        # Recall that the length of the state vector is p * (p + 1)
        k_states = p * (p + 1)
        super().__init__(y_t, exog=z_t, k_states=k_states)

        # Note that the state space system matrices default to contain zeros,
        # so we don't need to explicitly set c_t = d_t = 0.

        # Construct the design matrix Z_t
        # Notes:
        # -> self.k_endog = p is the dimension of the observed vector
        # -> self.k_states = p * (p + 1) is the dimension of the observed vector
        # -> self.nobs = T is the number of observations in y_t
        self['design'] = np.zeros((self.k_endog, self.k_states, self.nobs))
        for i in range(self.k_endog):
            start = i * (self.k_endog + 1)
            end = start + self.k_endog + 1
            self['design', i, start:end, :] = z_t.T

        # Construct the transition matrix T = I
        self['transition'] = np.eye(k_states)

        # Construct the selection matrix R = I
        self['selection'] = np.eye(k_states)

        # Step 3: Initialize the state vector as alpha_1 ~ N(0, 5I)
        self.ssm.initialize('known', stationary_cov=5 * np.eye(self.k_states))

    # Step 4. Create a method that we can call to update H and Q
    def update_variances(self, obs_cov, state_cov_diag):
        self['obs_cov'] = obs_cov
        self['state_cov'] = np.diag(state_cov_diag)

    # Finally, it can be convenient to define human-readable names for
    # each element of the state vector. These will be available in output
    @property
    def state_names(self):
        state_names = np.empty((self.k_endog, self.k_endog + 1), dtype=object)
        for i in range(self.k_endog):
            endog_name = self.endog_names[i]
            state_names[i] = (
                ['intercept.%s' % endog_name] +
                ['L1.%s->%s' % (other_name, endog_name) for other_name in self.endog_names])
        return state_names.ravel().tolist()

    # Create an instance of our TVPVAR class with our observed dataset y
mod = TVPVAR(y)

initial_obs_cov = np.cov(y.T)
initial_state_cov_diag = [0.01] * mod.k_states

# Update H and Q
mod.update_variances(initial_obs_cov, initial_state_cov_diag)

# Perform Kalman filtering and smoothing
# (the [] is just an empty list that in some models might contain
# additional parameters. Here, we don't have any additional parameters
# so we just pass an empty list)
initial_res = mod.smooth([])

#10
def plot_coefficients_by_equation(states):
    fig, axes = plt.subplots(2, 2, figsize=(15, 8))

    # The way we defined Z_t implies that the first 5 elements of the
    # state vector correspond to the first variable in y_t, which is la
    ax = axes[0, 0]
    states.iloc[:, :5].plot(ax=ax)
    ax.set_title('la')
    ax.legend()

    # The next 5 elements correspond to tf
    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title(tf')
    ax.legend();

    # The next 5 elements correspond to
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('Price')
    ax.legend()

    # The last 5 elements correspond to the U
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('U equation')
    ax.legend();

    # The next 5 elements correspond to bu
    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title('bu equation')
    ax.legend();

    # The next 5 elements correspond to ip
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('ip equation')
    ax.legend()

    # The last 5 elements correspond to the tra equation
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('tra equation')
    ax.legend();

   # The next 5 elements correspond to ex equation
    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title('ex equation')
    ax.legend();

   # The next 5 elements correspond to La equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('La equation')
    ax.legend()

  # The last 5 elements correspond to the gr
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('gr Rate equation')
    ax.legend();

  # The next 5 elements correspond to sd

    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title('sd equation')
    ax.legend();

  # The next 5 elements correspond to de equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('debtequation')
    ax.legend()

# The last 5 elements correspond to the  fi  equation
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('Fi equation')
    ax.legend();

  # The next 5 elements correspond to ka equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('ka equation')
    ax.legend()

# The next 5 elements correspond to Weighted magiority=0 equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('Weighted magiority=0 equation')
    ax.legend()

    return ax

#11
# Here, for illustration purposes only, we plot the time-varying
# coefficients conditional on an ad-hoc parameterization

# Recall that `initial_res` contains the Kalman filtering and smoothing,
# and the `states.smoothed` attribute contains the smoothed states
plot_coefficients_by_equation(initial_res.states.smoothed);

#12
# Prior hyperparameters

# Prior for obs. cov. is inverse-Wishart(v_1^0=k + 3, S10=I)
v10 = mod.k_endog + 3
S10 = np.eye(mod.k_endog)

# Prior for state cov. variances is inverse-Gamma(v_{i2}^0 / 2 = 3, S+{i2}^0 / 2 = 0.005)
vi20 = 6
Si20 = 0.01

#13
# Gibbs sampler setup
niter = 11000
nburn = 1000

# 1. Create storage arrays
store_states = np.zeros((niter + 1, mod.nobs, mod.k_states))
store_obs_cov = np.zeros((niter + 1, mod.k_endog, mod.k_endog))
store_state_cov = np.zeros((niter + 1, mod.k_states))

# 2. Put in the initial values
store_obs_cov[0] = initial_obs_cov
store_state_cov[0] = initial_state_cov_diag
mod.update_variances(store_obs_cov[0], store_state_cov[0])

# 3. Construct posterior samplers
sim = mod.simulation_smoother(method='cfa')

#14
for i in range(niter):
    mod.update_variances(store_obs_cov[i], store_state_cov[i])
    sim.simulate()

    # 1. Sample states
    store_states[i + 1] = sim.simulated_state.T

    # 2. Simulate obs cov
    fitted = np.matmul(mod['design'].transpose(2, 0, 1), store_states[i + 1][..., None])[..., 0]
    resid = mod.endog - fitted
    store_obs_cov[i + 1] = invwishart.rvs(v10 + mod.nobs, S10 + resid.T @ resid)

    # 3. Simulate state cov variances
    resid = store_states[i + 1, 1:] - store_states[i + 1, :-1]
    sse = np.sum(resid**2, axis=0)

    for j in range(mod.k_states):
        rv = invgamma.rvs((vi20 + mod.nobs - 1) / 2, scale=(Si20 + sse[j]) / 2)
        store_state_cov[i + 1, j] = rv

 #15
 # Collect the posterior means of each time-varying coefficient
states_posterior_mean = pd.DataFrame(
    np.mean(store_states[nburn + 1:], axis=0),
    index=mod._index, columns=mod.state_names)

# Plot these means over time
plot_coefficients_by_equation(states_posterior_mean);

#16
import arviz as az

# Collect the observation error covariance parameters
az_obs_cov = az.convert_to_inference_data({
    ('Var[%s]' % mod.endog_names[i] if i == j else
     'Cov[%s, %s]' % (mod.endog_names[i], mod.endog_names[j])):
    store_obs_cov[nburn + 1:, i, j]
    for i in range(mod.k_endog) for j in range(i, mod.k_endog)})

# Plot the credible intervals
az.plot_forest(az_obs_cov, figsize=(8, 7));

#17
# Collect the state innovation variance parameters
az_state_cov = az.convert_to_inference_data({
    r'$\sigma^2$[%s]' % mod.state_names[i]: store_state_cov[nburn + 1:, i]
    for i in range(mod.k_states)})

# Plot the credible intervals
az.plot_forest(az_state_cov, figsize=(8, 7));

#18
from statsmodels.tsa.statespace.simulation_smoother import SIMULATION_STATE

sim_cfa = mod.simulation_smoother(method='cfa')
sim_kfs = mod.simulation_smoother(simulation_output=SIMULATION_STATE)

#19

# Impluse Response
ax = res.impulse_responses(10, orthogonalized=True, impulse=[1, 0]).plot(figsize=(13,3))
ax.set(xlabel='t', title='Responses to a shock to `xxxx`');
</code>```

Could anyone suggest how to solve this and how to proceed up to the point 18 of his code?

Body:
I'm attempting to set up a panel TVPVAR using statistics models.
I'm going through Chad Fulton's steps 1 through 3.
Link
https://www.statsmodels.org/devel/examples/notebooks/generated/statespace_tvpvar_mcmc_cfa.html

Coming from Stata, I set up the panel framework as follows:

#  Panel data settings
year = dta.year
year = pd.Categorical(dta.year)
dta = dta.set_index([ "country", "year"])
dta["year"] = year

Now, when I try to run the locale model, I reach the point  #4 where I get the following error:

Traceback

Traceback (most recent call last):

  File "/var/folders/m6/68zljfsj2t9_dzgpwwslj29r0000gp/T/ipykernel_2096/947403769.py", line 103, in <module>
    ax.plot(dta.index, sim_kfs.simulated_state[0],

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1632, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 312, in __call__
    yield from self._plot_args(this, kwargs)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 493, in _plot_args
    self.axes.xaxis.update_units(x)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/axis.py", line 1449, in update_units
    default = self.converter.default_units(data, self)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/category.py", line 116, in default_units
    axis.set_units(UnitData(data))

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/category.py", line 192, in __init__
    self.update(data)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/category.py", line 227, in update
    _api.check_isinstance((str, bytes), value=val)

  File "/opt/anaconda3/envs/spyder-env/lib/python3.10/site-packages/matplotlib/_api/__init__.py", line 93, in check_isinstance
    raise TypeError(

TypeError: 'value' must be an instance of str or bytes, not a tuple

Additionally, the panel is composed of about 80 countries; nonetheless, only a few appear in the same graph. I get the following graph, which worries me because it shows countries and time instead of a single time series line.

The following image is the  second one produce in point #4 Simulations based on CFA approach, MLE parameters'

The error appears in the third image of point #4

enter image description here
enter image description hereCould anyone suggest how to solve this and how to proceed up to the point 18 of his code?
Full code  is

%matplotlib inline

from importlib import reload
import numpy as np
import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt

from scipy.stats import invwishart, invgamma

#1

import pyreadstat

dtafile = 'TVP.dta'
dta, meta = pyreadstat.read_dta(dtafile)
dta.tail()

labels=list(meta.column_labels)
column=list(meta.column_names)

#  Panel data settings
year = dta.year
year = pd.Categorical(dta.year)
dta = dta.set_index([ "country", "year"])
dta["year"] = year

dta.head()

#2
# Construct a local level model for Growth rate of labor productivity
mod = sm.tsa.UnobservedComponents(dta.lp, 'llevel')

# Fit the model's parameters (sigma2_varepsilon and sigma2_eta)
# via maximum likelihood
res = mod.fit()
print(res.params)

# Create simulation smoother objects
sim_kfs = mod.simulation_smoother()              # default method is KFS
sim_cfa = mod.simulation_smoother(method='cfa')  # can specify CFA method
fa = mod.simulation_smoother(method='cfa')  # can specify CFA method

#3
nsimulations = 20
simulated_state_kfs = pd.DataFrame(
    np.zeros((mod.nobs, nsimulations)), index=dta.index)
simulated_state_cfa = pd.DataFrame(
    np.zeros((mod.nobs, nsimulations)), index=dta.index)

for i in range(nsimulations):
    # Apply KFS simulation smoothing
    sim_kfs.simulate()
    # Save the KFS simulated state
    simulated_state_kfs.iloc[:, i] = sim_kfs.simulated_state[0]

    # Apply CFA simulation smoothing
    sim_cfa.simulate()
    # Save the CFA simulated state
    simulated_state_cfa.iloc[:, i] = sim_cfa.simulated_state[0]

#4
# Plot the Growth rate of labor productivity data along with simulated trends
fig, axes = plt.subplots(2, figsize=(15, 6))

# Plot data and KFS simulations
dta.lp.plot(ax=axes[0], color='k')
axes[0].set_title('Simulations based on KFS approach, MLE parameters')
simulated_state_kfs.plot(ax=axes[0], color='C0', alpha=0.25, legend=False)

# Plot data and CFA simulations
dta.lp.plot(ax=axes[1], color='k')
axes[1].set_title('Simulations based on CFA approach, MLE parameters')
simulated_state_cfa.plot(ax=axes[1], color='C0', alpha=0.25, legend=False)

# Add a legend, clean up layout
handles, labels = axes[0].get_legend_handles_labels()
axes[0].legend(handles[:2], ['Data', 'Simulated state'])
fig.tight_layout();

#5
fig, ax = plt.subplots(figsize=(15, 3))

# Update the model's parameterization to one that attributes more
# variation in productivity growth to the observation error and so has less
# variation in the trend component
mod.update([4, 0.05])

# Plot simulations
for i in range(nsimulations):
    sim_kfs.simulate()
    ax.plot(dta.index, sim_kfs.simulated_state[0],
            color='C0', alpha=0.25, label='Simulated state')

# Plot data
dta.lp.plot(ax=ax, color='k', label='Data', zorder=-1)

# Add title, legend, clean up layout
ax.set_title('Simulations with alternative parameterization yielding a smoother trend')
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:])
fig.tight_layout();

#6
# Subset to the four variables of interest
y = dta[['lp', 'tf', 'prices', 'u', 'bu', 'ip', 'tra',
        'ext', 'dom', 'la', 'gr', 'sd', 'de',
        'fd', 'ka',]].copy()
y.columns = ['lp', 'tf', 'prices', 'u', 'bu', 'ip', 'tra',
        'ext', 'dom', 'la', 'gr', 'sd', 'de',
        'fd', 'ka',]].]

fig, ax = plt.subplots(figsize=(15, 5))
y.plot(ax=ax)
ax.set_title('Evolution of macroeconomic variables included in TVP-VAR exercise');

#7
# 1. Create a new TVPVAR class as a subclass of sm.tsa.statespace.MLEModel
class TVPVAR(sm.tsa.statespace.MLEModel):
    # Steps 2-3 are best done in the class "constructor", i.e. the __init__ method
    def __init__(self, y):
        # Create a matrix with [y_t' : y_{t-1}'] for t = 2, ..., T
        augmented = sm.tsa.lagmat(y, 1, trim='both', original='in', use_pandas=True)
        # Separate into y_t and z_t = [1 : y_{t-1}']
        p = y.shape[1]
        y_t = augmented.iloc[:, :p]
        z_t = sm.add_constant(augmented.iloc[:, p:])

        # Recall that the length of the state vector is p * (p + 1)
        k_states = p * (p + 1)
        super().__init__(y_t, exog=z_t, k_states=k_states)

        # Note that the state space system matrices default to contain zeros,
        # so we don't need to explicitly set c_t = d_t = 0.

        # Construct the design matrix Z_t
        # Notes:
        # -> self.k_endog = p is the dimension of the observed vector
        # -> self.k_states = p * (p + 1) is the dimension of the observed vector
        # -> self.nobs = T is the number of observations in y_t
        self['design'] = np.zeros((self.k_endog, self.k_states, self.nobs))
        for i in range(self.k_endog):
            start = i * (self.k_endog + 1)
            end = start + self.k_endog + 1
            self['design', i, start:end, :] = z_t.T

        # Construct the transition matrix T = I
        self['transition'] = np.eye(k_states)

        # Construct the selection matrix R = I
        self['selection'] = np.eye(k_states)

        # Step 3: Initialize the state vector as alpha_1 ~ N(0, 5I)
        self.ssm.initialize('known', stationary_cov=5 * np.eye(self.k_states))

    # Step 4. Create a method that we can call to update H and Q
    def update_variances(self, obs_cov, state_cov_diag):
        self['obs_cov'] = obs_cov
        self['state_cov'] = np.diag(state_cov_diag)

    # Finally, it can be convenient to define human-readable names for
    # each element of the state vector. These will be available in output
    @property
    def state_names(self):
        state_names = np.empty((self.k_endog, self.k_endog + 1), dtype=object)
        for i in range(self.k_endog):
            endog_name = self.endog_names[i]
            state_names[i] = (
                ['intercept.%s' % endog_name] +
                ['L1.%s->%s' % (other_name, endog_name) for other_name in self.endog_names])
        return state_names.ravel().tolist()

    # Create an instance of our TVPVAR class with our observed dataset y
mod = TVPVAR(y)

initial_obs_cov = np.cov(y.T)
initial_state_cov_diag = [0.01] * mod.k_states

# Update H and Q
mod.update_variances(initial_obs_cov, initial_state_cov_diag)

# Perform Kalman filtering and smoothing
# (the [] is just an empty list that in some models might contain
# additional parameters. Here, we don't have any additional parameters
# so we just pass an empty list)
initial_res = mod.smooth([])

#10
def plot_coefficients_by_equation(states):
    fig, axes = plt.subplots(2, 2, figsize=(15, 8))

    # The way we defined Z_t implies that the first 5 elements of the
    # state vector correspond to the first variable in y_t, which is la
    ax = axes[0, 0]
    states.iloc[:, :5].plot(ax=ax)
    ax.set_title('la')
    ax.legend()

    # The next 5 elements correspond to tf
    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title(tf')
    ax.legend();

    # The next 5 elements correspond to
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('Price')
    ax.legend()

    # The last 5 elements correspond to the U
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('U equation')
    ax.legend();

    # The next 5 elements correspond to bu
    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title('bu equation')
    ax.legend();

    # The next 5 elements correspond to ip
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('ip equation')
    ax.legend()

    # The last 5 elements correspond to the tra equation
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('tra equation')
    ax.legend();

   # The next 5 elements correspond to ex equation
    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title('ex equation')
    ax.legend();

   # The next 5 elements correspond to La equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('La equation')
    ax.legend()

  # The last 5 elements correspond to the gr
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('gr Rate equation')
    ax.legend();

  # The next 5 elements correspond to sd

    ax = axes[0, 1]
    states.iloc[:, 5:10].plot(ax=ax)
    ax.set_title('sd equation')
    ax.legend();

  # The next 5 elements correspond to de equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('debtequation')
    ax.legend()

# The last 5 elements correspond to the  fi  equation
    ax = axes[1, 1]
    states.iloc[:, 15:20].plot(ax=ax)
    ax.set_title('Fi equation')
    ax.legend();

  # The next 5 elements correspond to ka equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('ka equation')
    ax.legend()

# The next 5 elements correspond to Weighted magiority=0 equation
    ax = axes[1, 0]
    states.iloc[:, 10:15].plot(ax=ax)
    ax.set_title('Weighted magiority=0 equation')
    ax.legend()

    return ax

#11
# Here, for illustration purposes only, we plot the time-varying
# coefficients conditional on an ad-hoc parameterization

# Recall that `initial_res` contains the Kalman filtering and smoothing,
# and the `states.smoothed` attribute contains the smoothed states
plot_coefficients_by_equation(initial_res.states.smoothed);

#12
# Prior hyperparameters

# Prior for obs. cov. is inverse-Wishart(v_1^0=k + 3, S10=I)
v10 = mod.k_endog + 3
S10 = np.eye(mod.k_endog)

# Prior for state cov. variances is inverse-Gamma(v_{i2}^0 / 2 = 3, S+{i2}^0 / 2 = 0.005)
vi20 = 6
Si20 = 0.01

#13
# Gibbs sampler setup
niter = 11000
nburn = 1000

# 1. Create storage arrays
store_states = np.zeros((niter + 1, mod.nobs, mod.k_states))
store_obs_cov = np.zeros((niter + 1, mod.k_endog, mod.k_endog))
store_state_cov = np.zeros((niter + 1, mod.k_states))

# 2. Put in the initial values
store_obs_cov[0] = initial_obs_cov
store_state_cov[0] = initial_state_cov_diag
mod.update_variances(store_obs_cov[0], store_state_cov[0])

# 3. Construct posterior samplers
sim = mod.simulation_smoother(method='cfa')

#14
for i in range(niter):
    mod.update_variances(store_obs_cov[i], store_state_cov[i])
    sim.simulate()

    # 1. Sample states
    store_states[i + 1] = sim.simulated_state.T

    # 2. Simulate obs cov
    fitted = np.matmul(mod['design'].transpose(2, 0, 1), store_states[i + 1][..., None])[..., 0]
    resid = mod.endog - fitted
    store_obs_cov[i + 1] = invwishart.rvs(v10 + mod.nobs, S10 + resid.T @ resid)

    # 3. Simulate state cov variances
    resid = store_states[i + 1, 1:] - store_states[i + 1, :-1]
    sse = np.sum(resid**2, axis=0)

    for j in range(mod.k_states):
        rv = invgamma.rvs((vi20 + mod.nobs - 1) / 2, scale=(Si20 + sse[j]) / 2)
        store_state_cov[i + 1, j] = rv

 #15
 # Collect the posterior means of each time-varying coefficient
states_posterior_mean = pd.DataFrame(
    np.mean(store_states[nburn + 1:], axis=0),
    index=mod._index, columns=mod.state_names)

# Plot these means over time
plot_coefficients_by_equation(states_posterior_mean);

#16
import arviz as az

# Collect the observation error covariance parameters
az_obs_cov = az.convert_to_inference_data({
    ('Var[%s]' % mod.endog_names[i] if i == j else
     'Cov[%s, %s]' % (mod.endog_names[i], mod.endog_names[j])):
    store_obs_cov[nburn + 1:, i, j]
    for i in range(mod.k_endog) for j in range(i, mod.k_endog)})

# Plot the credible intervals
az.plot_forest(az_obs_cov, figsize=(8, 7));

#17
# Collect the state innovation variance parameters
az_state_cov = az.convert_to_inference_data({
    r'$\sigma^2$[%s]' % mod.state_names[i]: store_state_cov[nburn + 1:, i]
    for i in range(mod.k_states)})

# Plot the credible intervals
az.plot_forest(az_state_cov, figsize=(8, 7));

#18
from statsmodels.tsa.statespace.simulation_smoother import SIMULATION_STATE

sim_cfa = mod.simulation_smoother(method='cfa')
sim_kfs = mod.simulation_smoother(simulation_output=SIMULATION_STATE)

#19

# Impluse Response
ax = res.impulse_responses(10, orthogonalized=True, impulse=[1, 0]).plot(figsize=(13,3))
ax.set(xlabel='t', title='Responses to a shock to `xxxx`');

Could anyone suggest how to solve this and how to proceed up to the point 18 of his code?


问:
The image is shrinking on smaller devices
I am randomly generating quotes using an api. I want to put that quote into my topbar but when I added it and checked mobile view , In smaller quotes it shows normal but in case of larger quotes, it shrinks the profile image present at left of my topbar. So please help to solve it.

screenshot of problem

Generating Quote

```<code>const [quote,setQuote] = useState("")

   useEffect(() => {
fetch("https://type.fit/api/quotes")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    setQuote(data[Math.floor(Math.random() * 1643) + 1].text);
    console.log("Quote"+quote)
  });
   }, []);
</code>```

TopBar

```<code>     <div
    classname={`fixed w-full h-16 flex justify-between items-center transition-all duration-[400ms] ${
        showNav ? "pl-56" : ""
      }`}
    >
      <div className="pl-4 md:pl-16">
        <Bars3CenterLeftIcon
          className="h-8 w-8 text-gray-700 cursor-pointer"
          onClick={() => setShowNav(!showNav)}
        />
      </div>
      <h1 className="mx-4 text-sm">{quote}</h1>
      <div className="flex items-center pr-4 md:pr-16">
        <Popover className="relative">
          <Popover.Button className="outline-none mr-5 md:mr-8 cursor-pointer text-gray-700">
            <BellIcon className="h-6 w-6" />
          </Popover.Button>
          <Transition
            as={Fragment}
            enter="transition ease-out duration-100"
            enterFrom="transform scale-95"
            enterTo="transform scale-100"
            leave="transition ease-in duration-75"
            leaveFrom="transform scale-100"
            leaveTo="transform scale-95"
          >
            <Popover.Panel className="absolute -right-16 sm:right-4 z-50 mt-2 bg-white shadow-sm rounded max-w-xs sm:max-w-sm w-screen">
              <div className="relative p-3">
                <div className="flex justify-between item-center w-full">
                  <p className="text-gray-700 font-medium">Notifications</p>
                  <a className="text-sm text-orange-500" href="#">
                    Mark all as read
                  </a>
                </div>
                <div className="mt-4 grid gap-4 grid-cols-1 overflow-hidden">
                  <div className="flex">
                    <div className="rounded-full shrink-0 bg-green-200 h-8 w-8 flex items-center justify-center">
                      <CheckIcon className="w-4 h-4 text-green-600" />
                    </div>
                    <div className="ml-4">
                      <p className="font-medium text-gray-700">
                        Notification Title
                      </p>
                      <p className="text-sm text-gray-500 truncate">
                        Text Notification text for design
                      </p>
                    </div>
                  </div>
                  <div className="flex">
                    <div className="rounded-full shrink-0 bg-green-200 h-8 w-8 flex items-center justify-center">
                      <CheckIcon className="w-4 h-4 text-green-600" />
                    </div>
                    <div className="ml-4">
                      <p className="font-medium text-gray-700">
                        Notification Title
                      </p>
                      <p className="text-sm text-gray-500 truncate">
                        Text Notification text for design
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </Popover.Panel>
          </Transition>
        </Popover>
        <Menu as={"div"} className="relative inline-block text-left">
          <div>
            <Menu.Button
              className={"inline-flex w-full justify-center items-center"}
            >
              <picture>
                <img
                  src="/man smiling.jpg"
                  alt="Profile picture"
                  className="rounded-full h-8 md:mr-4 bottom-2 border-white shadow-sm"
                />
              </picture>
              <span className="hidden md:block font-medium text-gray-700">
                Rettson
              </span>
              <ChevronDownIcon className="ml-2 h-4 w-4 text-gray-700" />
            </Menu.Button>
          </div>
          <Transition
            as={Fragment}
            enter="transition ease-out duration-100"
            enterFrom="transform scale-95"
            enterTo="transform scale-100"
            leave="transition ease-in duration-75"
            leaveFrom="transform scale-100"
            leaveTo="transform scale-95"
          >
            <Menu.Items
              className={
                "absolute right-0 w-56 z-50 mt-2 origin-top-right bg-white rounded shadow-sm"
              }
            >
              <div className="p-1">
                <Menu.Item>
                  <Link
                    href={"#"}
                    className="flex hover:bg-orange-500 hover:text-white text-gray-700 rounded p-2 text-sm group transition-colors items-center"
                  >
                    <PencilIcon className="h-4 w-4 mr-2" />
                    Edit
                  </Link>
                </Menu.Item>
                <Menu.Item>
                  <Link
                    href={"#"}
                    className="flex hover:bg-orange-500 hover:text-white text-gray-700 rounded p-2 text-sm group transition-colors items-center"
                  >
                    <CreditCardIcon className="h-4 w-4 mr-2" />
                    Billing
                  </Link>
                </Menu.Item>
                <Menu.Item>
                  <Link
                    href={"#"}
                    className="flex hover:bg-orange-500 hover:text-white text-gray-700 rounded p-2 text-sm group transition-colors items-center"
                  >
                    <Cog8ToothIcon className="h-4 w-4 mr-2" />
                    Settings
                  </Link>
                </Menu.Item>
              </div>
            </Menu.Items>
          </Transition>
        </Menu>
      </div>
    </div>
</code>```

layout.js for showNav

```<code>import { useState, useEffect, Fragment } from "react";
import SideBar from './SideBar'
import TopBar from './TopBar'
import { Transition } from "@headlessui/react";

export default function Layout({children}) {
    const [showNav, setShowNav] = useState(true)
    const [isMobile, setIsMobile] = useState(false)

    function handleResize() {
        if (innerWidth <= 640) {
            setShowNav(false)
            setIsMobile(true)
        } else {
            setShowNav(true)
            setIsMobile(false)
        }
    }

    useEffect(() => {
        if (typeof window != undefined) {
            addEventListener("resize",handleResize)
        }

        return () => {
            removeEventListener("resize",handleResize)
        }
    }, [])

    return (
        <>
            <TopBar showNav={showNav} setShowNav={setShowNav} />
            <Transition
                as={Fragment}
                show={showNav}
                enter="transform transition duration-[400ms]"
                enterFrom="-translate-x-full"
                enterTo="translate-x-0"
                leave="transform duration-[400ms] transition ease-in-out"
                leaveFrom="translate-x-0"
                leaveTo='-translate-x-full'
            >
                <SideBar showNav={showNav} />
            </Transition>
            <main className={`pt-16 transition-all duration-[400ms] ${showNav && !isMobile ? "pl-56" : ""}`}>
                <div className="px-4 md:px-16">
                    {children}
                </div>
            </main>
        </>
    )
}```

Here profile image is shrinking when bigger quote comes

I tried changing the width of quote, but it seems to have no effect
```

Body:
I am randomly generating quotes using an api. I want to put that quote into my topbar but when I added it and checked mobile view , In smaller quotes it shows normal but in case of larger quotes, it shrinks the profile image present at left of my topbar. So please help to solve it.

screenshot of problem

Generating Quote

const [quote,setQuote] = useState("")

   useEffect(() => {
fetch("https://type.fit/api/quotes")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    setQuote(data[Math.floor(Math.random() * 1643) + 1].text);
    console.log("Quote"+quote)
  });
   }, []);

TopBar

        <Bars3CenterLeftIcon
          className="h-8 w-8 text-gray-700 cursor-pointer"
          onClick={() => setShowNav(!showNav)}
        />

{quote}

        <Popover className="relative">
          <Popover.Button className="outline-none mr-5 md:mr-8 cursor-pointer text-gray-700">
            <BellIcon className="h-6 w-6" />
          </Popover.Button>
          <Transition
            as={Fragment}
            enter="transition ease-out duration-100"
            enterFrom="transform scale-95"
            enterTo="transform scale-100"
            leave="transition ease-in duration-75"
            leaveFrom="transform scale-100"
            leaveTo="transform scale-95"
          >
            <Popover.Panel className="absolute -right-16 sm:right-4 z-50 mt-2 bg-white shadow-sm rounded max-w-xs sm:max-w-sm w-screen">

Notifications

                    Mark all as read

                      <CheckIcon className="w-4 h-4 text-green-600" />

                        Notification Title

                        Text Notification text for design

                      <CheckIcon className="w-4 h-4 text-green-600" />

                        Notification Title

                        Text Notification text for design

            </Popover.Panel>
          </Transition>
        </Popover>
        <Menu as={"div"} className="relative inline-block text-left">

            <Menu.Button
              className={"inline-flex w-full justify-center items-center"}
            >
              <picture>

              </picture>

                Rettson

              <ChevronDownIcon className="ml-2 h-4 w-4 text-gray-700" />
            </Menu.Button>

          <Transition
            as={Fragment}
            enter="transition ease-out duration-100"
            enterFrom="transform scale-95"
            enterTo="transform scale-100"
            leave="transition ease-in duration-75"
            leaveFrom="transform scale-100"
            leaveTo="transform scale-95"
          >
            <Menu.Items
              className={
                "absolute right-0 w-56 z-50 mt-2 origin-top-right bg-white rounded shadow-sm"
              }
            >

                <Menu.Item>
                  <Link
                    href={"#"}
                    className="flex hover:bg-orange-500 hover:text-white text-gray-700 rounded p-2 text-sm group transition-colors items-center"
                  >
                    <PencilIcon className="h-4 w-4 mr-2" />
                    Edit
                  </Link>
                </Menu.Item>
                <Menu.Item>
                  <Link
                    href={"#"}
                    className="flex hover:bg-orange-500 hover:text-white text-gray-700 rounded p-2 text-sm group transition-colors items-center"
                  >
                    <CreditCardIcon className="h-4 w-4 mr-2" />
                    Billing
                  </Link>
                </Menu.Item>
                <Menu.Item>
                  <Link
                    href={"#"}
                    className="flex hover:bg-orange-500 hover:text-white text-gray-700 rounded p-2 text-sm group transition-colors items-center"
                  >
                    <Cog8ToothIcon className="h-4 w-4 mr-2" />
                    Settings
                  </Link>
                </Menu.Item>

            </Menu.Items>
          </Transition>
        </Menu>

layout.js for showNav

import { useState, useEffect, Fragment } from "react";
import SideBar from './SideBar'
import TopBar from './TopBar'
import { Transition } from "@headlessui/react";

export default function Layout({children}) {
    const [showNav, setShowNav] = useState(true)
    const [isMobile, setIsMobile] = useState(false)

    function handleResize() {
        if (innerWidth <= 640) {
            setShowNav(false)
            setIsMobile(true)
        } else {
            setShowNav(true)
            setIsMobile(false)
        }
    }

    useEffect(() => {
        if (typeof window != undefined) {
            addEventListener("resize",handleResize)
        }

        return () => {
            removeEventListener("resize",handleResize)
        }
    }, [])

    return (
        <>
            <TopBar showNav={showNav} setShowNav={setShowNav} />
            <Transition
                as={Fragment}
                show={showNav}
                enter="transform transition duration-[400ms]"
                enterFrom="-translate-x-full"
                enterTo="translate-x-0"
                leave="transform duration-[400ms] transition ease-in-out"
                leaveFrom="translate-x-0"
                leaveTo='-translate-x-full'
            >
                <SideBar showNav={showNav} />
            </Transition>
            <main className={`pt-16 transition-all duration-[400ms] ${showNav && !isMobile ? "pl-56" : ""}`}>

                    {children}

        </>
    )
}```

Here profile image is shrinking when bigger quote comes

I tried changing the width of quote, but it seems to have no effect


问:
C++ problem with multithreading using "mingw.thread "
I wanted to create a program where I can call multiple threads. I started using #include <thread> but since it did not worked I followed the instructions from std::thread error (thread not member of std). Now my program looks like

```<code>#include <iostream>
#include "PATH/mingw.thread.h"

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

int main() {
    std::thread t1(task1, "Hello from thread 1");
    std::thread t1(task1, "Hello from thread 2");

}
</code>```

When I run this I get the following error in Visual Studio Code: fatal error C1189: #error:  A C++11 compiler is required!

Also when I type g++ program.cpp -o programm, I get a long text of errors.

What can I do to fix this? Many thanks in advance

Body:
I wanted to create a program where I can call multiple threads. I started using #include <thread> but since it did not worked I followed the instructions from std::thread error (thread not member of std). Now my program looks like

#include <iostream>
#include "PATH/mingw.thread.h"

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

int main() {
    std::thread t1(task1, "Hello from thread 1");
    std::thread t1(task1, "Hello from thread 2");

}

When I run this I get the following error in Visual Studio Code: fatal error C1189: #error:  A C++11 compiler is required!

Also when I type g++ program.cpp -o programm, I get a long text of errors.

What can I do to fix this? Many thanks in advance


问:
Redirect user to different path after google oauth sign in
I'm building a web app with next.js where the user either authenticate using email adresse or third party provider like Google. In my case i'm google provider with next-auth. so after the user signs in i need to check if he exists in my mongodb database using Express.js. If he exists i true as response i want to redirect him to home page, else redirect him to a web page where he has to answer question before proceeding. My question is how and where do i implement different redirects after using next-auth sign in and receiving the response?

here's my next.js auth file

```<code>import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

callbacks: {
        async signIn({ account, profile} ) {
            if (account.provider === "google") {
                await authApi
                    .signInWithGoogle({...profile})
                    .then(function (response) {
                        // here the api returns true if exists and false if not
                        // i'd like to redirect him after the response. if true go to home page
                    })
                    .catch(function (error) {
                    })
                return profile.email_verified
            }
            return true // Do different verification for other providers that don't have `email_verified`
        },

        async jwt(token, user, account, profile, isNewUser) {
            if (account) {
                const { accessToken, provider } = account;
                token.provider = provider;
                token.accessToken = accessToken;
            }
            return token;
        },

        async session(session, user) {
            if (user) {
                const { accessToken, provider } = user;
                session.provider = provider;
                session.accessToken = accessToken;
            }
            return session;
        },
    },
</code>```

my small react component

```<code>import { useSession, signIn, signOut } from 'next-auth/react'
  function ApplyAsTenant() {

    const handleOAuthSignIn = (provider) => () => signIn(provider)
    return (
         <a
            href="#"
            onClick={handleOAuthSignIn('google')}
          >
             <span className="sr-only">Register with Google</span>
            <span className="font-bold mt-0.5 ml-2">Continue with Google</span>
         </a>
    )

}
</code>```

or should i handle the redirects using the rest api provided by next-auth as mentionned here : https://next-auth.js.org/getting-started/rest-api

Please help me out, i'm really struggling to wrap my head around that.

Body:
I'm building a web app with next.js where the user either authenticate using email adresse or third party provider like Google. In my case i'm google provider with next-auth. so after the user signs in i need to check if he exists in my mongodb database using Express.js. If he exists i true as response i want to redirect him to home page, else redirect him to a web page where he has to answer question before proceeding. My question is how and where do i implement different redirects after using next-auth sign in and receiving the response?

here's my next.js auth file

import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";

callbacks: {
        async signIn({ account, profile} ) {
            if (account.provider === "google") {
                await authApi
                    .signInWithGoogle({...profile})
                    .then(function (response) {
                        // here the api returns true if exists and false if not
                        // i'd like to redirect him after the response. if true go to home page
                    })
                    .catch(function (error) {
                    })
                return profile.email_verified
            }
            return true // Do different verification for other providers that don't have `email_verified`
        },

        async jwt(token, user, account, profile, isNewUser) {
            if (account) {
                const { accessToken, provider } = account;
                token.provider = provider;
                token.accessToken = accessToken;
            }
            return token;
        },

        async session(session, user) {
            if (user) {
                const { accessToken, provider } = user;
                session.provider = provider;
                session.accessToken = accessToken;
            }
            return session;
        },
    },

my small react component

import { useSession, signIn, signOut } from 'next-auth/react'
  function ApplyAsTenant() {

    const handleOAuthSignIn = (provider) => () => signIn(provider)
    return (

             Register with Google
            Continue with Google

    )

}

or should i handle the redirects using the rest api provided by next-auth as mentionned here : https://next-auth.js.org/getting-started/rest-api

Please help me out, i'm really struggling to wrap my head around that.


问:
Why can't LocalDateTime be obtained from a feasible temporal accessor?
I am using the same pattern to both format and parse a LocalDateTime object. However, parsing the formatted string is throwing a DateTimeParseException. I created this mcve to demonstrate the issue:

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss:nn");
LocalDateTime dateTime = LocalDateTime.of(2023, 1, 12, 10, 2, 7, 0);
String formatted = formatter.format(dateTime);
System.out.println(formatted);
LocalDateTime.parse(formatted, formatter);
</code>```

The output is:

```<code>01-12-2023 10:02:07:00
Exception in thread "main" java.time.format.DateTimeParseException: Text '01-12-2023 10:02:07:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at com.nhbb.router.drawing.DrawingManager.main(DrawingManager.java:45)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more
</code>```

Looking at other answers on this site, it seems like this only should happen if a required temporal field is missing, such as year or month. All the required fields are present in the java.time.format.Parsed instance shown in the output, so why is this code not working?

Body:
I am using the same pattern to both format and parse a LocalDateTime object. However, parsing the formatted string is throwing a DateTimeParseException. I created this mcve to demonstrate the issue:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss:nn");
LocalDateTime dateTime = LocalDateTime.of(2023, 1, 12, 10, 2, 7, 0);
String formatted = formatter.format(dateTime);
System.out.println(formatted);
LocalDateTime.parse(formatted, formatter);

The output is:

01-12-2023 10:02:07:00
Exception in thread "main" java.time.format.DateTimeParseException: Text '01-12-2023 10:02:07:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at com.nhbb.router.drawing.DrawingManager.main(DrawingManager.java:45)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MicroOfSecond=0, SecondOfMinute=7, HourOfAmPm=10, MilliOfSecond=0, NanoOfSecond=0, MinuteOfHour=2},ISO resolved to 2023-01-12 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more

Looking at other answers on this site, it seems like this only should happen if a required temporal field is missing, such as year or month. All the required fields are present in the java.time.format.Parsed instance shown in the output, so why is this code not working?


问:
Creative Cloud Installer Problem after BSOD
So I installed Adobe CC, and my computer made a restore point WHILE it was installing, i got a BSOD, and had to use that restore point. not that there is an error code, its 501 The only apps that are installed are acrobat, i've looked in the directories and it seems that all the program folders are there, but their empty. I've tried to delete everything Adobe off my computer then reinstall, even registry, but no luck. Can anyone help me here?

I Deleted everything Adobe and i was expecting that to work, but nope.


问:
Parsing String Expressions in Apache Flink 16
The ExpressionParser in Flink seems to have gotten deprecated and removed in Flink 15. Is there any replacement for the same? I am trying to achieve the following.

Typically in Flink this is how you write a groupby on a TableAPI [This works]

```<code>Table counts = orders
        .groupBy($("a"))
        .select($("a"), $("b").count().as("cnt"));
</code>```

If you see above the select $("b").count().as("cnt")  is written using Java APIs and ultimately resolves to an Expression in flink.

In Flink 14 i was able to pass the expression as a String and was able to use ExpressionParser.parseExpression(expressionAsString) to convert it to Flink's Expression Object as follows.

```<code>Table counts = orders
        .groupBy("a")
        .select("a", ExpressionParser.parseExpression("count(b) as cnt"));
</code>```

What is the replacement for ExpressionParser in Flink 16?

Body:
The ExpressionParser in Flink seems to have gotten deprecated and removed in Flink 15. Is there any replacement for the same? I am trying to achieve the following.

Typically in Flink this is how you write a groupby on a TableAPI [This works]

Table counts = orders
        .groupBy($("a"))
        .select($("a"), $("b").count().as("cnt"));

If you see above the select $("b").count().as("cnt")  is written using Java APIs and ultimately resolves to an Expression in flink.

In Flink 14 i was able to pass the expression as a String and was able to use ExpressionParser.parseExpression(expressionAsString) to convert it to Flink's Expression Object as follows.

Table counts = orders
        .groupBy("a")
        .select("a", ExpressionParser.parseExpression("count(b) as cnt"));

What is the replacement for ExpressionParser in Flink 16?


问:
How can I make a query in elastic search with one space in the query?
I am making queries in kibana and am getting errors. Specifically, I want my search query to be just one space. Here is an example: request.query(" "). However, I keep getting an error where it says it there is a parsing exception. Does anyone know how to properly format a string query with one blank space properly so that no error is returned? Thank you in advance!

"query_string":{ "query":"( ) OR (* )",. This is the query. The exception is "type" : "query_shard_exception", "reason" : "Failed to parse query [( ) OR ( *)]",

I have tried using escape characters and whatnot, but it did not seem to help.


问:
removing Y values that correspond to NA values on the X axis; reordering boxplots in ggplot or base R
I am a beginner in R have a question about process in terms of plotting values; I'm not sure how much the code will help. I am trying to make a boxplot of age categories for birds (Age Categories: HY, SY, TY, ATY, and NAs), while removing the NAs so that birds without an age don't get a boxplot at all. I've been able to remove the NAs just fine in other code to get me to KnownBehAgeCategoriesWithoutNAs, but I don't know how to tell R to match up the remaining values (non-NA values) with their corresponding y values, or how to eliminate the non-corresponding Y values myself. Is my idea of how to do this all wrong?

Below is an example of what I've tried, keeping in mind that KnownBehAgeCategoriesWithoutNAs is a short vector and DR is longer at 110 values.

```<code>ggplot(clawregression_data, aes(x= KnownBehAgeCategoriesWithoutNAs, y=DR, fill=KnownBehAgeCategoriesWithoutNAs)) +
  geom_boxplot() +
  theme_classic() +
  labs(y="Display Rate", x="Known Behavioral Age Categories")+
  scale_fill_brewer(palette="BuPu")
</code>```

And this is the error I get, which I think might be because the xs and ys don't match up. There are 110 values for y (DR), and many fewer for birds with actual age categories and not just NAs.

Don't know how to automatically pick scale for object of type <data.frame>.
Defaulting to continuous.
Error in geom_boxplot():
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in check_aesthetics():
! Aesthetics must be either length 1 or the same as the data (110)
✖ Fix the following mappings: x
Run rlang::last_error() to see where the error occurred.

I have also tried the below way of removing NAs because I'd like to reorder the categories anyway, but the NA values remain in a boxplot and I get the below message

```<code>ggplot(clawregression_data, aes(x= reorder(KnownBehAgeCategories,DR,na.rm = TRUE), y=DR, fill=KnownBehAgeCategories)) +
  geom_boxplot() +
  theme_classic() +
  labs(y="Display Rate", x="Known Behavioral Age Categories")+
  scale_fill_brewer(palette="BuPu")
</code>```

Warning message:
Removed 42 rows containing non-finite values (stat_boxplot()).

Finally, I have tried reordering with the following code but it does not appear to do anything, as it does not change the output of later code.

```<code>KnownBehAgeCategories <- factor(clawregression_data$KnownBehAgeCategories, levels=c('HY', 'SY', 'TY', 'ATY', NA))
</code>```

Apologies for the double question but it seemed that removing NAs and reordering were interlinked according to some of what I've read. I'd appreciate help with any of the above.

Body:
I am a beginner in R have a question about process in terms of plotting values; I'm not sure how much the code will help. I am trying to make a boxplot of age categories for birds (Age Categories: HY, SY, TY, ATY, and NAs), while removing the NAs so that birds without an age don't get a boxplot at all. I've been able to remove the NAs just fine in other code to get me to KnownBehAgeCategoriesWithoutNAs, but I don't know how to tell R to match up the remaining values (non-NA values) with their corresponding y values, or how to eliminate the non-corresponding Y values myself. Is my idea of how to do this all wrong?

Below is an example of what I've tried, keeping in mind that KnownBehAgeCategoriesWithoutNAs is a short vector and DR is longer at 110 values.

ggplot(clawregression_data, aes(x= KnownBehAgeCategoriesWithoutNAs, y=DR, fill=KnownBehAgeCategoriesWithoutNAs)) +
  geom_boxplot() +
  theme_classic() +
  labs(y="Display Rate", x="Known Behavioral Age Categories")+
  scale_fill_brewer(palette="BuPu")

And this is the error I get, which I think might be because the xs and ys don't match up. There are 110 values for y (DR), and many fewer for birds with actual age categories and not just NAs.

Don't know how to automatically pick scale for object of type <data.frame>.
Defaulting to continuous.
Error in geom_boxplot():
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in check_aesthetics():
! Aesthetics must be either length 1 or the same as the data (110)
✖ Fix the following mappings: x
Run rlang::last_error() to see where the error occurred.

I have also tried the below way of removing NAs because I'd like to reorder the categories anyway, but the NA values remain in a boxplot and I get the below message

ggplot(clawregression_data, aes(x= reorder(KnownBehAgeCategories,DR,na.rm = TRUE), y=DR, fill=KnownBehAgeCategories)) +
  geom_boxplot() +
  theme_classic() +
  labs(y="Display Rate", x="Known Behavioral Age Categories")+
  scale_fill_brewer(palette="BuPu")

Warning message:
Removed 42 rows containing non-finite values (stat_boxplot()).

Finally, I have tried reordering with the following code but it does not appear to do anything, as it does not change the output of later code.

KnownBehAgeCategories <- factor(clawregression_data$KnownBehAgeCategories, levels=c('HY', 'SY', 'TY', 'ATY', NA))

Apologies for the double question but it seemed that removing NAs and reordering were interlinked according to some of what I've read. I'd appreciate help with any of the above.


问:
Firebase Authentication reassigned UIDs of existing users on migration to a new version of an Android app
I store user data in a Firestore document, and for the document's ID I use the user's UID provided by Firebase Authentication. So to access the user data, I call fAuth.currentUser.uid and provide the string to the query.
The old version of the app was written in Java, and recently I translated it to Kotlin, creating a new project in Android Studio for that, though it's still connected to the same Firebase project. New users register and use the app just fine. Existing users, however, can't access their data (which is crucial for the app's functionality), because the call for UID returns a different value, and the Firestore query returns a non-existing snapshot.
I use authentication with email and password. Both of them stay the same, the old users login successfully, but as soon as the app needs the user data from the database, it crashes.

I guess there is no way to get back to the previous UID, so I am just curious about what has happened. The only differences between Java and Kotlin projects that I could identify are the app's namespace and the rootProject.name variable from the settings.gradle file.
Can anyone please explain why the existing users got new UIDs?

Edit 1: I use Firebase SDK Authentication with email and password

```<code>fAuth.createUserWithEmailAndPassword(email, password)
</code>```

Edit 2: what leads up to the crash:
from a data source, the app listens to a Firestore document containing the user data, and transmits it to a repository as a flow:

```<code>fun getUserFlow(): Flow<DocumentSnapshot?> =

    if (fAuth.getUserObject() != null) {
        fStore.collection("usuarios")
            .document(fAuth.getUserObject()!!.uid)
            .snapshotAsFlow()
    } else {
        flowOf(null)
    }
</code>```

the repository collects the flow and stores the data contained in the snapshot locally, in the form of a Proto DataStore object:

```<code>private fun collectUserFlow() {
    appScope.launch {
        fStoreSource.getUserFlow()
            .catch {
                currentCoroutineContext().cancel(null)
            }
            .collect { userSnapshot ->
                updateUserData(userSnapshot)
            }
    }
}

private suspend fun updateUserData(userSnapshot: DocumentSnapshot?) {

    if (userSnapshot != null) {

        userDataStore.updateData { user ->
            user.toBuilder()
                .setNombre(userSnapshot.getString(KEY_NOMBRE))
                .setTelefono(userSnapshot.getString(KEY_TELEFONO))
                .setEmail(userSnapshot.getString(KEY_EMAIL))
                .setToken(userSnapshot.getString(KEY_TOKEN))
                .setMesa(userSnapshot.getString(KEY_MESA))
                .setIsPresent(userSnapshot.getBoolean(KEY_IS_PRESENT)!!)
                .setBonos(userSnapshot.getLong(KEY_BONOS)!!)
                .build()
        }
    }
}
</code>```

For the new users, who just downloaded the Kotlin version, the code works perfectly fine. For the existing users, who migrated from the Java version to the Kotlin version, after they logged in successfully (i.e. the transmitted flow of the userSnapshot is not null), trying to update the userDataStore produces a NullPointerException:

```<code>2023-01-13 11:17:46.312 20966-21215/com.cafeyvinowinebar.Cafe_y_Vino E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.cafeyvinowinebar.Cafe_y_Vino, PID: 20966
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
    at com.cafeyvinowinebar.cafe_y_vino_client.UserData.setNombre(UserData.java:46)
    at com.cafeyvinowinebar.cafe_y_vino_client.UserData.access$100(UserData.java:9)
    at com.cafeyvinowinebar.cafe_y_vino_client.UserData$Builder.setNombre(UserData.java:428)
    at com.cafeyvinowinebar.cafe_y_vino_client.data.repositories.UserDataRepository$updateUserData$2.invokeSuspend(UserDataRepository.kt:340)
    at com.cafeyvinowinebar.cafe_y_vino_client.data.repositories.UserDataRepository$updateUserData$2.invoke(Unknown Source:8)
    at com.cafeyvinowinebar.cafe_y_vino_client.data.repositories.UserDataRepository$updateUserData$2.invoke(Unknown Source:4)
    at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$newData$1.invokeSuspend(SingleProcessDataStore.kt:402)
    at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$newData$1.invoke(Unknown Source:8)
    at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$newData$1.invoke(Unknown Source:4)
    at kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn(Undispatched.kt:89)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:169)
    at kotlinx.coroutines.BuildersKt.withContext(Unknown Source:1)
    at androidx.datastore.core.SingleProcessDataStore.transformAndWrite(SingleProcessDataStore.kt:402)
    at androidx.datastore.core.SingleProcessDataStore.handleUpdate(SingleProcessDataStore.kt:276)
    at androidx.datastore.core.SingleProcessDataStore.access$handleUpdate(SingleProcessDataStore.kt:76)
    at androidx.datastore.core.SingleProcessDataStore$actor$3.invokeSuspend(SingleProcessDataStore.kt:242)
    at androidx.datastore.core.SingleProcessDataStore$actor$3.invoke(Unknown Source:8)
    at androidx.datastore.core.SingleProcessDataStore$actor$3.invoke(Unknown Source:4)
    at androidx.datastore.core.SimpleActor$offer$2.invokeSuspend(SimpleActor.kt:122)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
    at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@9ab40ad, Dispatchers.IO]
</code>```

Basically, the get methods called on the snapshot return null.

To understand the issue better, I edited the updateUserData() a bit:

```<code>private suspend fun updateUserData(userSnapshot: DocumentSnapshot?) {

    if (userSnapshot != null) {

        if (!userSnapshot.exists()) {

            Log.d(TAG, "updateUserData: snapshot doesn't exist!")
            Log.d(TAG, "updateUserData: snapshot's ID: ${userSnapshot.id}")
            Log.d(TAG, "updateUserData: current user's UID: ${fAuthSource.getUserObject()!!.uid}")

        } else {

            userDataStore.updateData { user ->
                user.toBuilder()
                    .setNombre(userSnapshot.getString(KEY_NOMBRE))
                    .setTelefono(userSnapshot.getString(KEY_TELEFONO))
                    .setEmail(userSnapshot.getString(KEY_EMAIL))
                    .setToken(userSnapshot.getString(KEY_TOKEN))
                    .setMesa(userSnapshot.getString(KEY_MESA))
                    .setIsPresent(userSnapshot.getBoolean(KEY_IS_PRESENT)!!)
                    .setBonos(userSnapshot.getLong(KEY_BONOS)!!)
                    .build()
            }
        }
    }
}
</code>```

And the log reads:

```<code>2023-01-13 11:28:31.744 27734-28131/com.cafeyvinowinebar.Cafe_y_Vino D/UserDataRepository: updateUserData: snapshot doesn't exist!
2023-01-13 11:28:31.744 27734-28131/com.cafeyvinowinebar.Cafe_y_Vino D/UserDataRepository: updateUserData: snapshot's ID: gLYjEBJeMwRi5LgBSgztgqF7XYg2
2023-01-13 11:28:31.744 27734-28131/com.cafeyvinowinebar.Cafe_y_Vino D/UserDataRepository: updateUserData: current user's UID: gLYjEBJeMwRi5LgBSgztgqF7XYg2
</code>```

To sum up the problem: from the Firebase Authentication the app gets the current user's UID and queries the Firstore db for the user's document, stored under their UID. But since the current UID is not the UID under which the user initially signed in and stored their data, the document's snapshot returns empty, and the user can't access their data.

Edit 3: Also it's important to add, that before I updated the app to the Kotlin version on Google Play, I lost my keystore file and had to request a new upload key. So the upload key of the Kotlin version is different from that of the Java version. Can it be the source of the issue?

Body:
I store user data in a Firestore document, and for the document's ID I use the user's UID provided by Firebase Authentication. So to access the user data, I call fAuth.currentUser.uid and provide the string to the query.
The old version of the app was written in Java, and recently I translated it to Kotlin, creating a new project in Android Studio for that, though it's still connected to the same Firebase project. New users register and use the app just fine. Existing users, however, can't access their data (which is crucial for the app's functionality), because the call for UID returns a different value, and the Firestore query returns a non-existing snapshot.
I use authentication with email and password. Both of them stay the same, the old users login successfully, but as soon as the app needs the user data from the database, it crashes.

I guess there is no way to get back to the previous UID, so I am just curious about what has happened. The only differences between Java and Kotlin projects that I could identify are the app's namespace and the rootProject.name variable from the settings.gradle file.
Can anyone please explain why the existing users got new UIDs?

Edit 1: I use Firebase SDK Authentication with email and password

fAuth.createUserWithEmailAndPassword(email, password)

Edit 2: what leads up to the crash:
from a data source, the app listens to a Firestore document containing the user data, and transmits it to a repository as a flow:

fun getUserFlow(): Flow<DocumentSnapshot?> =

    if (fAuth.getUserObject() != null) {
        fStore.collection("usuarios")
            .document(fAuth.getUserObject()!!.uid)
            .snapshotAsFlow()
    } else {
        flowOf(null)
    }

the repository collects the flow and stores the data contained in the snapshot locally, in the form of a Proto DataStore object:

private fun collectUserFlow() {
    appScope.launch {
        fStoreSource.getUserFlow()
            .catch {
                currentCoroutineContext().cancel(null)
            }
            .collect { userSnapshot ->
                updateUserData(userSnapshot)
            }
    }
}

private suspend fun updateUserData(userSnapshot: DocumentSnapshot?) {

    if (userSnapshot != null) {

        userDataStore.updateData { user ->
            user.toBuilder()
                .setNombre(userSnapshot.getString(KEY_NOMBRE))
                .setTelefono(userSnapshot.getString(KEY_TELEFONO))
                .setEmail(userSnapshot.getString(KEY_EMAIL))
                .setToken(userSnapshot.getString(KEY_TOKEN))
                .setMesa(userSnapshot.getString(KEY_MESA))
                .setIsPresent(userSnapshot.getBoolean(KEY_IS_PRESENT)!!)
                .setBonos(userSnapshot.getLong(KEY_BONOS)!!)
                .build()
        }
    }
}

For the new users, who just downloaded the Kotlin version, the code works perfectly fine. For the existing users, who migrated from the Java version to the Kotlin version, after they logged in successfully (i.e. the transmitted flow of the userSnapshot is not null), trying to update the userDataStore produces a NullPointerException:

2023-01-13 11:17:46.312 20966-21215/com.cafeyvinowinebar.Cafe_y_Vino E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
Process: com.cafeyvinowinebar.Cafe_y_Vino, PID: 20966
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
    at com.cafeyvinowinebar.cafe_y_vino_client.UserData.setNombre(UserData.java:46)
    at com.cafeyvinowinebar.cafe_y_vino_client.UserData.access$100(UserData.java:9)
    at com.cafeyvinowinebar.cafe_y_vino_client.UserData$Builder.setNombre(UserData.java:428)
    at com.cafeyvinowinebar.cafe_y_vino_client.data.repositories.UserDataRepository$updateUserData$2.invokeSuspend(UserDataRepository.kt:340)
    at com.cafeyvinowinebar.cafe_y_vino_client.data.repositories.UserDataRepository$updateUserData$2.invoke(Unknown Source:8)
    at com.cafeyvinowinebar.cafe_y_vino_client.data.repositories.UserDataRepository$updateUserData$2.invoke(Unknown Source:4)
    at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$newData$1.invokeSuspend(SingleProcessDataStore.kt:402)
    at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$newData$1.invoke(Unknown Source:8)
    at androidx.datastore.core.SingleProcessDataStore$transformAndWrite$newData$1.invoke(Unknown Source:4)
    at kotlinx.coroutines.intrinsics.UndispatchedKt.startUndispatchedOrReturn(Undispatched.kt:89)
    at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:169)
    at kotlinx.coroutines.BuildersKt.withContext(Unknown Source:1)
    at androidx.datastore.core.SingleProcessDataStore.transformAndWrite(SingleProcessDataStore.kt:402)
    at androidx.datastore.core.SingleProcessDataStore.handleUpdate(SingleProcessDataStore.kt:276)
    at androidx.datastore.core.SingleProcessDataStore.access$handleUpdate(SingleProcessDataStore.kt:76)
    at androidx.datastore.core.SingleProcessDataStore$actor$3.invokeSuspend(SingleProcessDataStore.kt:242)
    at androidx.datastore.core.SingleProcessDataStore$actor$3.invoke(Unknown Source:8)
    at androidx.datastore.core.SingleProcessDataStore$actor$3.invoke(Unknown Source:4)
    at androidx.datastore.core.SimpleActor$offer$2.invokeSuspend(SimpleActor.kt:122)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.internal.LimitedDispatcher.run(LimitedDispatcher.kt:42)
    at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:95)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
    Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [StandaloneCoroutine{Cancelling}@9ab40ad, Dispatchers.IO]

Basically, the get methods called on the snapshot return null.

To understand the issue better, I edited the updateUserData() a bit:

private suspend fun updateUserData(userSnapshot: DocumentSnapshot?) {

    if (userSnapshot != null) {

        if (!userSnapshot.exists()) {

            Log.d(TAG, "updateUserData: snapshot doesn't exist!")
            Log.d(TAG, "updateUserData: snapshot's ID: ${userSnapshot.id}")
            Log.d(TAG, "updateUserData: current user's UID: ${fAuthSource.getUserObject()!!.uid}")

        } else {

            userDataStore.updateData { user ->
                user.toBuilder()
                    .setNombre(userSnapshot.getString(KEY_NOMBRE))
                    .setTelefono(userSnapshot.getString(KEY_TELEFONO))
                    .setEmail(userSnapshot.getString(KEY_EMAIL))
                    .setToken(userSnapshot.getString(KEY_TOKEN))
                    .setMesa(userSnapshot.getString(KEY_MESA))
                    .setIsPresent(userSnapshot.getBoolean(KEY_IS_PRESENT)!!)
                    .setBonos(userSnapshot.getLong(KEY_BONOS)!!)
                    .build()
            }
        }
    }
}

And the log reads:

2023-01-13 11:28:31.744 27734-28131/com.cafeyvinowinebar.Cafe_y_Vino D/UserDataRepository: updateUserData: snapshot doesn't exist!
2023-01-13 11:28:31.744 27734-28131/com.cafeyvinowinebar.Cafe_y_Vino D/UserDataRepository: updateUserData: snapshot's ID: gLYjEBJeMwRi5LgBSgztgqF7XYg2
2023-01-13 11:28:31.744 27734-28131/com.cafeyvinowinebar.Cafe_y_Vino D/UserDataRepository: updateUserData: current user's UID: gLYjEBJeMwRi5LgBSgztgqF7XYg2

To sum up the problem: from the Firebase Authentication the app gets the current user's UID and queries the Firstore db for the user's document, stored under their UID. But since the current UID is not the UID under which the user initially signed in and stored their data, the document's snapshot returns empty, and the user can't access their data.

Edit 3: Also it's important to add, that before I updated the app to the Kotlin version on Google Play, I lost my keystore file and had to request a new upload key. So the upload key of the Kotlin version is different from that of the Java version. Can it be the source of the issue?