问:
Connect to Firebird DB via ODBC in R
I am trying to connect to Firebird DB via ODBC. I have R Studio Server installed on a Linux virtual machine. I use dbConnect. This connection works fine on my local machine. However, on the server I get an error:

Error: nanodbc/nanodbc.cpp:1021: 00000: [ODBC Firebird
Driver]connection shutdown  [ODBC Firebird Driver]Invalid connection
string attribute

My dbconnect:

```<code>library(DBI)
library(odbc)
dbConnect(odbc::odbc(),
              Driver = 'Firebird',
              Server = 'xxx',
              Database = 'xx.x.x.xxx:/xxx.gdb',
              Uid = 'SYSDBA',
              Pwd = 'masterkey',
              encoding = 'cp1250')
</code>```

Sometimes I manage to connect, but then I have to reset the R session every time.

> odbc::odbcListDrivers()
      name   attribute                          value
1 Firebird Description InterBase/Firebird ODBC Driver
2 Firebird      Driver          /usr/lib/libOdbcFb.so
3 Firebird       Setup         /usr/lib/libOdbcFbS.so
4 Firebird   Threading                              1
5 Firebird   FileUsage                              1
6 Firebird   CPTimeout                           <NA>
7 Firebird     CPReuse                           <NA>
```
<p>My Sys.info:</p>
<pre class="lang-none prettyprint-override"><code>> Sys.info()[["machine"]]
[1] "x86_64"
> Sys.info()[["sysname"]]
[1] "Linux"
> Sys.info()[["version"]]
[1] "#59-Ubuntu SMP Mon Oct 17 18:53:30 UTC 2022"
</code>```

Title: Connect to Firebird DB via ODBC in R

Body:
I am trying to connect to Firebird DB via ODBC. I have R Studio Server installed on a Linux virtual machine. I use dbConnect. This connection works fine on my local machine. However, on the server I get an error:

Error: nanodbc/nanodbc.cpp:1021: 00000: [ODBC Firebird
Driver]connection shutdown  [ODBC Firebird Driver]Invalid connection
string attribute

My dbconnect:

library(DBI)
library(odbc)
dbConnect(odbc::odbc(),
              Driver = 'Firebird',
              Server = 'xxx',
              Database = 'xx.x.x.xxx:/xxx.gdb',
              Uid = 'SYSDBA',
              Pwd = 'masterkey',
              encoding = 'cp1250')

Sometimes I manage to connect, but then I have to reset the R session every time.

> odbc::odbcListDrivers()
      name   attribute                          value
1 Firebird Description InterBase/Firebird ODBC Driver
2 Firebird      Driver          /usr/lib/libOdbcFb.so
3 Firebird       Setup         /usr/lib/libOdbcFbS.so
4 Firebird   Threading                              1
5 Firebird   FileUsage                              1
6 Firebird   CPTimeout                           <NA>
7 Firebird     CPReuse                           <NA>

My Sys.info:

> Sys.info()[["machine"]]
[1] "x86_64"
> Sys.info()[["sysname"]]
[1] "Linux"
> Sys.info()[["version"]]
[1] "#59-Ubuntu SMP Mon Oct 17 18:53:30 UTC 2022"


来源: stackexchange

问:
How to get the total number of count in acf field
```<code><p class="showitem">Showing
    <span>
        <?php if ( have_rows( 'packaging', 'options' ) ) : ?>
            <?php while ( have_rows( 'packaging', 'options' ) ) : the_row(); ?>
                <?php $count = count( get_sub_field( 'content' ) ); ?>
            <?php endwhile; ?>
        <?php endif; ?>
        <?php echo $count; ?>
    </span>
items</p>
</code>```

I need output Showing 20 items. But it shows Showing 1 items

I tried to give inside the loop but it shows 1 20 times

ContentLicense: CC BY-SA 4.0

Body:
Showing

        <?php if ( have_rows( 'packaging', 'options' ) ) : ?>
            <?php while ( have_rows( 'packaging', 'options' ) ) : the_row(); ?>
                <?php $count = count( get_sub_field( 'content' ) ); ?>
            <?php endwhile; ?>
        <?php endif; ?>
        <?php echo $count; ?>

items

I need output Showing 20 items. But it shows Showing 1 items

I tried to give inside the loop but it shows 1 20 times


问:
Am I able to apply code changes while debugging using VS Code?
When using Visual Studio I am able to apply code changes and continue debugging. As far as I can tell this feature doesn't exist in VS Code, which means a lot of restarts and wasted time.

Is there a way to be able to add and execute new lines of code without restarting in VS Code?


问:
Pandas Dataframe transformation from row to column
I would need assistance in transforming a Data-frame. the structure is currently like this:

id
date
color
value

0
25.05.20
Red
245

0
25.05.20
Blue
245

0
25.05.20
Orange
220

0
25.05.20
Red
230

0
26.05.20
Orange
220

0
26.05.20
Red
230

1
25.05.20
Red
245

1
25.05.20
Blue
245

1
25.05.20
Orange
220

1
25.05.20
Red
230

1
26.05.20
Orange
220

1
26.05.20
Red
230

In the end the dataframe should look like this:

id
date
Red
Blue
Orange

0
25.05.20
245
245
220

0
26.05.20
230
0
220

1
25.05.20
245
245
220

1
26.05.20
230
0
220

I want to display the colors in columns for each ID and enter the values there. Furthermore, if several values have been entered for a color on one day, only the highest value should be taken.
If no value is available for a color on the date, a 0 should be entered.

Thanks in advance


问:
How to avoid target "leaking" into the training process with PyTorch's TimeSeriesDataSet and TemporalFusionTransformer?
Basically, I have a time series dataset that wants to predict the price 14 days from now. There are dozens of features and everything is being trained with TemporalFusionTransformer (PyTorch version).

Originally, I trained to predict price every day for the next 14 days, however these gave fairly poor results. So, I want to switch to predict ONLY the price 14 days from now. For a conventional dataset I would just lag the price variable 14 days (dataset['price_lagged'] = dataset['price'].shift(-13) and set max_prediction_length to 1 to predict the 14th day) and set this as a target variable.

Current code that still predicts well (and it shouldn't):

```<code>training = TimeSeriesDataSet(
    dataset[lambda x: x.day <= training_cutoff],
    time_idx="day",
    target="price_lagged",
    group_ids=["group_id"]
    min_encoder_length=max_encoder_length ,
    max_encoder_length=max_encoder_length,
    max_prediction_length=max_prediction_length,
    static_categoricals=[],
    static_reals=[],
    time_varying_known_categoricals=[],
    time_varying_unknown_reals=[
        #I removed EVERYTHING from here
    ],
    time_varying_unknown_categoricals=[
],
    time_varying_known_reals=[
],
    target_normalizer=EncoderNormalizer(),
    #lags=lags,
    add_relative_time_idx=True,
    allow_missing_timesteps=False,
    add_target_scales=True,
)
</code>```

However, the model seems to use the target as a variable as well. I can see this if I literally remove every other feature, I still get a fairly good prediction. How can I explicitly have the model NOT use the target as a (obvious) feature? Can TFT work like this?

Body:
Basically, I have a time series dataset that wants to predict the price 14 days from now. There are dozens of features and everything is being trained with TemporalFusionTransformer (PyTorch version).

Originally, I trained to predict price every day for the next 14 days, however these gave fairly poor results. So, I want to switch to predict ONLY the price 14 days from now. For a conventional dataset I would just lag the price variable 14 days (dataset['price_lagged'] = dataset['price'].shift(-13) and set max_prediction_length to 1 to predict the 14th day) and set this as a target variable.

Current code that still predicts well (and it shouldn't):

training = TimeSeriesDataSet(
    dataset[lambda x: x.day <= training_cutoff],
    time_idx="day",
    target="price_lagged",
    group_ids=["group_id"]
    min_encoder_length=max_encoder_length ,
    max_encoder_length=max_encoder_length,
    max_prediction_length=max_prediction_length,
    static_categoricals=[],
    static_reals=[],
    time_varying_known_categoricals=[],
    time_varying_unknown_reals=[
        #I removed EVERYTHING from here
    ],
    time_varying_unknown_categoricals=[
],
    time_varying_known_reals=[
],
    target_normalizer=EncoderNormalizer(),
    #lags=lags,
    add_relative_time_idx=True,
    allow_missing_timesteps=False,
    add_target_scales=True,
)

However, the model seems to use the target as a variable as well. I can see this if I literally remove every other feature, I still get a fairly good prediction. How can I explicitly have the model NOT use the target as a (obvious) feature? Can TFT work like this?


问:
CI4 & WordPress HTACCESS Redirects
I have a CodeIgniter 4 installation and a WordPress one within the same public directory.

If I set the permalinks to anything but the default ones in WordPress I start getting "redirected to many times" error.

I believe I need to exclude the CI4 htaccess file from the WordPress one, however this is were I and struggling. I have tried various things but still getting the same errors.

The htaccess for the CI4 looks like

Any help would be much appreciated

```<code> Options +FollowSymlinks RewriteEngine On
# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
RewriteBase /

 #RewriteRule ^(WP)($|/) - [L]
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</code>```

I have

```<code>RewriteRule ^(wordpress)($|/) - [L]
</code>```

But this did not solve the problem

Title: CI4 & WordPress HTACCESS Redirects

Body:
I have a CodeIgniter 4 installation and a WordPress one within the same public directory.

If I set the permalinks to anything but the default ones in WordPress I start getting "redirected to many times" error.

I believe I need to exclude the CI4 htaccess file from the WordPress one, however this is were I and struggling. I have tried various things but still getting the same errors.

The htaccess for the CI4 looks like

Any help would be much appreciated

 Options +FollowSymlinks RewriteEngine On
# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
RewriteBase /

 #RewriteRule ^(WP)($|/) - [L]
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]

# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

I have

RewriteRule ^(wordpress)($|/) - [L]

But this did not solve the problem


问:
Possible to Stringize a Pandas Expression?
Is it possible to stringize a Pandas expression? For example, convert df['Date'].ge('2022') to a string of "df['Date'].ge('2022')". Sort of the inverse of query(). I want to show the specified filter in the title of plots.


问:
Passing Database Password to Dataproc PySpark batch job
I want to create a pyspark job, and I want to have two separate environments: sandbox and production. Based on the environment it runs in, the script should connect either to the sandbox or production postgres database that runs on Google Cloud SQL.

For all the other functionalities required (things that run in Cloud Functions or Cloud Run) I managed to separate the environments using pydantic settings with the following class:

class Settings(BaseSettings):
    db_user: str = Field()
    db_pass: str = Field()
    db_name: str = Field()
    db_host: str = Field()

    class Config:
        env_file = ".env"
```

These values are passed in as environment variables through the Secret Manager, so only requests from within Google Cloud Datacenters access the sensible data. I did not find a suitable way to pass secrets to a Dataproc batch job, the best alternative I found are properties (https://cloud.google.com/dataproc-serverless/docs/concepts/properties), that become environment variables.

Functionally I can simply set all the variables I need using the properties, but it would mean sending all my database information over the network from my computer where I launch the job to GCP, which looks like a security risk.

Is there a better way to separate sandbox and production environments in dataproc, or can I somehow access secrets when deploying a dataproc batch job?

Body:
I want to create a pyspark job, and I want to have two separate environments: sandbox and production. Based on the environment it runs in, the script should connect either to the sandbox or production postgres database that runs on Google Cloud SQL.

For all the other functionalities required (things that run in Cloud Functions or Cloud Run) I managed to separate the environments using pydantic settings with the following class:

class Settings(BaseSettings):
    db_user: str = Field()
    db_pass: str = Field()
    db_name: str = Field()
    db_host: str = Field()

    class Config:
        env_file = ".env"

These values are passed in as environment variables through the Secret Manager, so only requests from within Google Cloud Datacenters access the sensible data. I did not find a suitable way to pass secrets to a Dataproc batch job, the best alternative I found are properties (https://cloud.google.com/dataproc-serverless/docs/concepts/properties), that become environment variables.

Functionally I can simply set all the variables I need using the properties, but it would mean sending all my database information over the network from my computer where I launch the job to GCP, which looks like a security risk.

Is there a better way to separate sandbox and production environments in dataproc, or can I somehow access secrets when deploying a dataproc batch job?


问:
error: React is not defined, when i try deploying to github pages
enter image description here

i get this error, can someone help me?

ive used the install gh-pages, and it publiches but dosnt work


问:
My Vscode terminal is not doing anything, there are no errors it just isn't doing anything
Very simply my Vscode terminal isn't doing anything it's there but it's not doing anything

Vscode terminal

I don't get any errors or anything it's just not doing anything.

I've tried running multiple diffrent files, I've restarted my computer and Vscode.
Not only that but a project i was working on just deleted.
How do I fix this


问:
PL/SQL how to count values if one variable inside other variable (SQLDeveloper)
I have a person_data table:
person_data table

Firstly I tried to find how many persons were born in each year (Person birth year is substr(id,2,2)):

```<code>`set serveroutput on
declare
max_year CONSTANT integer := 84;
min_year CONSTANT integer := 82;
birthyear integer;
persons integer;
begin
FOR birthyear IN min_year .. max_year
LOOP
SELECT count(*) into persons FROM person_data
WHERE substr(id,2,2)=birthyear;
dbms_output.put_line('19'||birthyear||'. year were born '||persons||);
END LOOP;
end;`
</code>```

But now I have to find how many persosn were born in each year-month: 1982 first month ...; 1982 second month... etc)
Person birth year is substr(id,2,2) and birth month is substr(id,4,2).
Does anyone know how to do that?

Thanks in advance!

Body:
I have a person_data table:
person_data table

Firstly I tried to find how many persons were born in each year (Person birth year is substr(id,2,2)):

`set serveroutput on
declare
max_year CONSTANT integer := 84;
min_year CONSTANT integer := 82;
birthyear integer;
persons integer;
begin
FOR birthyear IN min_year .. max_year
LOOP
SELECT count(*) into persons FROM person_data
WHERE substr(id,2,2)=birthyear;
dbms_output.put_line('19'||birthyear||'. year were born '||persons||);
END LOOP;
end;`

But now I have to find how many persosn were born in each year-month: 1982 first month ...; 1982 second month... etc)
Person birth year is substr(id,2,2) and birth month is substr(id,4,2).
Does anyone know how to do that?

Thanks in advance!


问:
Firestore database creation lock on GCP project restore
We have restored a GCP project that had several resources associated to it. Among those there was a Firestore database. After restoring the project and verified everything, I noticed that the database was not shown in the console, it asks me to create a new one, which is strange since in theory any resource should be kept if restored within 30 days:

I tried to recreate the database and I receive an error that a database already exists for this project:

It seems like a big GCP issue. Has anyone experienced this before?


问:
Next.js 13 all pages are server-side render bug
All pages in next 13 (experimental app.dir) are server side rendered λ.

Doesn't matter if there is any fetching inside them.

Only slug pages with generateStaticParams are automatically generated as static.

For example:

app/test/page.tsx

```<code>
const page = () => {
  return <h1> test page</h1>;
};

export default page;

</code>```

Output after running npm run build

```<code>Route (app)                                   Size     First Load JS
┌ λ /                                         0 B                0 B
├ λ /about-me                                 172 B          71.6 kB
├ λ /backend                                  189 B          89.3 kB
├ λ /backend/[post]                           139 B          66.8 kB
├ λ /frontend                                 189 B          89.3 kB
├ ● /frontend/[post]                          1.4 kB         68.1 kB
├   ├ /frontend/post1
├   ├ /frontend/post2
├   └ /frontend/post3
└ λ /test                                     139 B          66.8 kB
+ First Load JS shared by all                 66.7 kB
  ├ chunks/17-07dd3c6388d7c9b8.js             64 kB
  ├ chunks/main-app-f7991bdf5a7d528d.js       200 B
  └ chunks/webpack-25c60cf3849dbdaa.js        2.52 kB

Route (pages)                                 Size     First Load JS
┌ ○ /404                                      179 B          81.5 kB
└ λ /api/hello                                0 B            81.3 kB
+ First Load JS shared by all                 81.3 kB
  ├ chunks/main-c47fccc8bf0082d4.js           78.6 kB
  ├ chunks/pages/_app-9f5490aa3d56632f.js     192 B
  └ chunks/webpack-25c60cf3849dbdaa.js        2.52 kB

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)
</code>```

next.config.js

```<code>/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    appDir: true,
    fontLoaders: [
      {
        loader: '@next/font/google',
        options: {
          subsets: ['latin'],
        },
      },
    ],
  },
  images: {
    domains: ['media.graphassets.com', 'avatars.githubusercontent.com'],
  },
};

module.exports = nextConfig;

</code>```

layout.tsx

```<code>import { Roboto } from '@next/font/google';
import { Footer } from './components/footer/Footer';
import { Nav } from './components/nav/Nav';
import { Providers } from './providers';
import './styles/globals.scss';

const font = Roboto({
  weight: ['400', '500', '700'],
});

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html className={font.className} lang="en">
      <head></head>
      <body>
        <Providers>
          <Nav />
          {children}
          <Footer />
        </Providers>
      </body>
    </html>
  );
}
</code>```

Dont understand why pages are not ssg by default as it should be .
I'm trying to make a simple blog using next.js, graphQL and hygraphCMS.
In blog everything that can should be server side generated but my project is broken.

Body:
All pages in next 13 (experimental app.dir) are server side rendered λ.

Doesn't matter if there is any fetching inside them.

Only slug pages with generateStaticParams are automatically generated as static.

For example:

app/test/page.tsx

const page = () => {
  return
 test page
;
};

export default page;

Output after running npm run build

Route (app)                                   Size     First Load JS
┌ λ /                                         0 B                0 B
├ λ /about-me                                 172 B          71.6 kB
├ λ /backend                                  189 B          89.3 kB
├ λ /backend/[post]                           139 B          66.8 kB
├ λ /frontend                                 189 B          89.3 kB
├ ● /frontend/[post]                          1.4 kB         68.1 kB
├   ├ /frontend/post1
├   ├ /frontend/post2
├   └ /frontend/post3
└ λ /test                                     139 B          66.8 kB
+ First Load JS shared by all                 66.7 kB
  ├ chunks/17-07dd3c6388d7c9b8.js             64 kB
  ├ chunks/main-app-f7991bdf5a7d528d.js       200 B
  └ chunks/webpack-25c60cf3849dbdaa.js        2.52 kB

Route (pages)                                 Size     First Load JS
┌ ○ /404                                      179 B          81.5 kB
└ λ /api/hello                                0 B            81.3 kB
+ First Load JS shared by all                 81.3 kB
  ├ chunks/main-c47fccc8bf0082d4.js           78.6 kB
  ├ chunks/pages/_app-9f5490aa3d56632f.js     192 B
  └ chunks/webpack-25c60cf3849dbdaa.js        2.52 kB

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    appDir: true,
    fontLoaders: [
      {
        loader: '@next/font/google',
        options: {
          subsets: ['latin'],
        },
      },
    ],
  },
  images: {
    domains: ['media.graphassets.com', 'avatars.githubusercontent.com'],
  },
};

module.exports = nextConfig;

layout.tsx

import { Roboto } from '@next/font/google';
import { Footer } from './components/footer/Footer';
import { Nav } from './components/nav/Nav';
import { Providers } from './providers';
import './styles/globals.scss';

const font = Roboto({
  weight: ['400', '500', '700'],
});

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (

        <Providers>

          {children}

        </Providers>

  );
}

Dont understand why pages are not ssg by default as it should be .
I'm trying to make a simple blog using next.js, graphQL and hygraphCMS.
In blog everything that can should be server side generated but my project is broken.


问:
chrome.tabCapture unavailable in MV3's new offscreen API
Our extension uses tabCapture to record the sound of a tab. In MV3, chrome.tabCapture is only available in foreground pages (like popups), which makes the API useless for recording anything in the tab since it can't be kept open.

There's the current hack which opens an extension page in a new Tab while recording, to satisfy both the keep-alive and foreground constraints in the API, but that is less than ideal as it requires tabs pop-in and pop-out of existence without user interaction so it makes for a terrible user experience.

Then there's the new chrome.offscreen API which had this capturing use case as one of its main highlighted use cases in the initial draft request by Devlin Cronin here. Now, the offscreen API is enabled in 109 beta ready to be deployed in production on Jan 10th 2023 and this use case appears ignored. chrome.tabCapture is not exposed to the offscreen document.

In the extension service worker:

```<code>chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    chrome.offscreen.hasDocument().then(function(has) {
        if (!has) {
            chrome.offscreen.createDocument({
                justification: 'record audio',
                reasons: [chrome.offscreen.Reason.USER_MEDIA],
                url: chrome.runtime.getURL('record.html'),
            });
        }
    });
});
</code>```

In the offscreen document's JS script:

```<code>window.addEventListener("load", () => {
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        console.log(chrome.tabCapture); // **this is always undefined**
    });
});
</code>```

So now the question. Is there another way to record the current tab audio that isn't listed above? Not talking about recording the user's mic with getUserMedia and not involving desktopCapture which brings up the nasty popup. The ideal solution would still involve tabCapture. But how?

Body:
Our extension uses tabCapture to record the sound of a tab. In MV3, chrome.tabCapture is only available in foreground pages (like popups), which makes the API useless for recording anything in the tab since it can't be kept open.

There's the current hack which opens an extension page in a new Tab while recording, to satisfy both the keep-alive and foreground constraints in the API, but that is less than ideal as it requires tabs pop-in and pop-out of existence without user interaction so it makes for a terrible user experience.

Then there's the new chrome.offscreen API which had this capturing use case as one of its main highlighted use cases in the initial draft request by Devlin Cronin here. Now, the offscreen API is enabled in 109 beta ready to be deployed in production on Jan 10th 2023 and this use case appears ignored. chrome.tabCapture is not exposed to the offscreen document.

In the extension service worker:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    chrome.offscreen.hasDocument().then(function(has) {
        if (!has) {
            chrome.offscreen.createDocument({
                justification: 'record audio',
                reasons: [chrome.offscreen.Reason.USER_MEDIA],
                url: chrome.runtime.getURL('record.html'),
            });
        }
    });
});

In the offscreen document's JS script:

window.addEventListener("load", () => {
    chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
        console.log(chrome.tabCapture); // **this is always undefined**
    });
});

So now the question. Is there another way to record the current tab audio that isn't listed above? Not talking about recording the user's mic with getUserMedia and not involving desktopCapture which brings up the nasty popup. The ideal solution would still involve tabCapture. But how?


问:
Mobility management function
I am not sure if it is the right community here for this question.

I am looking for information on what mobility management function exactly means. ( in the context of dynamic reconfiguration of management function, organic networking, authentication functionality, QoS, and network architecture)

For me,  as someone who spent almost whole life in math, function means an expression, rule, or law that defines a relationship between one variable and another variable, an equation with x, y,z
In network theory,  it seems, it has a different meaning.

Can someone explain what network function for mobility management means or look like?

I want to understand what the Mobility management function in network architecture is. Maybe someone of you has a resource where I can find info and study this question... it would be helpful for me.

Title: Mobility management function


问:
AIOHTTP Errors with SSL
I am testing a simple AIOHTTP server inspired by this documentation and this answer:

```<code>async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    print(text)
    return web.Response(text=text)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])
ssl_context: SSLContext = create_default_context(purpose=Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(certfile=<my cert file>)

if __name__ == '__main__':
    web.run_app(app, ssl_context=ssl_context)
</code>```

and I keep getting this error after a while:

```<code>Exception in callback _ProactorBasePipeTransport._call_connection_lost(None)
handle: <Handle _ProactorBasePipeTransport._call_connection_lost(None)>
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Program Files\Python310\lib\asyncio\proactor_events.py", line 162, in _call_connection_lost
    self._sock.shutdown(socket.SHUT_RDWR)
ConnectionResetError: [WinError 10054] Une connexion existante a dû être fermée par l’hôte distant
</code>```

The error doesn't appear when I do not use SSL.

Note that everything else seems to work fine:

```<code>======== Running on https://0.0.0.0:8443 ========
(Press CTRL+C to quit)
Hello, Anonymous
Hello, favicon.ico
</code>```

Any insight would be much appreciated, thanks.

Title: AIOHTTP Errors with SSL

Body:
I am testing a simple AIOHTTP server inspired by this documentation and this answer:

async def handle(request):
    name = request.match_info.get('name', "Anonymous")
    text = "Hello, " + name
    print(text)
    return web.Response(text=text)

app = web.Application()
app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])
ssl_context: SSLContext = create_default_context(purpose=Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(certfile=<my cert file>)

if __name__ == '__main__':
    web.run_app(app, ssl_context=ssl_context)

and I keep getting this error after a while:

Exception in callback _ProactorBasePipeTransport._call_connection_lost(None)
handle: <Handle _ProactorBasePipeTransport._call_connection_lost(None)>
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Program Files\Python310\lib\asyncio\proactor_events.py", line 162, in _call_connection_lost
    self._sock.shutdown(socket.SHUT_RDWR)
ConnectionResetError: [WinError 10054] Une connexion existante a dû être fermée par l’hôte distant

The error doesn't appear when I do not use SSL.

Note that everything else seems to work fine:

======== Running on https://0.0.0.0:8443 ========
(Press CTRL+C to quit)
Hello, Anonymous
Hello, favicon.ico

Any insight would be much appreciated, thanks.


问:
How do I apply permanent style changes to a data frame?
I'm trying to apply permanent style changes to my data frame (by using inplace=True) after using the dataset.style.format() function because I want adding zeros to some columns.

I put inplace=True inside the format function:

dataset.style.format(
    {
        'Size': '{:,.1f}',
        'RetailPrice': '{:,.2f}'
    },
    inplace=True
)
```
<p>But I get the following error:</p>
<pre class="lang-py prettyprint-override"><code>TypeError: format() got an unexpected keyword argument 'inplace'
</code>```

Is there any way around this?

I was expecting the inplace=True to work so that it would apply permanent changes to the data frame, and then I could export the CSV.

Body:
I'm trying to apply permanent style changes to my data frame (by using inplace=True) after using the dataset.style.format() function because I want adding zeros to some columns.

I put inplace=True inside the format function:

dataset.style.format(
    {
        'Size': '{:,.1f}',
        'RetailPrice': '{:,.2f}'
    },
    inplace=True
)

But I get the following error:

TypeError: format() got an unexpected keyword argument 'inplace'

Is there any way around this?

I was expecting the inplace=True to work so that it would apply permanent changes to the data frame, and then I could export the CSV.


问:
Update to FederatedDatabaseInstance MongoDB from DBeaver
I created a Data Federation Database Instance like below:

I can connect to it from DBeaver, but when I tried to insert/update the data, it cause an error:

How can I update/insert mongodb from DBeaver?


问:
Storing PDF in RamDisk vs MemoryMappedFile
I am using a library to create a PDF file from HTML, then I print that file and delete it from disk. The issue is, we don't want anything stored on disk, not even temporarily. I thought about using some kind of RamDisk, but I see MemoryMappedFile thrown around everywhere. I looked into it, but I don't think that provides the functionality I want since the file should already exist on disk before using it in a MemoryMappedFile.

My question is: Is my assumption true about the file needing to be on disk FIRST before using it in a MemoryMappedFile? IS there a way to create a MemoryMappedFile and access it using a virtual path without it existing on disk?

In case MemoryMappedFile doesn't work, what library can I use to create a virtual RamDisk with C#? It will only be storing 1 file at a time.


问:
How to use more than one extension
```<code>import os
import glob
import re

html = ""
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( f"Folder Name  :{nmFolders[-2]}" )
for X in {nmFolders[-2]}:

    for file in sorted(glob.glob( os.path.join('*.webp') ),key=lambda x:float(re.findall("([0-9]+?)\.webp",x)[0])):
         html += f"<title> {X} </title><body><div align='center'><div class='card'><p><h3><font>{X}</font></h3></p><div class='mdl-card__actions mdl-card--border'><p></p></div></div><div align='center'><img src ='{os.path.realpath(file)}'/>"

for X in {nmFolders[-2]}:
    with open(f"{X}.html","w", encoding="utf-8") as outputfile:
        outputfile.write(html)

os.startfile(f"{X}.html")
</code>```

This code create html with single extension (.webp) with numerical order but can't access multiple extension(.jpg,.png)

```<code>for file in sorted(glob.glob( os.path.join('*.webp') ),key=lambda x:float(re.findall("([0-9]+?)\.webp",x)[0])):
</code>```

How should the code be changed?

Title: How to use more than one extension

Body:
import os
import glob
import re

html = ""
strPath = os.path.realpath(__file__)
print( f"Full Path    :{strPath}" )
nmFolders = strPath.split( os.path.sep )
print( f"Folder Name  :{nmFolders[-2]}" )
for X in {nmFolders[-2]}:

    for file in sorted(glob.glob( os.path.join('*.webp') ),key=lambda x:float(re.findall("([0-9]+?)\.webp",x)[0])):
         html += f"<title> {X} </title>

{X}

"

for X in {nmFolders[-2]}:
    with open(f"{X}.html","w", encoding="utf-8") as outputfile:
        outputfile.write(html)

os.startfile(f"{X}.html")

This code create html with single extension (.webp) with numerical order but can't access multiple extension(.jpg,.png)

for file in sorted(glob.glob( os.path.join('*.webp') ),key=lambda x:float(re.findall("([0-9]+?)\.webp",x)[0])):

How should the code be changed?


问:
How to build a number counter using array with rxjs
I'm trying to build a counter number using an array and rxjs.
Each element of the array must counter until reaching the draw value.

```<code>        const numberSequencePrize = [3, 4, 8, 1, 1, 6];
        const numbersCounter = [...numberSequencePrize].map(r => 0);

        numbersCounter.forEach((number, i) => {
          timer(1, 1).pipe(
            take(10),
            repeat(10)
          ).subscribe((counter: number) => {
            numbersCounter[i] = counter;
          });
        });
</code>```

Each number must counter 10 times (that's why I'm using repeat operator) between 0 and 9 and then counter one last time until a condition is met (when the number of sequence equals to the number of the counter).
Is there's a better way to do it?

Body:
I'm trying to build a counter number using an array and rxjs.
Each element of the array must counter until reaching the draw value.

        const numberSequencePrize = [3, 4, 8, 1, 1, 6];
        const numbersCounter = [...numberSequencePrize].map(r => 0);

        numbersCounter.forEach((number, i) => {
          timer(1, 1).pipe(
            take(10),
            repeat(10)
          ).subscribe((counter: number) => {
            numbersCounter[i] = counter;
          });
        });

Each number must counter 10 times (that's why I'm using repeat operator) between 0 and 9 and then counter one last time until a condition is met (when the number of sequence equals to the number of the counter).
Is there's a better way to do it?


问:
While I was fetching data from DBpedia, an error named ConnectionResetError: [WinError 10054] occured, how to fix it?
I was trying to search for matching entities using SPARQL with python. The codes are as follow.

```<code>from SPARQLWrapper import SPARQLWrapper, JSON, XML, N3, RDF
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?label
    WHERE { <http://dbpedia.org/resource/Asturias> rdfs:label ?label }
""")

print(sparql)
sparql.setReturnFormat(JSON)
results = sparql.query()
results = results.convert()
for result in results["results"]["bindings"]:
    print (result["label"]["value"])
</code>```

The error info was like this:

```<code>Traceback (most recent call last):
  File "D:\All_python_projects\geometric_learning\SPARQL_test.py", line 11, in <module>
    results = sparql.query()
  File "D:\Anaconda\envs\normal\lib\site-packages\SPARQLWrapper\Wrapper.py", line 960, in query
    return QueryResult(self._query())
  File "D:\Anaconda\envs\normal\lib\site-packages\SPARQLWrapper\Wrapper.py", line 926, in _query
    response = urlopener(request)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 517, in open
    response = self._open(req, data)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 1375, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 1350, in do_open
    r = h.getresponse()
  File "D:\Anaconda\envs\normal\lib\http\client.py", line 1377, in getresponse
    response.begin()
  File "D:\Anaconda\envs\normal\lib\http\client.py", line 320, in begin
    version, status, reason = self._read_status()
  File "D:\Anaconda\envs\normal\lib\http\client.py", line 281, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "D:\Anaconda\envs\normal\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。
</code>```

The Chinese means The remote host forced an existing connection to close.
Note that I have already closed the Microsoft defender, and I was able to make direct access to the url, which means I can open it through the browser. Besides, using urllib.request doesn't work as well. Can you help me with this problem?

Body:
I was trying to search for matching entities using SPARQL with python. The codes are as follow.

from SPARQLWrapper import SPARQLWrapper, JSON, XML, N3, RDF
sparql = SPARQLWrapper("http://dbpedia.org/sparql")
sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?label
    WHERE { <http://dbpedia.org/resource/Asturias> rdfs:label ?label }
""")

print(sparql)
sparql.setReturnFormat(JSON)
results = sparql.query()
results = results.convert()
for result in results["results"]["bindings"]:
    print (result["label"]["value"])

The error info was like this:

Traceback (most recent call last):
  File "D:\All_python_projects\geometric_learning\SPARQL_test.py", line 11, in <module>
    results = sparql.query()
  File "D:\Anaconda\envs\normal\lib\site-packages\SPARQLWrapper\Wrapper.py", line 960, in query
    return QueryResult(self._query())
  File "D:\Anaconda\envs\normal\lib\site-packages\SPARQLWrapper\Wrapper.py", line 926, in _query
    response = urlopener(request)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 517, in open
    response = self._open(req, data)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 1375, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "D:\Anaconda\envs\normal\lib\urllib\request.py", line 1350, in do_open
    r = h.getresponse()
  File "D:\Anaconda\envs\normal\lib\http\client.py", line 1377, in getresponse
    response.begin()
  File "D:\Anaconda\envs\normal\lib\http\client.py", line 320, in begin
    version, status, reason = self._read_status()
  File "D:\Anaconda\envs\normal\lib\http\client.py", line 281, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "D:\Anaconda\envs\normal\lib\socket.py", line 704, in readinto
    return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。

The Chinese means The remote host forced an existing connection to close.
Note that I have already closed the Microsoft defender, and I was able to make direct access to the url, which means I can open it through the browser. Besides, using urllib.request doesn't work as well. Can you help me with this problem?


问:
How can i encoding in UTF-8 a Oracle SQL Developper Table
I'm working on a university project with Oracle SQL Developper. I'm working with french adress but i have the problem of encoding.

How can I change the encoding for oracle SQL table ?

I would like to have for example in line 9: "rue de béthune"

Thanks in advance,
François

I change the encoding in Tools --> Environnement --> UTF_8 but that didn't worked :(


问:
How come text can't be selected in react-select's demo?
This is a question I've been pondering, how does react-select prohibit text selection? Specifically in the first demo. I don't see a css property that disallows this in the DOM


问:
TypeError in plt.barh: 'value' must be an instance of str or bytes, not a tuple
I am getting this error when trying to plot the top features from a random forest model.

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

This is the code below. TIA

```<code>sorted_idx = trainedforest.feature_importances_.argsort()[-20:]
plt.barh(df.drop(columns=['feature_name'], axis = 1).columns.values[sorted_idx], trainedforest.feature_importances_[sorted_idx])
plt.figure(figsize=(500, 500))
plt.show()
</code>```

Body:
I am getting this error when trying to plot the top features from a random forest model.

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

This is the code below. TIA

sorted_idx = trainedforest.feature_importances_.argsort()[-20:]
plt.barh(df.drop(columns=['feature_name'], axis = 1).columns.values[sorted_idx], trainedforest.feature_importances_[sorted_idx])
plt.figure(figsize=(500, 500))
plt.show()


问:
How to get `geom_smooth` style CIs when using `emmip`
I have a model and a graph in R:

```<code>fit.lmer = lmer(std_brain ~ std_beh*type*taught + (1|subject/run), data=avg_data)
graph_lmer =  emmip(fit.lmer, type~std_beh | taught , at=list(type=type, std_beh=std_beh,
                                                             taught=taught), CIs=FALSE)
</code>```

I always set CIs to false because the default style of the CIs makes the graph totally illegible -- there's a colorful vertical bar at every marking point on three different lines.  You can't see the actual lines on the graph.  But I see examples of the kind of bands I'd like using geom_smooth and stat_smooth with ggplot. Here's an example -- there's a solid band, rather than bars on points, and it's gray:  However, I am not graphing points, I'm graphing marginal means, and so I don't think geom_smooth or stat_smooth are appropriate.  What I really want is just to apply that style to my emmip graph.  I can't find an example.

Body:
I have a model and a graph in R:

fit.lmer = lmer(std_brain ~ std_beh*type*taught + (1|subject/run), data=avg_data)
graph_lmer =  emmip(fit.lmer, type~std_beh | taught , at=list(type=type, std_beh=std_beh,
                                                             taught=taught), CIs=FALSE)

I always set CIs to false because the default style of the CIs makes the graph totally illegible -- there's a colorful vertical bar at every marking point on three different lines.  You can't see the actual lines on the graph.  But I see examples of the kind of bands I'd like using geom_smooth and stat_smooth with ggplot. Here's an example -- there's a solid band, rather than bars on points, and it's gray:  However, I am not graphing points, I'm graphing marginal means, and so I don't think geom_smooth or stat_smooth are appropriate.  What I really want is just to apply that style to my emmip graph.  I can't find an example.


问:
How do I use regex_replace from TR1?
I've not been able to get regex_replace from TR1 working.

```<code>#include <iostream>
#include <string>
#include <tr1/regex>

int main()
{
std::string str = "Hello world";
std::tr1::regex rx("world");
std::string replacement = "planet";
std::string str2 = std::tr1::regex_replace(str, rx, replacement);

std::cout << str2 << "\n";
}
</code>```

str2 is an empty string.

OwnerDisplayName: Koonool

LastEditorDisplayName: Koonool

ContentLicense: CC BY-SA 2.5

Title: How do I use regex_replace from TR1?

Body:
I've not been able to get regex_replace from TR1 working.

#include <iostream>
#include <string>
#include <tr1/regex>

int main()
{
std::string str = "Hello world";
std::tr1::regex rx("world");
std::string replacement = "planet";
std::string str2 = std::tr1::regex_replace(str, rx, replacement);

std::cout << str2 << "\n";
}

str2 is an empty string.


问:
How to test Cloud Function in GCP where I am inserting data into Database
I am trying to test this function which inserts data into postgres via GCP Cloud Function. I am having trouble testing this. It say some JSON is required. However what is exactly required her to be called?

```<code>def hello_world(self):
# establishing the connection
conn = psycopg2.connect(
    database='somedb',
    user='someuser',
    password='somepwd',
    host='XX.XXX.XXX.XXX',
    port='5432'
)

# creating a cursor object
cursor = conn.cursor()

# list that contain records to be inserted into table
data = [('Babita', 'Bihar'), ('Anushka', 'Hyderabad'),
        ('Anamika', 'Banglore'), ('Sanaya', 'Pune'),
        ('Radha', 'Chandigarh')]

# inserting record into employee table
for d in data:
    cursor.execute("INSERT into employee(name, state) VALUES (%s, %s)", d)

# print("List has been inserted to employee table successfully...")

# Commit your changes in the database
conn.commit()

# Closing the connection
conn.close()
</code>```

Body:
I am trying to test this function which inserts data into postgres via GCP Cloud Function. I am having trouble testing this. It say some JSON is required. However what is exactly required her to be called?

def hello_world(self):
# establishing the connection
conn = psycopg2.connect(
    database='somedb',
    user='someuser',
    password='somepwd',
    host='XX.XXX.XXX.XXX',
    port='5432'
)

# creating a cursor object
cursor = conn.cursor()

# list that contain records to be inserted into table
data = [('Babita', 'Bihar'), ('Anushka', 'Hyderabad'),
        ('Anamika', 'Banglore'), ('Sanaya', 'Pune'),
        ('Radha', 'Chandigarh')]

# inserting record into employee table
for d in data:
    cursor.execute("INSERT into employee(name, state) VALUES (%s, %s)", d)

# print("List has been inserted to employee table successfully...")

# Commit your changes in the database
conn.commit()

# Closing the connection
conn.close()


问:
feature extraction on real data isolet dataset
it is my first time dealing with audio data and i'm having a bit of trouble extracting the freature of a real sample audio to pass on the model for evaluation especially that i didn't really understand how the data was pre-processed from the paper below and "The exact order of appearance of the features is not known"
as stated in the Attribute Information.

https://aclanthology.org/H90-1075.pdf

any help would be appreciated.

i tried searching for "spectral coefficients; contour features, sonorant features, pre-sonorant features, and post-sonorant features" but got with a lot of information to start with.


问:
R - readtext and list of .xml files
I'm trying to create a corpus and a vcorpus with a bulk of .xml files, for quantitative linguistics
With txt files I usually write

```<code>library(tm)
library(stopwords)
library(magrittr)
library(dplyr)
library(readtext)
library(quanteda)
library(quanteda.textmodels)
library(quanteda.textplots)
library(quanteda.textstats)

object <- readtext ("directory")
and
objectV <- DirSource ("directory") %>%
VCorpus(readerControl = list(language = "it-IT"))
</code>```

Trying with a directory containing xml files I get this error

```<code>The xml format does not fit for the extraction without xPath
Use xPath method instead
</code>```

Any suggestion? Thank you! E.

Title: R - readtext and list of .xml files

Body:
I'm trying to create a corpus and a vcorpus with a bulk of .xml files, for quantitative linguistics
With txt files I usually write

library(tm)
library(stopwords)
library(magrittr)
library(dplyr)
library(readtext)
library(quanteda)
library(quanteda.textmodels)
library(quanteda.textplots)
library(quanteda.textstats)

object <- readtext ("directory")
and
objectV <- DirSource ("directory") %>%
VCorpus(readerControl = list(language = "it-IT"))

Trying with a directory containing xml files I get this error

The xml format does not fit for the extraction without xPath
Use xPath method instead

Any suggestion? Thank you! E.


问:
Add animation landing page to Rasa chatbot
I would like to know if it is possible to add an "on init" animation when opening the Rasa webchat widget.
https://github.com/botfront/rasa-webchat

I need to add some HTML and additional CSS classes to rasa in order to show an animation when first opening the chat widget, is that possible ?

Thank you!


问:
How to set select box to be width of parent, no matter content size (antd)?
A regular select box behaves differently than an antd select box when the parent is a display: flex and each item is flex: 1 (that is, it should equally stretch to fill in the width).

I am working with an antd select box under these conditions, and can't figure out how to get the select box to be flex: 1 and fill the available space equally as much as the other things. Instead, it stretches to accommodate large content in the selected option, and shrinks down to some minimum width. If there are 5 elements in the row, I want it to be 1/5th the width (plus some gap between elements). If there are 4 elements, then 1/4th the width, etc..

How can I make an antd select behave well under these conditions? That is, given the parent is display: flex, and I want to accomplish flex: 1 on each child, how can I accomplish it in antd? If I need to completely change my DOM structure I am okay with that, I just don't want to have to provide an explicit width on the select box.

<link rel="stylesheet" href="https://unpkg.com/antd@4.18.9/dist/antd.min.css" />

regular:

  <select style="flex: 1">
    <option>a short thing</option>
    <option>a thing</option>
    <option>a really long thing</option>
    <option>a really really really long thing</option>
  </select>

Content 1

Content 2

Content 3

Content 4

Content 5

Content 6

Content 7

Content 8

antd:

```

Note, it appears the unpkg'd antd is erroring on cloudflare occasionally, but the above code does work in showing the faulty case.

Body:
A regular select box behaves differently than an antd select box when the parent is a display: flex and each item is flex: 1 (that is, it should equally stretch to fill in the width).

I am working with an antd select box under these conditions, and can't figure out how to get the select box to be flex: 1 and fill the available space equally as much as the other things. Instead, it stretches to accommodate large content in the selected option, and shrinks down to some minimum width. If there are 5 elements in the row, I want it to be 1/5th the width (plus some gap between elements). If there are 4 elements, then 1/4th the width, etc..

How can I make an antd select behave well under these conditions? That is, given the parent is display: flex, and I want to accomplish flex: 1 on each child, how can I accomplish it in antd? If I need to completely change my DOM structure I am okay with that, I just don't want to have to provide an explicit width on the select box.

<link rel="stylesheet" href="https://unpkg.com/antd@4.18.9/dist/antd.min.css" />

regular:

  <select style="flex: 1">
    <option>a short thing</option>
    <option>a thing</option>
    <option>a really long thing</option>
    <option>a really really really long thing</option>
  </select>

Content 1

Content 2

Content 3

Content 4

Content 5

Content 6

Content 7

Content 8

antd:

Note, it appears the unpkg'd antd is erroring on cloudflare occasionally, but the above code does work in showing the faulty case.


问:
Same print styles for @media print and a class using SCSS mixin
I have many places where I have print styles for particular components in my scss file.

Each of these use the standard @media print. But I have had a request to detect if the site is too wide to print in portrait mode and automatically switch to landscape.

To do this I need to check using beforeprint if there is any overflow on the body tag, if there is, I inject a separate stylesheet that adds an @page declaration and switches the size to A4 Landscape.

This all works fine. The problem is, to detect the overflow on a portrait page, I must first add a class of .printing which changes the document's dimensions to that of an A4 page. I also need all the print styles to "kick in" at this point, but as there is no way to trigger a media switch, I add a class on the html tag called ".printing".

When the printing class is present I want any print styles I have in the file to work the same as @media print.

So to cut down on maintenance and inconsistent behaviour I started with a mixin:

@mixin mediaPrint {
    .printing {
        @content;
    }

    @media print {
        @content;
    }
}
```
<p>This would be used like this:</p>
<pre class="lang-scss prettyprint-override"><code>.headerAndNavigation {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    grid-template-rows: auto minmax(0, 1fr);
    block-size: var(--documentHeight);
    background: var(--content__background);

    @media screen and (max-width: $navigationToggle) {
        grid-template-columns: 0 minmax(0,1fr);
    }
    // Elements ---------
    &__header {
        grid-column: 1 / span 2;
    }

    &__navigation {
        grid-column: 1;
        grid-row: 2;
    }

    &__content {
        grid-column: 2;
        grid-row: 2;
        overflow: auto;
    }

    @include mediaPrint {
        display: block;

        &__header,
        &__navigation {
            display: none;
        }
    }
}
</code>```

The issue here is the & is replaced by .printing instead of .headerAndNavigation.

As a result, I changed the mixin to this:

@mixin mediaPrint {
    .printing #{&} {
        @content;
    }

    @media print {
        @content;
    }
}
```
<p>Which renders out this:</p>
<pre class="lang-css prettyprint-override"><code>.headerAndNavigation .printing .headerAndNavigation .headerAndNavigation__header,
.headerAndNavigation .printing .headerAndNavigation .headerAndNavigation__navigation
</code>```

Because the mixin is nested in the class, is it possible to prevent the nesting even when it is nested inside another class?

I'm not sure its even possible to do what I need, but I'm not sure what else to try.

The end result should be:

.printing .headerAndNavigation {
    display: block
}

.printing .headerAndNavigation .headerAndNavigation__header,
.printing .headerAndNavigation .headerAndNavigation__navigation {
    display: none
}

@media print {
    .headerAndNavigation {
        display: block
    }

    .headerAndNavigation .headerAndNavigation__header,
    .headerAndNavigation .headerAndNavigation__navigation {
        display: none
    }
}
```

Body:
I have many places where I have print styles for particular components in my scss file.

Each of these use the standard @media print. But I have had a request to detect if the site is too wide to print in portrait mode and automatically switch to landscape.

To do this I need to check using beforeprint if there is any overflow on the body tag, if there is, I inject a separate stylesheet that adds an @page declaration and switches the size to A4 Landscape.

This all works fine. The problem is, to detect the overflow on a portrait page, I must first add a class of .printing which changes the document's dimensions to that of an A4 page. I also need all the print styles to "kick in" at this point, but as there is no way to trigger a media switch, I add a class on the html tag called ".printing".

When the printing class is present I want any print styles I have in the file to work the same as @media print.

So to cut down on maintenance and inconsistent behaviour I started with a mixin:

@mixin mediaPrint {
    .printing {
        @content;
    }

    @media print {
        @content;
    }
}

This would be used like this:

.headerAndNavigation {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    grid-template-rows: auto minmax(0, 1fr);
    block-size: var(--documentHeight);
    background: var(--content__background);

    @media screen and (max-width: $navigationToggle) {
        grid-template-columns: 0 minmax(0,1fr);
    }
    // Elements ---------
    &__header {
        grid-column: 1 / span 2;
    }

    &__navigation {
        grid-column: 1;
        grid-row: 2;
    }

    &__content {
        grid-column: 2;
        grid-row: 2;
        overflow: auto;
    }

    @include mediaPrint {
        display: block;

        &__header,
        &__navigation {
            display: none;
        }
    }
}

The issue here is the & is replaced by .printing instead of .headerAndNavigation.

As a result, I changed the mixin to this:

@mixin mediaPrint {
    .printing #{&} {
        @content;
    }

    @media print {
        @content;
    }
}

Which renders out this:

.headerAndNavigation .printing .headerAndNavigation .headerAndNavigation__header,
.headerAndNavigation .printing .headerAndNavigation .headerAndNavigation__navigation

Because the mixin is nested in the class, is it possible to prevent the nesting even when it is nested inside another class?

I'm not sure its even possible to do what I need, but I'm not sure what else to try.

The end result should be:

.printing .headerAndNavigation {
    display: block
}

.printing .headerAndNavigation .headerAndNavigation__header,
.printing .headerAndNavigation .headerAndNavigation__navigation {
    display: none
}

@media print {
    .headerAndNavigation {
        display: block
    }

    .headerAndNavigation .headerAndNavigation__header,
    .headerAndNavigation .headerAndNavigation__navigation {
        display: none
    }
}


问:
Why bsdtar translates some special characters?
I have a simple piece of code (part of a larger PowerShell script) that I use to pack files into .tar:

```<code>tar -cf $Destination $Source
</code>```

It did the job well for what I needed, but recently I encountered some special characters that are not supported.

Characters like : ¿ ï â € ™ are handled well and everything goes fine.

Characters like : ł ż ń ś are just translated to their latin form (l z n s).
When the characters get translated the code can't find the source folder (as it's looking for a totally different one) and the resulting .tar file is also renamed.

Is there a solution to process the characters as they are?

Tried to pack all files from folder "D:\Test\Błasino" and expected a "Błasino.tar" file to be created.

PowerShell threw the following error and created a "BÅ,asino.tar" file.

```<code>tar.exe: D:/Test/BÅ,asino/*: Couldn't find file: No such file or directory
tar.exe: Error exit delayed from previous errors.
</code>```

Body:
I have a simple piece of code (part of a larger PowerShell script) that I use to pack files into .tar:

tar -cf $Destination $Source

It did the job well for what I needed, but recently I encountered some special characters that are not supported.

Characters like : ¿ ï â € ™ are handled well and everything goes fine.

Characters like : ł ż ń ś are just translated to their latin form (l z n s).
When the characters get translated the code can't find the source folder (as it's looking for a totally different one) and the resulting .tar file is also renamed.

Is there a solution to process the characters as they are?

Tried to pack all files from folder "D:\Test\Błasino" and expected a "Błasino.tar" file to be created.

PowerShell threw the following error and created a "BÅ,asino.tar" file.

tar.exe: D:/Test/BÅ,asino/*: Couldn't find file: No such file or directory
tar.exe: Error exit delayed from previous errors.


问:
How to pass data from EJS to MYSQL route?
I have an EJS view where I´m displaying cards (data) from a MYSQL table by an email search box (users dont need to login). I want to give users the option of clicking any of the cards they pull with their email and be able to send me a message about that specific card.
I´m able to retrieve the message with the POST method and the normal POST route, but I don´t know how to get the "titulo" of the card from which Im getting the message about. How can I pass that info to the route response body?

This is my code

adcards.ejs

```<code><div class="cssshowlaptopcampanas">
    <div
        style="display: flex; flex-direction: row;  max-width: 100%; flex-wrap: wrap; margin-left: 400px; font-family: 'Raleway', sans-serif; justify-content: space-around; margin-bottom: 30px; padding-bottom: 30px;">
        <% clients.forEach(function(clients){ %>
            <div style="margin: 10px; margin-top: 30px; border-radius: 20px;">
                <span class="badge badge-success" style="width: 100px;">
                    <%= clients.status%>
                </span>
                <div class="card" style="width: 19rem; border-radius: 20px;">
                    <img src="/city2.png" class="card-img-top" alt="..."
                        style=" border-bottom-left-radius: 0px; border-bottom-right-radius: 0px; border-top-right-radius: 20px; border-top-left-radius: 20px;">

<!--  I NEED TO GET THIS CLIENTS.TITULO RESULT TOGETHER WITH THE FORM MESSAGE BELOW  -->

<div class="card-body">
                        <h5 class="card-title" style="position: relative; top: 7px;">
                            <%= clients.titulo %>
                        </h5>
                    </div>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">Fecha inicio: <span style="font-weight: bold;">
                                <%= clients.fechas %>
                            </span>
                        </li>
                        <li class="list-group-item">Mostrando en: <span style="font-weight: bold;">
                                <%= clients.zonas %>
                            </span>
                        </li>

                    </ul>
                    <div class="card-body"
                        style="display: flex; flex-direction: row; width: 302px; justify-content: space-around; background-color: #6351ce; color: white; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; padding-left: 10px; padding-right: 10px;">

                        <nav class="navbar " >
                            <div class="container-fluid" style="display: flex; flex-direction: column;">
                                <a class="navbar-toggler" type="button" data-bs-toggle="collapse"
                                    data-bs-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent"
                                    aria-expanded="false" aria-label="Toggle navigation">
                                    <span style="color: white; position: relative; margin-bottom: 10px; ">Editar</span>
                                </a>

                                <div class="collapse" id="navbarToggleExternalContent" style="padding-top: 25px;" >
                                    <div  style="display: flex; flex-direction: column; color: white; align-items: flex-start; align-content: flex-start; background-color: #6351ce;">

<!-- THIS IS THE FORM WHERE IM TRYING TO GET THE MESSAGE AND TITLE FROM  -->

                                        <form action="/cambios" method="POST" >
                                        <textarea type="text" name="cambiossolicitados" id="cambiossolicitados" placeholder="¿Cuáles cambios deseas realizar?" autofocus> </textarea>
                                        <br>
                                        <button class="btn btn-success btn-block" type="submit" value="Enviar"> Save </button>
                                        <br>
                                       </form>

                                    </div>
                                </div>
                            </div>

                        </nav>

                    </div>
                </div>
            </div>
            <% }) %>
    </div>
</div>
</code>```

This is where my routes are.
routes.js

```<code>

router.get('/search-email',  function (req, res) {

    pool.getConnection(function(err) {
        var sql = 'SELECT * from anuncios';

         pool.query(sql, function(error, result){

            if(error) console.log(error);

            res.render('./search-email.ejs' , { clients: result})

            })

})});

router.get('/search',  function (req, res) {

    var email = req.query.email;
    console.log(email);
    pool.getConnection(function(error) {
        if(error) console.log(error);
        pool.query("SELECT * FROM clientes WHERE Email LIKE ?" , [email], function(error, result){

        if(error) console.log(error);
        res.render('./search-email.ejs', { clients: result} )

        })

})});

//THIS IS THE ROUTE FOR THE FORM IM TRYING TO GET THE MESSAGE AND CLIENTS.TITULO FROM

router.post('/cambios', async (req, res) => {
    const  cambiossolicitados  = req.body.cambiossolicitados;
    const newCambio = { ID: req.clients.id }

    console.log(newCambio);
    console.log(cambiossolicitados);
})
</code>```

I tried using req.clients.id but it didnt work. I get an error message saying

{ ID: req.clients.id }
^

TypeError: Cannot read properties of undefined (reading 'id')

I would appreciate if someone can help me! Thanks.

Body:
I have an EJS view where I´m displaying cards (data) from a MYSQL table by an email search box (users dont need to login). I want to give users the option of clicking any of the cards they pull with their email and be able to send me a message about that specific card.
I´m able to retrieve the message with the POST method and the normal POST route, but I don´t know how to get the "titulo" of the card from which Im getting the message about. How can I pass that info to the route response body?

This is my code

adcards.ejs

        <% clients.forEach(function(clients){ %>

                    <%= clients.status%>

                            <%= clients.titulo %>

Fecha inicio:
                                <%= clients.fechas %>

Mostrando en:
                                <%= clients.zonas %>

                                    Editar

                                        <form action="/cambios" method="POST" >
                                        <textarea type="text" name="cambiossolicitados" id="cambiossolicitados" placeholder="¿Cuáles cambios deseas realizar?" autofocus> </textarea>

                                        <button class="btn btn-success btn-block" type="submit" value="Enviar"> Save </button>

                                       </form>

            <% }) %>

This is where my routes are.
routes.js

router.get('/search-email',  function (req, res) {

    pool.getConnection(function(err) {
        var sql = 'SELECT * from anuncios';

         pool.query(sql, function(error, result){

            if(error) console.log(error);

            res.render('./search-email.ejs' , { clients: result})

            })

})});

router.get('/search',  function (req, res) {

    var email = req.query.email;
    console.log(email);
    pool.getConnection(function(error) {
        if(error) console.log(error);
        pool.query("SELECT * FROM clientes WHERE Email LIKE ?" , [email], function(error, result){

        if(error) console.log(error);
        res.render('./search-email.ejs', { clients: result} )

        })

})});

//THIS IS THE ROUTE FOR THE FORM IM TRYING TO GET THE MESSAGE AND CLIENTS.TITULO FROM

router.post('/cambios', async (req, res) => {
    const  cambiossolicitados  = req.body.cambiossolicitados;
    const newCambio = { ID: req.clients.id }

    console.log(newCambio);
    console.log(cambiossolicitados);
})

I tried using req.clients.id but it didnt work. I get an error message saying

{ ID: req.clients.id }
^

TypeError: Cannot read properties of undefined (reading 'id')

I would appreciate if someone can help me! Thanks.


问:
Kubernetes dashboard and pvc problems
I install a Kubernetes cluster on two VMS VMware with CentOS 8.  The cluster is working

```<code>[root@master storage-classes]# kubectl get no -o wide
NAME      STATUS   ROLES           AGE   VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE          KERNEL-VERSION          CONTAINER-RUNTIME
master    Ready    control-plane   10d   v1.25.4   10.10.100.9    <none>        CentOS Stream 8   4.18.0-408.el8.x86_64   containerd://1.6.10
worker1   Ready    worker          10d   v1.25.4   10.10.100.13   <none>        CentOS Stream 8   4.18.0-408.el8.x86_64   containerd://1.6.10

[root@master storage-classes]# kubectl get PO --all-namespaces  -o wide
NAMESPACE              NAME                                          READY   STATUS    RESTARTS       AGE   IP             NODE      NOMINATED NODE   READINESS GATES
kube-system            coredns-565d847f94-b2884                      1/1     Running   9 (35m ago)    10d   10.32.0.2      master    <none>           <none>
kube-system            coredns-565d847f94-rjnl2                      1/1     Running   9 (35m ago)    10d   10.32.0.3      master    <none>           <none>
kube-system            etcd-master                                   1/1     Running   29 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            kube-apiserver-master                         1/1     Running   28 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            kube-controller-manager-master                1/1     Running   10 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            kube-proxy-dm9kv                              1/1     Running   9 (35m ago)    10d   10.10.100.9    master    <none>           <none>
kube-system            kube-proxy-vjdf8                              1/1     Running   6 (34m ago)    10d   10.10.100.13   worker1   <none>           <none>
kube-system            kube-scheduler-master                         1/1     Running   10 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            weave-net-rs7vc                               2/2     Running   26 (34m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            weave-net-zsmmh                               2/2     Running   18 (34m ago)   10d   10.10.100.13   worker1   <none>           <none>
kubernetes-dashboard   dashboard-metrics-scraper-64bcc67c9c-hrk7q    1/1     Running   3 (34m ago)    7d    10.32.0.3      worker1   <none>           <none>
kubernetes-dashboard   kubernetes-dashboard-66c887f759-qcqfg         1/1     Running   3 (34m ago)    7d    10.32.0.4      worker1   <none>           <none>
kubernetes-dashboard   kubernetes-metrics-scraper-549b9bbf45-9n7gv   1/1     Running   3 (34m ago)    7d    10.32.0.2      worker1   <none>           <none>
</code>```

But I have two problems: I can not run the dashboard on port 8001, and I create a PVC and am pending with which I can not lift any pod. I thank you for any help you can give me.

What information would they need to bring us closer to the solution?

Title: Kubernetes dashboard and pvc problems

Body:
I install a Kubernetes cluster on two VMS VMware with CentOS 8.  The cluster is working

[root@master storage-classes]# kubectl get no -o wide
NAME      STATUS   ROLES           AGE   VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE          KERNEL-VERSION          CONTAINER-RUNTIME
master    Ready    control-plane   10d   v1.25.4   10.10.100.9    <none>        CentOS Stream 8   4.18.0-408.el8.x86_64   containerd://1.6.10
worker1   Ready    worker          10d   v1.25.4   10.10.100.13   <none>        CentOS Stream 8   4.18.0-408.el8.x86_64   containerd://1.6.10

[root@master storage-classes]# kubectl get PO --all-namespaces  -o wide
NAMESPACE              NAME                                          READY   STATUS    RESTARTS       AGE   IP             NODE      NOMINATED NODE   READINESS GATES
kube-system            coredns-565d847f94-b2884                      1/1     Running   9 (35m ago)    10d   10.32.0.2      master    <none>           <none>
kube-system            coredns-565d847f94-rjnl2                      1/1     Running   9 (35m ago)    10d   10.32.0.3      master    <none>           <none>
kube-system            etcd-master                                   1/1     Running   29 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            kube-apiserver-master                         1/1     Running   28 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            kube-controller-manager-master                1/1     Running   10 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            kube-proxy-dm9kv                              1/1     Running   9 (35m ago)    10d   10.10.100.9    master    <none>           <none>
kube-system            kube-proxy-vjdf8                              1/1     Running   6 (34m ago)    10d   10.10.100.13   worker1   <none>           <none>
kube-system            kube-scheduler-master                         1/1     Running   10 (35m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            weave-net-rs7vc                               2/2     Running   26 (34m ago)   10d   10.10.100.9    master    <none>           <none>
kube-system            weave-net-zsmmh                               2/2     Running   18 (34m ago)   10d   10.10.100.13   worker1   <none>           <none>
kubernetes-dashboard   dashboard-metrics-scraper-64bcc67c9c-hrk7q    1/1     Running   3 (34m ago)    7d    10.32.0.3      worker1   <none>           <none>
kubernetes-dashboard   kubernetes-dashboard-66c887f759-qcqfg         1/1     Running   3 (34m ago)    7d    10.32.0.4      worker1   <none>           <none>
kubernetes-dashboard   kubernetes-metrics-scraper-549b9bbf45-9n7gv   1/1     Running   3 (34m ago)    7d    10.32.0.2      worker1   <none>           <none>

But I have two problems: I can not run the dashboard on port 8001, and I create a PVC and am pending with which I can not lift any pod. I thank you for any help you can give me.

What information would they need to bring us closer to the solution?


问:
Swift 5: Getting "Variable 'xxxx' used before being initialized" in initalizer although the variable is not used
I am trying to write an iOS application and get the error in the title. The problem is not with the @State property but with the order of initialization. In my opinion this post (SwiftUI @State var initialization issue) does not answer the question why the above error only occurs if the @State properties are declared before the normal variable.
I created an simple example so there is less code to read.

The error occurs in the initializer of this SwiftUI View:

```<code>import SwiftUI
import MapKit
import CoreLocation

struct SimpleExample: View {
    @State var trackingMode: MapUserTrackingMode = .follow
    @State var searchRadius = CGFloat(200.0)
    let isWholeScreen: Bool

    var body: some View {
        VStack(spacing: 0) {
            Text("Placeholder")
        }
    }

    init(trackingMode: MapUserTrackingMode, searchRadius: CGFloat, isWholeScreen: Bool) {
        self.trackingMode = trackingMode
        self.searchRadius = searchRadius
        self.isWholeScreen = isWholeScreen
    }
}

struct SimpleExample_Previews: PreviewProvider {
    static var previews: some View {
        MapView(trackingMode: .follow, searchRadius: CGFloat(200.0), isWholeScreen: true)
    }
}
</code>```

If you change the order of initializations everything works. I am interested in why it works when the order is reversed

```<code>init(trackingMode: MapUserTrackingMode, searchRadius: CGFloat, isWholeScreen: Bool) {
        self.isWholeScreen = isWholeScreen
        self.trackingMode = trackingMode
        self.searchRadius = searchRadius
//        self.isWholeScreen = isWholeScreen
    }
</code>```

My only idea is that it’s caused by @State.

Body:
I am trying to write an iOS application and get the error in the title. The problem is not with the @State property but with the order of initialization. In my opinion this post (SwiftUI @State var initialization issue) does not answer the question why the above error only occurs if the @State properties are declared before the normal variable.
I created an simple example so there is less code to read.

The error occurs in the initializer of this SwiftUI View:

import SwiftUI
import MapKit
import CoreLocation

struct SimpleExample: View {
    @State var trackingMode: MapUserTrackingMode = .follow
    @State var searchRadius = CGFloat(200.0)
    let isWholeScreen: Bool

    var body: some View {
        VStack(spacing: 0) {
            Text("Placeholder")
        }
    }

    init(trackingMode: MapUserTrackingMode, searchRadius: CGFloat, isWholeScreen: Bool) {
        self.trackingMode = trackingMode
        self.searchRadius = searchRadius
        self.isWholeScreen = isWholeScreen
    }
}

struct SimpleExample_Previews: PreviewProvider {
    static var previews: some View {
        MapView(trackingMode: .follow, searchRadius: CGFloat(200.0), isWholeScreen: true)
    }
}

If you change the order of initializations everything works. I am interested in why it works when the order is reversed

init(trackingMode: MapUserTrackingMode, searchRadius: CGFloat, isWholeScreen: Bool) {
        self.isWholeScreen = isWholeScreen
        self.trackingMode = trackingMode
        self.searchRadius = searchRadius
//        self.isWholeScreen = isWholeScreen
    }

My only idea is that it’s caused by @State.


问:
how to sort rows of an R dataframe based on a binary condition within subjects
I have a dataset composed of the following columns

```<code>Subject_Number     Condition        .... other columns
300                drug
300                placebo
299                placebo
298                drug
297                drug
296                placebo
</code>```

...

As you can see, each participant (e.g. participant number 300) has been analysed on two occasions once with the drug and once with a placebo

Now i am required to do the following: for each participant, I need to make it so the first condition is the drug and the second is the placebo:

```<code>Subject_Number     Condition        .... other columns
300                drug
300                placebo
299                drug
298                placebo
297                drug
296                placebo
...
</code>```

Can you help me find out how to do this? Thanks!

I can sort or order the dataframe based on the condition column but then it will change the dataframe in a way where first it shows all the drug rows, then all the placebo rows together. I don't want that. I need to make it so within each subject number the drug row comes first and the placebo row comes second.
Hope I explained myself!

Body:
I have a dataset composed of the following columns

Subject_Number     Condition        .... other columns
300                drug
300                placebo
299                placebo
298                drug
297                drug
296                placebo

...

As you can see, each participant (e.g. participant number 300) has been analysed on two occasions once with the drug and once with a placebo

Now i am required to do the following: for each participant, I need to make it so the first condition is the drug and the second is the placebo:

Subject_Number     Condition        .... other columns
300                drug
300                placebo
299                drug
298                placebo
297                drug
296                placebo
...

Can you help me find out how to do this? Thanks!

I can sort or order the dataframe based on the condition column but then it will change the dataframe in a way where first it shows all the drug rows, then all the placebo rows together. I don't want that. I need to make it so within each subject number the drug row comes first and the placebo row comes second.
Hope I explained myself!


问:
gather images from folder create a file and authomatic download
I'm creating an small component to create some images that I need for my database, I create a file based on react using doom-to-img and file-saver, and what this does is upload and image center this image in a div with some size parameter and when i click on download images this export the div as img, im doing this to create some image by bulk for a website because photoshop cant do it. The app is working manually right now, then i have to specify the source file and click on download imgs to do the process but I need to do it automatically  indicating the folder with the images, the app just export one by one through a loop i dont know how to do it, if someone could guide me thats gonna be awesome.

I'm leaving the repository for the app here and the main app.js code

repository: https://github.com/sraponte91/react-dic-to-imgs

```<code>import React, { useRef } from 'react';
import './style.css';
import domtoimage from 'dom-to-image';
import {
  exportComponentAsJPEG,
  exportComponentAsPDF,
  exportComponentAsPNG,
} from 'react-component-export-image';

export default function App() {
  const downloadRef = useRef();

  const handleDownloadImage = () => {
    const targetEl = downloadRef.current;
    domtoimage.toJpeg(targetEl, { quality: 1 }).then((dataUrl) => {
      let link = document.createElement('a');
      link.download = 'my-image-name.jpeg';
      link.href = dataUrl;
      link.click();
    });
  };

  return (
    <div>
      <div className="container" ref={downloadRef}>
        <img src={"./assets/nyxprofessionalmakeuptintedbrowmascara-tbm04-espresso-color.jpg"} />
      </div>
      <button className="download" onClick={handleDownloadImage}>
        Download
      </button>
      <button onClick={() => exportComponentAsPNG(downloadRef)}>
        Convert To PNG
      </button>
    </div>
  );
}
</code>```

I created the manual steps but the automation I don't know how to do it

Body:
I'm creating an small component to create some images that I need for my database, I create a file based on react using doom-to-img and file-saver, and what this does is upload and image center this image in a div with some size parameter and when i click on download images this export the div as img, im doing this to create some image by bulk for a website because photoshop cant do it. The app is working manually right now, then i have to specify the source file and click on download imgs to do the process but I need to do it automatically  indicating the folder with the images, the app just export one by one through a loop i dont know how to do it, if someone could guide me thats gonna be awesome.

I'm leaving the repository for the app here and the main app.js code

repository: https://github.com/sraponte91/react-dic-to-imgs

import React, { useRef } from 'react';
import './style.css';
import domtoimage from 'dom-to-image';
import {
  exportComponentAsJPEG,
  exportComponentAsPDF,
  exportComponentAsPNG,
} from 'react-component-export-image';

export default function App() {
  const downloadRef = useRef();

  const handleDownloadImage = () => {
    const targetEl = downloadRef.current;
    domtoimage.toJpeg(targetEl, { quality: 1 }).then((dataUrl) => {
      let link = document.createElement('a');
      link.download = 'my-image-name.jpeg';
      link.href = dataUrl;
      link.click();
    });
  };

  return (

      <button className="download" onClick={handleDownloadImage}>
        Download
      </button>
      <button onClick={() => exportComponentAsPNG(downloadRef)}>
        Convert To PNG
      </button>

  );
}

I created the manual steps but the automation I don't know how to do it


问:
what is the proper way to get a result from this SQL function if statement?
The original idea for my function was to have the date in my schedule table be compared to today's date in an if statement, and if the date in the table is past the date of today it would move the row of data from the schedule table to the past_shows  table.

this is what i have tried so far,

```<code>DELIMITER //
CREATE FUNCTION pastShow (
showID INT,
date_time DATETIME
)
BEGIN
// if condition
IF (date_time > DATE)
  THEN
    INSERT showID, date_time INTO past_shows From schedule
END IF;
END; //
DELIMITER ;
</code>```

Body:
The original idea for my function was to have the date in my schedule table be compared to today's date in an if statement, and if the date in the table is past the date of today it would move the row of data from the schedule table to the past_shows  table.

this is what i have tried so far,

DELIMITER //
CREATE FUNCTION pastShow (
showID INT,
date_time DATETIME
)
BEGIN
// if condition
IF (date_time > DATE)
  THEN
    INSERT showID, date_time INTO past_shows From schedule
END IF;
END; //
DELIMITER ;


问:
Auto-editing a dependent value in a column of pandas dataframe by editing an independent column value
Assume that there is a pandas data frame containing two columns, A and B; where : B = f(A) <<e.g. B=3*A>>. And we already have some data in it.

```<code>data = {'A' : [2, 4]}
df = pd.DataFrame(data)
df['B'] = 3 * df.A
</code>```

Now, if I change a value of column A, it won't apply to column B. for example if:

```<code>df['A'][0] = 5
</code>```

the desired result for B[0] would be 15, but it's not happening by doing so.
Is there any way to change the value of B[0] automatically?

Body:
Assume that there is a pandas data frame containing two columns, A and B; where : B = f(A) <<e.g. B=3*A>>. And we already have some data in it.

data = {'A' : [2, 4]}
df = pd.DataFrame(data)
df['B'] = 3 * df.A

Now, if I change a value of column A, it won't apply to column B. for example if:

df['A'][0] = 5

the desired result for B[0] would be 15, but it's not happening by doing so.
Is there any way to change the value of B[0] automatically?


问:
Run build only if certain file types are updated by git pull
I'm looking for a command or a series of commands that will allow me to run npm run build only if certain file types have been updated by git pull. I've tried researching the issue but haven't found anything if it is at all possible.

My current (Runcloud) deployment script is as follows:

```<code>git pull
npm run build
</code>```

Building takes a minute or so each time even if I'm only pushing .html or .php files. Ideally, it would only build if building would make a difference, such as .js or .scss files.

The build process uses Webpack so if that can be used to achieve the same effect, I'd be happy to try it.

Thank you

Body:
I'm looking for a command or a series of commands that will allow me to run npm run build only if certain file types have been updated by git pull. I've tried researching the issue but haven't found anything if it is at all possible.

My current (Runcloud) deployment script is as follows:

git pull
npm run build

Building takes a minute or so each time even if I'm only pushing .html or .php files. Ideally, it would only build if building would make a difference, such as .js or .scss files.

The build process uses Webpack so if that can be used to achieve the same effect, I'd be happy to try it.

Thank you


问:
Missing or incorrect code related to charting
enter image description hereWhen write this code, it is give me a charting but I write new code abot charting it give mi drew the code-related content but removed the graphics lines. For example When I write the chart title code it just gives a hollow square and the title code but no graph lines. Why?

When write this code, it is give me a charting but I write new code abot charting it give mi drew the code-related content but removed the graphics lines. For example When I write the chart title code it just gives a hollow square and the title code but no graph lines. Why?

[1]: https://i.stack.imgur.com/iucSs.png


问:
Boost.Signals2 doesn't call connected slot
I have simple variant of testing program what processes some events. If I run code with same way I'll get different behaviour

```<code>class EventBus : public std::enable_shared_from_this<EventBus>
{
    using handlers = boost::signals2::signal<void(std::shared_ptr<EventBase>)>;

private:
    std::atomic<double> m_GameTicks;

    std::thread m_Worker;
    std::mutex m_Locker;
    std::condition_variable m_NewEvent;
    bool m_Suspend;
    std::queue<std::shared_ptr<EventBase>> m_EventStorage;

    std::unordered_map<std::type_index, handlers> m_Subscribers;
    std::shared_ptr<IPrinter> m_InfoPrinter;

public:
    explicit EventBus(std::shared_ptr <IPrinter> printer_impl)
        : m_GameTicks(0.0)
        , m_Suspend(false)
        , m_InfoPrinter(std::move(printer_impl))
    {
        logging::INFO("EventBus");
        m_Worker = std::thread([this]()
        {
            while (true)
            {
                std::shared_ptr<EventBase> event;
                {
                    std::unique_lock guard(m_Locker);
                    m_NewEvent.wait(guard, [this]{ return m_Suspend || !m_EventStorage.empty(); });
                    if (m_Suspend && m_EventStorage.empty())
                    {
                        break;
                    }

                    event = std::move(m_EventStorage.front());
                    m_EventStorage.pop();
                }

                auto raw_event = event.get();
                try
                {
                    m_Subscribers[typeid(*raw_event)](event);
                }
                catch (std::exception& ex)
                {
                    std::cerr << ex.what() << std::endl;
                    std::exit(EXIT_FAILURE);
                }
            }
        });
    }

    ~EventBus()
    {
        m_Worker.join();
    }

    void AddEvent(std::shared_ptr<EventBase>&& event)
    {
        {
            std::lock_guard guard(m_Locker);
            m_EventStorage.push(std::move(event));
        }
        m_NewEvent.notify_one();
    }

    void ProcessEvent([[maybe_unused]] std::shared_ptr<FinishEvent> event)
    {
        {
            std::lock_guard guard(m_Locker);
            m_Suspend = true;
        }
        m_NewEvent.notify_one();
    }

    template <typename TEvent, typename TSubscriber>
    void Subscribe(const std::shared_ptr<TSubscriber>& subscriber)
    {
        m_Subscribers[typeid(TEvent)].connect(
            [subscriber](std::shared_ptr<EventBase> event)
            {
                // work flow didn't go here ???
                subscriber->ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }

    template <typename TEvent>
    void SubscribeSelf()
    {
        m_Subscribers[typeid(TEvent)].connect(
            [this](std::shared_ptr<EventBase> event)
            {
                // work flow went here
                ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }
};

int main(int ac, [[maybe_unused]] char **av)
{
    std::shared_ptr<EventBus> bus = std::make_shared<EventBus(std::make_shared<StdOutPrinter>());

    bus->SubscribeSelf<FinishEvent>(); // OK
//    bus->Subscribe<FinishEvent>(bus); // Fail

    std::vector<std::shared_ptr<EventBase>> events = {
        std::make_shared<FinishEvent>(),
    };

    for (auto& ev : events)
    {
        bus->AddEvent(std::move(ev));
    }
}
</code>```

If I run with using SubscribeSelf, it will OK. But if I run with Subscribe, it fails without calling EventBus destructor and connected slot. EventBus worker thread didn't finish too...  What do I do wrong?

Body:
I have simple variant of testing program what processes some events. If I run code with same way I'll get different behaviour

class EventBus : public std::enable_shared_from_this<EventBus>
{
    using handlers = boost::signals2::signal<void(std::shared_ptr<EventBase>)>;

private:
    std::atomic<double> m_GameTicks;

    std::thread m_Worker;
    std::mutex m_Locker;
    std::condition_variable m_NewEvent;
    bool m_Suspend;
    std::queue<std::shared_ptr<EventBase>> m_EventStorage;

    std::unordered_map<std::type_index, handlers> m_Subscribers;
    std::shared_ptr<IPrinter> m_InfoPrinter;

public:
    explicit EventBus(std::shared_ptr <IPrinter> printer_impl)
        : m_GameTicks(0.0)
        , m_Suspend(false)
        , m_InfoPrinter(std::move(printer_impl))
    {
        logging::INFO("EventBus");
        m_Worker = std::thread([this]()
        {
            while (true)
            {
                std::shared_ptr<EventBase> event;
                {
                    std::unique_lock guard(m_Locker);
                    m_NewEvent.wait(guard, [this]{ return m_Suspend || !m_EventStorage.empty(); });
                    if (m_Suspend && m_EventStorage.empty())
                    {
                        break;
                    }

                    event = std::move(m_EventStorage.front());
                    m_EventStorage.pop();
                }

                auto raw_event = event.get();
                try
                {
                    m_Subscribers[typeid(*raw_event)](event);
                }
                catch (std::exception& ex)
                {
                    std::cerr << ex.what() << std::endl;
                    std::exit(EXIT_FAILURE);
                }
            }
        });
    }

    ~EventBus()
    {
        m_Worker.join();
    }

    void AddEvent(std::shared_ptr<EventBase>&& event)
    {
        {
            std::lock_guard guard(m_Locker);
            m_EventStorage.push(std::move(event));
        }
        m_NewEvent.notify_one();
    }

    void ProcessEvent([[maybe_unused]] std::shared_ptr<FinishEvent> event)
    {
        {
            std::lock_guard guard(m_Locker);
            m_Suspend = true;
        }
        m_NewEvent.notify_one();
    }

    template <typename TEvent, typename TSubscriber>
    void Subscribe(const std::shared_ptr<TSubscriber>& subscriber)
    {
        m_Subscribers[typeid(TEvent)].connect(
            [subscriber](std::shared_ptr<EventBase> event)
            {
                // work flow didn't go here ???
                subscriber->ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }

    template <typename TEvent>
    void SubscribeSelf()
    {
        m_Subscribers[typeid(TEvent)].connect(
            [this](std::shared_ptr<EventBase> event)
            {
                // work flow went here
                ProcessEvent(std::static_pointer_cast<TEvent>(event));
            });
    }
};

int main(int ac, [[maybe_unused]] char **av)
{
    std::shared_ptr<EventBus> bus = std::make_shared<EventBus(std::make_shared<StdOutPrinter>());

    bus->SubscribeSelf<FinishEvent>(); // OK
//    bus->Subscribe<FinishEvent>(bus); // Fail

    std::vector<std::shared_ptr<EventBase>> events = {
        std::make_shared<FinishEvent>(),
    };

    for (auto& ev : events)
    {
        bus->AddEvent(std::move(ev));
    }
}

If I run with using SubscribeSelf, it will OK. But if I run with Subscribe, it fails without calling EventBus destructor and connected slot. EventBus worker thread didn't finish too...  What do I do wrong?


问:
how to listen to audio starting from the feature extractions of the deep learning model?
How can I play audio from model.predict return</p>
```<code>features_test = model.predict(X_test)

x = features_test\[0\]
x = np.expand_dims(x, 0)
ipd.Audio(x\[0,:,0\], rate=16000, autoplay=False)
</code>```

Body:
How can I play audio from model.predict return

features_test = model.predict(X_test)

x = features_test\[0\]
x = np.expand_dims(x, 0)
ipd.Audio(x\[0,:,0\], rate=16000, autoplay=False)