问:
Stacking contest: for some reason child stays on top of parent element (Even though parent has higher z-index)
So basically I need the nav ul to stay under the header (which is his parent). Also,the header is the cyan section with the logo and burger button.`

```<code><html>
<head>
</head>

<body>

<header>
        <section class="header-container">
          <section class="wrap-logo">
            <img src="" alt="" />
          </section>
          <nav>
            <ul id="nav-list-wrapper" class="nav__hide">
              <a href=""><li>Homepage</li></a>
              <a href=""><li>Categories</li></a>
              <a href=""><li>Our Blog</li></a>
              <a href=""><li>Contacts</li></a>
            </ul>
          </nav>
          <section class="wrap-icons">
            <section class="wrap-searchbar" id="wrap-searchbar">
              <input type="text" placeholder="Cerca" class="search-input" />
              <a class="search-btn" href="#">
                <i class="fa-solid fa-magnifying-glass"></i>
              </a>
            </section>
            <i class="fa-solid fa-user"></i>
            <button
              id="btn-hamburger"
              class="hamburger-btn"
              aria-expanded="false"
            >
              <span class="line"></span>
              <span class="line"></span>
              <span class="line"></span>
            </button>
          </section>
        </section>
      </header>
</body>
</html>
</code>```
```<code>header {
    position: fixed;
    top: 0;
    z-index: 999;
  }

  nav ul {
    position: fixed;
    width: 100%;
    height: auto;
    z-index: 9;
    background-color: var(--clr-bg-body);
    flex-direction: column;
    justify-content: center !important;
    align-items: center !important;
    top: 60px;
    left: 0px;
    padding-block: 20px;
    box-shadow: 0px 5px 18px black;
    transition: all 0.5s cubic-bezier(0.215, 0.61, 0.355, 1);
  }
</code>```

`

And I need both of them fixed, but apparentely, even if z-index are one higher than another, nav ul shows up on top of parent. You can tell by the shadow, but you could tell even better if you'd be able to see the animation of the nav ul coming down from outside the screen on top of the header (instead of below it).
header on top and nav ul below

Body:
So basically I need the nav ul to stay under the header (which is his parent). Also,the header is the cyan section with the logo and burger button.`

Homepage

Categories

Our Blog

Contacts

              <input type="text" placeholder="Cerca" class="search-input" />

            <button
              id="btn-hamburger"
              class="hamburger-btn"
              aria-expanded="false"
            >

            </button>

header {
    position: fixed;
    top: 0;
    z-index: 999;
  }

  nav ul {
    position: fixed;
    width: 100%;
    height: auto;
    z-index: 9;
    background-color: var(--clr-bg-body);
    flex-direction: column;
    justify-content: center !important;
    align-items: center !important;
    top: 60px;
    left: 0px;
    padding-block: 20px;
    box-shadow: 0px 5px 18px black;
    transition: all 0.5s cubic-bezier(0.215, 0.61, 0.355, 1);
  }

`

And I need both of them fixed, but apparentely, even if z-index are one higher than another, nav ul shows up on top of parent. You can tell by the shadow, but you could tell even better if you'd be able to see the animation of the nav ul coming down from outside the screen on top of the header (instead of below it).
header on top and nav ul below


来源: stackexchange

问:
Styled Component not rendering properly in NextJS?
I have a navigation bar in NextJS which I define as follows:

```<code>import { useState } from 'react';
import { TomatoButton } from '@/components/button';
import styled from 'styled-components';

const Head = styled.div`
  display: inline-block;
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
  display: block;
`;

export default function Navbar() {
  return (
    <div>
      <TomatoButton as="a" href="#">About</TomatoButton>
    </div>
  );
}

</code>```

where TomatoButton is defined in a separate file:

```<code>import styled from 'styled-components';

export const Button = styled.button`
  display: inline-block;
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
  display: block;
`;

export const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;
</code>```

For whatever reason, it does not seem to be rendering properly (the style is not showing up):

However, according to the Styled Component example I followed, it should render differently.

I am wondering if I'm missing something basic?

ContentLicense: CC BY-SA 4.0

Body:
I have a navigation bar in NextJS which I define as follows:

import { useState } from 'react';
import { TomatoButton } from '@/components/button';
import styled from 'styled-components';

const Head = styled.div`
  display: inline-block;
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
  display: block;
`;

export default function Navbar() {
  return (

      <TomatoButton as="a" href="#">About</TomatoButton>

  );
}

where TomatoButton is defined in a separate file:

import styled from 'styled-components';

export const Button = styled.button`
  display: inline-block;
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
  display: block;
`;

export const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

For whatever reason, it does not seem to be rendering properly (the style is not showing up):

However, according to the Styled Component example I followed, it should render differently.

I am wondering if I'm missing something basic?


问:
Plotly: Draw a horizontal line on a chart when you press it (Jupyter Notebook)
How can I draw a horizontal line on a plotly chart (Jupyter notebook) at the y value where I pressed the chart? I have been trying to use fig_widget, but can't get it to work properly.</p>


问:
encode problem when I use NamedTemporaryFile
I want to create a temporary file then send it to the client. The file I send has an encoding problem. I create a temporary file with the function NamedTemporaryFile().

When I put encoding="utf-8" to NamedTemporaryFile, I get this error:

```<code>** PermissionError: [WinError 32] The process cannot access the file because this file is in use by another process: 'C:\\..\\AppData\\Local\\Temp\\tmpglkdf_2o'
</code>```

( When i don't write encoding="utf-8", all goes well, I can download the file but with encoding problem )

views.py

```<code>from django.http.response import HttpResponse
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
import mimetypes
import pandas as pd
import pdb;

def page(request):
    object = pd.DataFrame(data={"ColumnWithé": ["éà"]})
    fileErr(request, object=object)

def fileErr(request, object=None):
    # Create a temp file
    if(isinstance(object, pd.DataFrame)):
        print("========== IF ==========")
        #pdb.set_trace()
        f = NamedTemporaryFile(delete=False, encoding="utf-8")
        object.to_csv(f, sep=',')
        request.session["errpath"] = f.name.replace("\\","/")
    # Send the temp file when the user click on button
    else:
        print("========== ELSE ==========")
        #pdb.set_trace()
        filename="err.csv"
        file_path = request.session.get("errpath")
        response = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')),
                                        content_type=mimetypes.guess_type(file_path)[0])
        response['Content-Length'] = os.path.getsize(file_path)
        response['Content-Disposition'] = "Attachment;filename=%s" % filename
        return response
</code>```

.html

```<code><a href="{% url 'downloadfile' %}"> <button> download </button> </a>
</code>```

urls.py

```<code> urlpatterns = [
    path("", views.page),
    path("download-file", views.fileErr, name="downloadfile"),
]
</code>```

The result when i don't write encoding="utf-8"

Body:
I want to create a temporary file then send it to the client. The file I send has an encoding problem. I create a temporary file with the function NamedTemporaryFile().

When I put encoding="utf-8" to NamedTemporaryFile, I get this error:

** PermissionError: [WinError 32] The process cannot access the file because this file is in use by another process: 'C:\\..\\AppData\\Local\\Temp\\tmpglkdf_2o'

( When i don't write encoding="utf-8", all goes well, I can download the file but with encoding problem )

views.py

from django.http.response import HttpResponse
from django.http import StreamingHttpResponse
from wsgiref.util import FileWrapper
import mimetypes
import pandas as pd
import pdb;

def page(request):
    object = pd.DataFrame(data={"ColumnWithé": ["éà"]})
    fileErr(request, object=object)

def fileErr(request, object=None):
    # Create a temp file
    if(isinstance(object, pd.DataFrame)):
        print("========== IF ==========")
        #pdb.set_trace()
        f = NamedTemporaryFile(delete=False, encoding="utf-8")
        object.to_csv(f, sep=',')
        request.session["errpath"] = f.name.replace("\\","/")
    # Send the temp file when the user click on button
    else:
        print("========== ELSE ==========")
        #pdb.set_trace()
        filename="err.csv"
        file_path = request.session.get("errpath")
        response = StreamingHttpResponse(FileWrapper(open(file_path, 'rb')),
                                        content_type=mimetypes.guess_type(file_path)[0])
        response['Content-Length'] = os.path.getsize(file_path)
        response['Content-Disposition'] = "Attachment;filename=%s" % filename
        return response

.html

 <button> download </button>

urls.py

 urlpatterns = [
    path("", views.page),
    path("download-file", views.fileErr, name="downloadfile"),
]

The result when i don't write encoding="utf-8"


问:
Telegram: check authorization hash mismatch
I'm trying to use javascript to implement this Telegram PHP example, but the hashes don't match. I ran the example's php code; it also failed, and the hash returned by the example and mine are identical. I'm wondering if it has anything to do with my bot settings (I set my domain to 127.0.0.1 and try another https domain - still failed). I'm completely stuck and have no idea how to make it work.

My code is as follows:

```<code>'use strict';

const sha256 = require('crypto-js/sha256');
const hmacSHA256 = require('crypto-js/hmac-sha256');
const Hex = require('crypto-js/enc-hex');

const { ValidationError } = require('objection');

const data = {
id: 5528016998,
first_name: 'Lê Văn',
last_name: 'Hùng',
username: 'HungLV46',
photo_url: 'https://t.me/i/userpic/320/gy_L5Q2zLLZyUrtCw0Fh9D0oy0CuabiM2A0-68FY27Inz94yP7ypxCrAF7G7_asy.jpg',
auth_date: 1670774122,
hash: '893e4bd66128d8696d63aa285b0aff6e8b970cbe9c9e43dacfa9e2da7420c16c'
};

function verifyAuthorization(params) {
if ((new Date() - new Date(params.auth_date * 1000)) > 86400000) { // milisecond
    throw new ValidationError('Authorization data is outdated');
}

const verificationParams = { ...params };
delete verificationParams.hash;

const message = Object.keys(verificationParams)
    .map(key => `${key}=${verificationParams[key]}`)
    .sort().join('\n');
const secretKey = sha256('xxxx'); // replace with the token of my bot
const hash = Hex.stringify(hmacSHA256(message, secretKey));

if (hash !== params.hash) {
    throw new ValidationError('Authorization data is not from telegram!');
}
}

verifyAuthorization(data);
</code>```

similar question

Edit:

After experimenting with the login widget for some time, I tried to print return value to the developer console of Chrome (pressing f12, console tab), and then run my code again. The 2 hashes awardly match!.

I initially got the user info and hash from the response of this API, POST https://oauth.telegram.org/auth/get?bot_id=xxx in network-tab, and it turned out the response of API in network-tab was different from the response printed in console-tab.

I tried some more time, and the response of the API suddenly worked well with my function. Now I am just curious about why?

Body:
I'm trying to use javascript to implement this Telegram PHP example, but the hashes don't match. I ran the example's php code; it also failed, and the hash returned by the example and mine are identical. I'm wondering if it has anything to do with my bot settings (I set my domain to 127.0.0.1 and try another https domain - still failed). I'm completely stuck and have no idea how to make it work.

My code is as follows:

'use strict';

const sha256 = require('crypto-js/sha256');
const hmacSHA256 = require('crypto-js/hmac-sha256');
const Hex = require('crypto-js/enc-hex');

const { ValidationError } = require('objection');

const data = {
id: 5528016998,
first_name: 'Lê Văn',
last_name: 'Hùng',
username: 'HungLV46',
photo_url: 'https://t.me/i/userpic/320/gy_L5Q2zLLZyUrtCw0Fh9D0oy0CuabiM2A0-68FY27Inz94yP7ypxCrAF7G7_asy.jpg',
auth_date: 1670774122,
hash: '893e4bd66128d8696d63aa285b0aff6e8b970cbe9c9e43dacfa9e2da7420c16c'
};

function verifyAuthorization(params) {
if ((new Date() - new Date(params.auth_date * 1000)) > 86400000) { // milisecond
    throw new ValidationError('Authorization data is outdated');
}

const verificationParams = { ...params };
delete verificationParams.hash;

const message = Object.keys(verificationParams)
    .map(key => `${key}=${verificationParams[key]}`)
    .sort().join('\n');
const secretKey = sha256('xxxx'); // replace with the token of my bot
const hash = Hex.stringify(hmacSHA256(message, secretKey));

if (hash !== params.hash) {
    throw new ValidationError('Authorization data is not from telegram!');
}
}

verifyAuthorization(data);

similar question

Edit:

After experimenting with the login widget for some time, I tried to print return value to the developer console of Chrome (pressing f12, console tab), and then run my code again. The 2 hashes awardly match!.

I initially got the user info and hash from the response of this API, POST https://oauth.telegram.org/auth/get?bot_id=xxx in network-tab, and it turned out the response of API in network-tab was different from the response printed in console-tab.

I tried some more time, and the response of the API suddenly worked well with my function. Now I am just curious about why?


问:
bert custom entity model , find confidence score for all words for particular entity in text
i have build custom entity recognition model using Bert. I have trained model with 2 custom entity geography and other

I ran below command to predict custom entities in sentence
prediction, model_output = model.predict(["Where is Pakistanio "])

prediction-
[[{'Where': 'O'}, {'is': 'O'}, {'Pakistanio': 'O'}]]

when i print model_output. I'm getting below response

```<code>[[{'Where': [[4.37, -3.977]]},{'is': [[4.484, -4.305]]},{'Pakistanio': [[0.1176, -0.6206], [0.74, -1.063]]}]]
</code>```

Is there a way in which i can find confidence score for both custom entity for all words so we if it is not able to identity correct custom entity i can take top 3 values

Also can anyone please let me know for model_output negative value stands for which value

Body:
i have build custom entity recognition model using Bert. I have trained model with 2 custom entity geography and other

I ran below command to predict custom entities in sentence
prediction, model_output = model.predict(["Where is Pakistanio "])

prediction-
[[{'Where': 'O'}, {'is': 'O'}, {'Pakistanio': 'O'}]]

when i print model_output. I'm getting below response

[[{'Where': [[4.37, -3.977]]},{'is': [[4.484, -4.305]]},{'Pakistanio': [[0.1176, -0.6206], [0.74, -1.063]]}]]

Is there a way in which i can find confidence score for both custom entity for all words so we if it is not able to identity correct custom entity i can take top 3 values

Also can anyone please let me know for model_output negative value stands for which value


问:
How do I properly reuse the connection and client object throughout my project in Rust?
I am trying to create my postgres client and functions in it's own db.rs file. I then want to be able to call the functions from other files within my application without having to recreate the database connection/client.
Here is the code I currently have:

```<code>//File: db.rs
async fn init_db() -> Result<(tokio_postgres::Client), Error> {
    // Connect to the database.
    let (client, connection) =
        tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;

    // The connection object performs the actual communication with the database,
    // so spawn it off to run on its own.
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });
    Ok(client)
}
</code>```

I understand what tokio::spawn is doing with the connection object... moving it to it's own thread for concurrency... or at least managing that under the hood for me based on my Tokio configuration.

Although, I'm not quite sure how to preserve the "client" object that I am returning from the function, to later use in async DB functions. Obviously, the client is going to still need the connection. Am I supposed to return the connection and the client and then store them into a variable in my main.rs? So like:

```<code>// File: main.rs
let (client, connection) = crate::db::init_db();
</code>```

or do I just need to grab the client?

```<code>File: main.rs
let client = crate::db::init_db();
</code>```

So now, which is the proper way to reuse this throughout my whole project? Or did I even set this up right? Do I use an Arc or something?

I was thinking I would create the "DB functions" inside the db.rs file. The functions would require the client object to be passed as a reference into it. Looking like:

```<code>// File: db.rs
async pub fn get_user(client: &tokio_postgres::Client, user_name: String) -> Result<User, Error> {
let rows = client.query("SELECT * FROM users WHERE user_name = $1", &[&user_name]).await?;
let user_id = rows[0].get[0];
let user_name = rows[0].get[1];
let user = User {
user_id
user_name
};
user
}
</code>```

So, if I want to call this function from other files OTHER than main.rs, would I reinitilize the connection for each file in my project that needs to use the DB? I feel like I should only need to create ONE connection/client... and somehow use that throughout my whole app.

```<code>// File: client.rs
struct User {
user_id: i32
user_name: String
};
let conn = db::init_db();
let found_user: User = db::get_user(conn, String::from("AdminUser");
</code>```

If someone could give me some best-practice guidance on how to do this I would appreciate it, thank you!

Body:
I am trying to create my postgres client and functions in it's own db.rs file. I then want to be able to call the functions from other files within my application without having to recreate the database connection/client.
Here is the code I currently have:

//File: db.rs
async fn init_db() -> Result<(tokio_postgres::Client), Error> {
    // Connect to the database.
    let (client, connection) =
        tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;

    // The connection object performs the actual communication with the database,
    // so spawn it off to run on its own.
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });
    Ok(client)
}

I understand what tokio::spawn is doing with the connection object... moving it to it's own thread for concurrency... or at least managing that under the hood for me based on my Tokio configuration.

Although, I'm not quite sure how to preserve the "client" object that I am returning from the function, to later use in async DB functions. Obviously, the client is going to still need the connection. Am I supposed to return the connection and the client and then store them into a variable in my main.rs? So like:

// File: main.rs
let (client, connection) = crate::db::init_db();

or do I just need to grab the client?

File: main.rs
let client = crate::db::init_db();

So now, which is the proper way to reuse this throughout my whole project? Or did I even set this up right? Do I use an Arc or something?

I was thinking I would create the "DB functions" inside the db.rs file. The functions would require the client object to be passed as a reference into it. Looking like:

// File: db.rs
async pub fn get_user(client: &tokio_postgres::Client, user_name: String) -> Result<User, Error> {
let rows = client.query("SELECT * FROM users WHERE user_name = $1", &[&user_name]).await?;
let user_id = rows[0].get[0];
let user_name = rows[0].get[1];
let user = User {
user_id
user_name
};
user
}

So, if I want to call this function from other files OTHER than main.rs, would I reinitilize the connection for each file in my project that needs to use the DB? I feel like I should only need to create ONE connection/client... and somehow use that throughout my whole app.

// File: client.rs
struct User {
user_id: i32
user_name: String
};
let conn = db::init_db();
let found_user: User = db::get_user(conn, String::from("AdminUser");

If someone could give me some best-practice guidance on how to do this I would appreciate it, thank you!


问:
Is there a way to programatically get the emoji unicode starting from css?
I have to get the Emoji unicode starting from some css, like that:

```<code>    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
     class="smilie smilie--sprite smilie--sprite2" alt=";)" title="Wink    ;)" loading="lazy"
     data-shortname=";)">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
     class="smilie smilie--sprite smilie--sprite3" alt=":(" title="Frown    :(" loading="lazy"
     data-shortname=":(">
</code>```

In the first case it is possible, because the first word of the title (wink), is the short name for the emoji.
In the second case, the title does not correspond to the short name of the emoji.

Someone knows if this is possible?

thanks in advance.

Body:
I have to get the Emoji unicode starting from some css, like that:

In the first case it is possible, because the first word of the title (wink), is the short name for the emoji.
In the second case, the title does not correspond to the short name of the emoji.

Someone knows if this is possible?

thanks in advance.


问:
Reuse aiohttp socket in separate process
I've noticed that it is possible to reuse a socket in another process by using the sockets' fileno attribute (given socket module).

However, I cannot find a way to achieve the same using aiohttp... how can I reuse sockets from one process in another by passing e.g. a fileno?

The idea is that I want the first process to lose the access to the socket (without closing) and start reusing the connection in another process.


问:
I want to use GridSearchCV to find best parameters and predict two methods
My code is below:

import numpy as np
import matplotlib.pyplot as plt

from sklearn.svm import SVC
from sklearn.linear_model import Lasso

from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score

from sklearn.datasets import make_moons

n = 300
n_tr = 200
X, y = make_moons(n, shuffle=True, noise=0.2, random_state=112)
y[y==0] = -1

# standardise the data
trmean = np.mean(X[:n_tr, :], axis=0)
trvar = np.var(X[:n_tr, :], axis=0)
X = (X - trmean[np.newaxis, :]) / np.sqrt(trvar)[np.newaxis, :]

# take first n_tr as training, others as test.
Xtr = X[:n_tr, :]
ytr = y[:n_tr]
Xt = X[n_tr:, :]
yt = y[n_tr:]

# the parameters to consider in cross-validation
# order lasso params from largest to smallest so that if ties occur CV will select the one with more sparsity
params_lasso = [1, 1e-1, 1e-2, 1e-3, 1e-4]
params_rbf = [1e-3, 1e-2, 1e-1, 1, 10, 100]
params_svm = [1e-3, 1e-2, 1e-1, 1, 10, 100, 1000]  # smaller C: more regularisation

# the noisy features to be considered; for n noisy features, add the first n columns
n_tot_noisy_feats = 50
np.random.seed(92)
X_noise = 2*np.random.randn(X.shape[0], n_tot_noisy_feats)
Xtr_noise = X_noise[:n_tr, :]
Xt_noise = X_noise[n_tr:, :]

svm_accs=[]
lasso_accs=[]
lasso_n_feats=[]
amount_of_noise_feature=np.arange(n_tot_noisy_feats+1)
k=5
for n_nosie_feats in amount_of_noise_feature:
    print(n_nosie_feats)
    Xtr_noisy = np.copy(Xtr)
    Xt_nosiy = np.copy(Xt)
    if n_nosie_feats > 0:
        Xtr_noisy = np.hstack((Xtr_noisy, Xtr_noise[:,:n_nosie_feats]))
        Xt_nosiy = np.hstack((Xt_nosiy, Xt_noise[:,:n_nosie_feats]))
    lasso_valid_accs = np.zeros((k, len(params_lasso)))
    svm_valid_accs = np.zeros((k, len(params_rbf), len(params_svm)))

    from sklearn.model_selection import GridSearchCV

    cscv_lasso=GridSearchCV(Lasso(),{"alpha":params_lasso},scoring='accuracy',cv=KFold(5))
    cscv_lasso.fit(Xtr_noisy,ytr)
    cscv_lassopreds=np.sign(cscv_lasso.best_estimator_.predict(Xt_nosiy))

    cscv_svm = GridSearchCV(SVC(), {"C": params_svm,"gamma":params_rbf},scoring='accuracy', cv=KFold(5))
    cscv_svm.fit(Xtr_noisy, ytr)
```
<p>Which results in this error message:</p>
<pre class="lang-py prettyprint-override"><code>  UserWarning,
/usr/local/lib/python3.6/dist-packages/sklearn/model_selection/_validation.py:700: UserWarning: Scoring failed. The score on this train-test partition for these parameters will be set to nan. Details:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/sklearn/model_selection/_validation.py", line 687, in _score
    scores = scorer(estimator, X_test, y_test)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_scorer.py", line 200, in __call__
    sample_weight=sample_weight)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_scorer.py", line 243, in _score
    **self._kwargs)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py", line 63, in inner_f
    return f(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py", line 202, in accuracy_score
    y_type, y_true, y_pred = _check_targets(y_true, y_pred)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py", line 93, in _check_targets
    "and {1} targets".format(type_true, type_pred))
ValueError: Classification metrics can't handle a mix of binary and continuous targets
</code>```

What is the lowest amount of noisy features added to the original data, when Lasso accuracy on test set is better than SVM?
It seems that the the predict is weird.

```<code>best lasso parameters: {'alpha': 0.1}
best svm params: {'C': 100, 'gamma': 0.001}
</code>```

I want to find the best param for Lasso and SVC, and the corresponding accuracy_score when noisy features added to the original data.

Body:
My code is below:

import numpy as np
import matplotlib.pyplot as plt

from sklearn.svm import SVC
from sklearn.linear_model import Lasso

from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score

from sklearn.datasets import make_moons

n = 300
n_tr = 200
X, y = make_moons(n, shuffle=True, noise=0.2, random_state=112)
y[y==0] = -1

# standardise the data
trmean = np.mean(X[:n_tr, :], axis=0)
trvar = np.var(X[:n_tr, :], axis=0)
X = (X - trmean[np.newaxis, :]) / np.sqrt(trvar)[np.newaxis, :]

# take first n_tr as training, others as test.
Xtr = X[:n_tr, :]
ytr = y[:n_tr]
Xt = X[n_tr:, :]
yt = y[n_tr:]

# the parameters to consider in cross-validation
# order lasso params from largest to smallest so that if ties occur CV will select the one with more sparsity
params_lasso = [1, 1e-1, 1e-2, 1e-3, 1e-4]
params_rbf = [1e-3, 1e-2, 1e-1, 1, 10, 100]
params_svm = [1e-3, 1e-2, 1e-1, 1, 10, 100, 1000]  # smaller C: more regularisation

# the noisy features to be considered; for n noisy features, add the first n columns
n_tot_noisy_feats = 50
np.random.seed(92)
X_noise = 2*np.random.randn(X.shape[0], n_tot_noisy_feats)
Xtr_noise = X_noise[:n_tr, :]
Xt_noise = X_noise[n_tr:, :]

svm_accs=[]
lasso_accs=[]
lasso_n_feats=[]
amount_of_noise_feature=np.arange(n_tot_noisy_feats+1)
k=5
for n_nosie_feats in amount_of_noise_feature:
    print(n_nosie_feats)
    Xtr_noisy = np.copy(Xtr)
    Xt_nosiy = np.copy(Xt)
    if n_nosie_feats > 0:
        Xtr_noisy = np.hstack((Xtr_noisy, Xtr_noise[:,:n_nosie_feats]))
        Xt_nosiy = np.hstack((Xt_nosiy, Xt_noise[:,:n_nosie_feats]))
    lasso_valid_accs = np.zeros((k, len(params_lasso)))
    svm_valid_accs = np.zeros((k, len(params_rbf), len(params_svm)))

    from sklearn.model_selection import GridSearchCV

    cscv_lasso=GridSearchCV(Lasso(),{"alpha":params_lasso},scoring='accuracy',cv=KFold(5))
    cscv_lasso.fit(Xtr_noisy,ytr)
    cscv_lassopreds=np.sign(cscv_lasso.best_estimator_.predict(Xt_nosiy))

    cscv_svm = GridSearchCV(SVC(), {"C": params_svm,"gamma":params_rbf},scoring='accuracy', cv=KFold(5))
    cscv_svm.fit(Xtr_noisy, ytr)

Which results in this error message:

  UserWarning,
/usr/local/lib/python3.6/dist-packages/sklearn/model_selection/_validation.py:700: UserWarning: Scoring failed. The score on this train-test partition for these parameters will be set to nan. Details:
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/sklearn/model_selection/_validation.py", line 687, in _score
    scores = scorer(estimator, X_test, y_test)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_scorer.py", line 200, in __call__
    sample_weight=sample_weight)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_scorer.py", line 243, in _score
    **self._kwargs)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py", line 63, in inner_f
    return f(*args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py", line 202, in accuracy_score
    y_type, y_true, y_pred = _check_targets(y_true, y_pred)
  File "/usr/local/lib/python3.6/dist-packages/sklearn/metrics/_classification.py", line 93, in _check_targets
    "and {1} targets".format(type_true, type_pred))
ValueError: Classification metrics can't handle a mix of binary and continuous targets

What is the lowest amount of noisy features added to the original data, when Lasso accuracy on test set is better than SVM?
It seems that the the predict is weird.

best lasso parameters: {'alpha': 0.1}
best svm params: {'C': 100, 'gamma': 0.001}

I want to find the best param for Lasso and SVC, and the corresponding accuracy_score when noisy features added to the original data.


问:
Spring application.yaml and boolean values through env file
In my Spring Boot project, I have to pass to application.yaml file the SHOW_SQL boolean value from an environment file.

Here is application.yaml

```<code>spring:
  ...
  show-sql: ${SHOW_SQL}
  ...

server:
  port: 8080
</code>```

Here is my env file (used to start the spring app)

```<code>SHOW_SQL=true
</code>```

During the mvn test process I receive this error

```<code>Failed to bind properties under 'spring.jpa.show-sql' to boolean:
    Property: spring.jpa.show-sql
    Value: "${SHOW_SQL}"
    Origin: class path resource [application.yaml] - 13:15
    Reason: failed to convert java.lang.String to boolean (caused by java.lang.IllegalArgumentException: Invalid boolean value '${SHOW_SQL}')
Action:
Update your application's configuration
</code>```

Is there a way to use boolean values from an .env file and pass them to the application yaml?

Body:
In my Spring Boot project, I have to pass to application.yaml file the SHOW_SQL boolean value from an environment file.

Here is application.yaml

spring:
  ...
  show-sql: ${SHOW_SQL}
  ...

server:
  port: 8080

Here is my env file (used to start the spring app)

SHOW_SQL=true

During the mvn test process I receive this error

Failed to bind properties under 'spring.jpa.show-sql' to boolean:
    Property: spring.jpa.show-sql
    Value: "${SHOW_SQL}"
    Origin: class path resource [application.yaml] - 13:15
    Reason: failed to convert java.lang.String to boolean (caused by java.lang.IllegalArgumentException: Invalid boolean value '${SHOW_SQL}')
Action:
Update your application's configuration

Is there a way to use boolean values from an .env file and pass them to the application yaml?


问:
Can object of an abstract class be constructed in Java?
In Java, I created an abstract class name Media. This class is used for abstract method for class DigitalVideoDisc, Book and CompactDisc. From class name Cart, I created an array list ArrayList itemsOrdered to store the media in cart. I think we can't create object for that ArrayList like this:

```<code>ArrayList<Media> itemsOrdered = new ArrayList<Media> ();
</code>```

. But Eclipse didn't notice that's an error. As I known, we can't create object like that. Please explain for me.

I read tutorials from W3 school but it also written that it is not possible to create an object of the Abstract class. I don't understand this because of my problem.

Media class
Cart class where I created ArrayList for Media

Body:
In Java, I created an abstract class name Media. This class is used for abstract method for class DigitalVideoDisc, Book and CompactDisc. From class name Cart, I created an array list ArrayList itemsOrdered to store the media in cart. I think we can't create object for that ArrayList like this:

ArrayList<Media> itemsOrdered = new ArrayList<Media> ();

. But Eclipse didn't notice that's an error. As I known, we can't create object like that. Please explain for me.

I read tutorials from W3 school but it also written that it is not possible to create an object of the Abstract class. I don't understand this because of my problem.

Media class
Cart class where I created ArrayList for Media


问:
Unable to connect to iOS simulator & run Flutter app

Previously in XCode there has been these warning messages with yellow warning icon. Back then,  I was able to run my Flutter app on iOS simulator just fine. Now that they have become red, I can't run it on iOS simulator anymore. And there's No Devices listed anymore as shown below.

Is there a way to revert the iOS configurations in Flutter to the default? Or is any better way?


问:
Vue3 + Vite. How to transpile dependencies?
I have a Vue 3 project that uses Vite.

NPM package that I want to use requires me to modify vue.config.js and do the following:

```<code>module.exports = {
    transpileDependencies: ['@jsonforms/core', '@jsonforms/vue2', '@jsonforms/vue2-vanilla']
}
</code>```

However, Vite projects don't use vue.config.js, instead they have vite.config.js (I assume they are not equivalent in what they do).

How do I configure such NPM package to work in Vite based Vue projects?

Body:
I have a Vue 3 project that uses Vite.

NPM package that I want to use requires me to modify vue.config.js and do the following:

module.exports = {
    transpileDependencies: ['@jsonforms/core', '@jsonforms/vue2', '@jsonforms/vue2-vanilla']
}

However, Vite projects don't use vue.config.js, instead they have vite.config.js (I assume they are not equivalent in what they do).

How do I configure such NPM package to work in Vite based Vue projects?


问:
Playwright: "Test Timeout Exceeded Error" when 5 or 6 similar type of test cases are included in one file
So, I am writing automation script in playwright using TypeScript. Each of the testcases are running perfectly but when I try to execute more similar testcases at once, it is showing Timeout error after executing 2/3 testcases. I want to know the approach of how I can write multiple testcases on a single file without having any timeout issues. I am attaching some example code snippets.

```<code>import { test, expect, Locator } from '@playwright/test';
import { waitFor } from '@testing-library/react';

let businessSidebar: Locator;
let search: Locator;
let advanceFilter: Locator;

test.beforeEach(async({ page }) => {
    await page.goto('/');

    //login
    await page.locator("input[name='email']").fill('admin@gmail.com');
    await page.locator("input[name='password']").fill('admin');
    await page.locator("button:text('Login')").click();

    businessSidebar = page.locator('text=Business Profile');
    await businessSidebar.click();

    search = page.locator("input[name='search']");
    advanceFilter = page.locator("//button[text()='Filters']")

})

test.skip('Verify user can filter business profile by: Industries', async({ page }) => {
    const industryFilter = await page.locator("(//button[contains(@class,'flex w-full')])[1]");
    await industryFilter.click();

    const select = await page.locator("//span[text()='Agriculture and Fisheries']");
    await select.click();

    await expect(page).toHaveURL(`http://localhost:3000/dashboard/business`);
})

test.skip('Verify user can filter business profile by: Business Type', async({ page }) => {
    const businessTypeFilter = await page.locator("(//button[contains(@class,'flex w-full')])[2]");
    await businessTypeFilter.click();

    const select = await page.locator("//span[text()='Association']");
    await select.click();

    await expect(page).toHaveURL(`http://localhost:3000/dashboard/business`);
})

</code>```

These testcases are running perfectly. The error occurs after adding 2/3 more similar type of testcases. The timeout is occurs in the befoEach() scope.

My timeout is set as below. I have also tried to increase the timeout.

```<code>timeout: 40 * 1000,
  expect: {
    /**
     * Maximum time expect() should wait for the condition to be met.
     * For example in `await expect(locator).toHaveText();`
     */
    timeout: 5000
  },
</code>```

I tried using waitForTimeout() in every testcases but the result remains the same. I am asking for an approch so that I can solve this issue.

Body:
So, I am writing automation script in playwright using TypeScript. Each of the testcases are running perfectly but when I try to execute more similar testcases at once, it is showing Timeout error after executing 2/3 testcases. I want to know the approach of how I can write multiple testcases on a single file without having any timeout issues. I am attaching some example code snippets.

import { test, expect, Locator } from '@playwright/test';
import { waitFor } from '@testing-library/react';

let businessSidebar: Locator;
let search: Locator;
let advanceFilter: Locator;

test.beforeEach(async({ page }) => {
    await page.goto('/');

    //login
    await page.locator("input[name='email']").fill('admin@gmail.com');
    await page.locator("input[name='password']").fill('admin');
    await page.locator("button:text('Login')").click();

    businessSidebar = page.locator('text=Business Profile');
    await businessSidebar.click();

    search = page.locator("input[name='search']");
    advanceFilter = page.locator("//button[text()='Filters']")

})

test.skip('Verify user can filter business profile by: Industries', async({ page }) => {
    const industryFilter = await page.locator("(//button[contains(@class,'flex w-full')])[1]");
    await industryFilter.click();

    const select = await page.locator("//span[text()='Agriculture and Fisheries']");
    await select.click();

    await expect(page).toHaveURL(`http://localhost:3000/dashboard/business`);
})

test.skip('Verify user can filter business profile by: Business Type', async({ page }) => {
    const businessTypeFilter = await page.locator("(//button[contains(@class,'flex w-full')])[2]");
    await businessTypeFilter.click();

    const select = await page.locator("//span[text()='Association']");
    await select.click();

    await expect(page).toHaveURL(`http://localhost:3000/dashboard/business`);
})

These testcases are running perfectly. The error occurs after adding 2/3 more similar type of testcases. The timeout is occurs in the befoEach() scope.

My timeout is set as below. I have also tried to increase the timeout.

timeout: 40 * 1000,
  expect: {
    /**
     * Maximum time expect() should wait for the condition to be met.
     * For example in `await expect(locator).toHaveText();`
     */
    timeout: 5000
  },

I tried using waitForTimeout() in every testcases but the result remains the same. I am asking for an approch so that I can solve this issue.


问:
what is the fastest ffmpeg video codec for decoding?
I am using ffmpeg on Linux to transcode video files.  The files are video from a race car camera.  They have been downloaded from Youtube as "webm" format.  I want to compare two of the videos, side-by-side, using GridPlayer, which uses vlc as its underlying video processor.  GridPlayer has very nice, frame-by-frame controls, but, they are very slow.  What video codec should I use to impose the least decoding overhead on vlc/GridPlayer for smoother playback?

I have tried re-encoding as h264, 1920x1080, 30 fps, in mp4 container.  I have since discovered a "-tune fastdecode" option that seems to be helpful, along with resizing to 854x480.  Any other suggestions?


问:
What does a PC byte order of a binary file mean?

Intro

I want to program a parser on Windows in C++ that parses a binary file. It is a star catalog that stores the data in its own binary format (see http://tdc-www.harvard.edu/catalogs/bsc5.html).

Various binary files are made available, each with the following information:

Sun/Mac byte order

Sun/Alpha byte order

PC byte order

Problem

I know the difference between big and little endian, but the terms Sun/Mac, Sun/Alpha and PC byte order mean nothing to me. How can an already with bytes filled file have an PC byte order? What is PC (my current PC or Mac or IBM etc.) and what byte order should I proceed with?


问:
dotnet core configuration alternatives
I needed to write to appsettings.json and started using https://github.com/labrador999/WritableOptions.Net, however I am running into issues (not reading the file on my user defined path when injected into class, its a blank object).

I am now looking to simplifying by modifying appsettings.json and using IOptionsMonitor to detect changes to the file - this is starting to detract from writing application code.

Any known tried and tested methods to do the above? Any pitfalls to be aware of?

Alternatively, I had a quick look for config frameworks and have come across https://github.com/aloneguid/config

In addition to Config.net are there any other libraries that for dotnet configuration that support writing as a foundational concept from the start?

Title: dotnet core configuration alternatives


问:
Datadog alerts | Slack notifications
I have set up event-based alerting on Datadog and notifications on slack.

I am receiving 2 events triggered this monitor, here is the last one.
I want both events' data to show, not just the last one.
Alert screenshot

Can someone help me here, please?

I did not find anything as of now

Title: Datadog alerts | Slack notifications


问:
How do I fix this SQLite error: SQLite Error 1: 'table "StudentCourses" already exists'
I'm creating a CRUD project in asp.net entity framework, and from my understanding, in order to see the data on the HTML page I have to scaffold the pages. For example I have two entity models Student and Major

This is the Student entity

```<code>public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("Major")]
    public int? MajorId { get; set; }
    public Major Major { get; set; }

    [ForeignKey("Advisor")]
    public int AdvisorId { get; set; }
    public Advisor Advisor { get; set; }

    public ICollection<StudentCourses>? StudentCourses { get; set; }

}
</code>```

This is the Major entity

```<code>public class Major
{
    public int MajorId { get; set; }
    public string MajorName { get; set; }

    public ICollection<Student> Students { get; set; }
    public ICollection<Advisor> Advisors { get; set; }
    public ICollection<MajorCourse> MajorCourses { get; set; }
}
</code>```

If I want to see the Student data I have to create a Students folder and add a new Scaffolding along with a DbContext like your_namespace.Data.StudentContext. I would also have to follow the same steps for the Major entity but am I correct to use another DbContext? For example: your_namespace.Data.MajorContext. This is what I have done but when I try to make migrations and update the database in the your_namespace.Data.MajorContext, I get an error that reads SQLite Error 1: 'table "StudentCourses" already exists'.`

How do I fix this error?
I should also add the Context classes:
This is the StudentContext class:

```<code>public class AdvismentContext : DbContext
{
    public AdvismentContext(DbContextOptions<AdvismentContext> options)
        : base(options)
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Major> Majors { get; set; }
    public DbSet<Advisor> Advisors { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<MajorCourse> MajorCourses { get; set; }
    public DbSet <StudentCourses> StudentCourses{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .ToTable("Students");

        modelBuilder.Entity<Major>()
            .ToTable("Majors");

        modelBuilder.Entity<Advisor>()
            .ToTable("Advisors");

        modelBuilder.Entity<Course>()
            .ToTable("Courses");

        //modelBuilder.Entity<MajorCourse>()
        //    .ToTable("MajorCourse");

            //.HasKey(mc => new { mc.MajorId, mc.CourseId });

    }
</code>```

And this is the MajorContext class:

```<code>public class MajorContext : DbContext
{
    public MajorContext (DbContextOptions<MajorContext> options)
        : base(options)
    {
    }

    public DbSet<Advisment.Models.Major> Major { get; set; } = default!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Major>()
            .ToTable("Major");

        //modelBuilder.Entity<MajorCourse>() This is commented out because I was getting the same error that the table already exists.
        //    .ToTable("MajorCourse");
    }

}
</code>```

What am I doing wrong?

Body:
I'm creating a CRUD project in asp.net entity framework, and from my understanding, in order to see the data on the HTML page I have to scaffold the pages. For example I have two entity models Student and Major

This is the Student entity

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("Major")]
    public int? MajorId { get; set; }
    public Major Major { get; set; }

    [ForeignKey("Advisor")]
    public int AdvisorId { get; set; }
    public Advisor Advisor { get; set; }

    public ICollection<StudentCourses>? StudentCourses { get; set; }

}

This is the Major entity

public class Major
{
    public int MajorId { get; set; }
    public string MajorName { get; set; }

    public ICollection<Student> Students { get; set; }
    public ICollection<Advisor> Advisors { get; set; }
    public ICollection<MajorCourse> MajorCourses { get; set; }
}

If I want to see the Student data I have to create a Students folder and add a new Scaffolding along with a DbContext like your_namespace.Data.StudentContext. I would also have to follow the same steps for the Major entity but am I correct to use another DbContext? For example: your_namespace.Data.MajorContext. This is what I have done but when I try to make migrations and update the database in the your_namespace.Data.MajorContext, I get an error that reads SQLite Error 1: 'table "StudentCourses" already exists'.`

How do I fix this error?
I should also add the Context classes:
This is the StudentContext class:

public class AdvismentContext : DbContext
{
    public AdvismentContext(DbContextOptions<AdvismentContext> options)
        : base(options)
    {
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Major> Majors { get; set; }
    public DbSet<Advisor> Advisors { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<MajorCourse> MajorCourses { get; set; }
    public DbSet <StudentCourses> StudentCourses{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .ToTable("Students");

        modelBuilder.Entity<Major>()
            .ToTable("Majors");

        modelBuilder.Entity<Advisor>()
            .ToTable("Advisors");

        modelBuilder.Entity<Course>()
            .ToTable("Courses");

        //modelBuilder.Entity<MajorCourse>()
        //    .ToTable("MajorCourse");

            //.HasKey(mc => new { mc.MajorId, mc.CourseId });

    }

And this is the MajorContext class:

public class MajorContext : DbContext
{
    public MajorContext (DbContextOptions<MajorContext> options)
        : base(options)
    {
    }

    public DbSet<Advisment.Models.Major> Major { get; set; } = default!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Major>()
            .ToTable("Major");

        //modelBuilder.Entity<MajorCourse>() This is commented out because I was getting the same error that the table already exists.
        //    .ToTable("MajorCourse");
    }

}

What am I doing wrong?


问:
How to read only keys from firebase database using recycler view in android studio
I want to read only keys from the firebase database to recycler view in android studio
How to do it please

like this how to read only "jawad" not his children


问:
How to get all the items present in a folder in google drive and also their respective download links in dart or flutter
Get all those folder names in the form of list as the output after fetching from the link.
The link is of a google drive folder which contains some pdf files and the task is to fetch all the pdf file names and return in the form of list.

Also the download link of each pdf file should be returned.

All of these should be worked with flutter/dart

If any other details needed please comment below


问:
Using Action in Controller every 10min
I am new to programming with ASP.NET MVC.

I want to write a function in the view in which makes sure that a specific action in the controller gets called.

Is this possible in ASP.NET MVC?

Title: Using Action in Controller every 10min


问:
I am trying to display a choropleth map in jupyter notebook however nothing is showing up
I have one dataset with state and counts.
And I have imported the geojson of UK cities into UK_city. I have linked the two (json and dataset with the country id (column 'id'). The simplified dataset is:

This is my dataset with the count of vehicle crime in each city

I have written this code with aim to plot the count on each city of the country, However, no error is being displayed neither any map is showing up.

I have tried solutions like using firefox to display it but nothing seems to work.

I have downloaded the geojson from here:
https://geoportal.statistics.gov.uk/datasets/ons::wards-dec-2015-full-extent-boundaries-in-gb/explore?location=55.081966%2C-3.262780%2C6.00


问:
How to Plot 2 columns in x axis grouped in area stacked chart using Pandas
I have set of data with 3 columns Label, Year and Total. My total count is based on the group of label and year.

```<code>+--------------------+-------+-------+
|               Label|   Year|  Total|
+--------------------+-------+-------+
|                 FTP|02/2018| 193360|
|              BBBB  |01/1970|     14|
|              BBBB  |02/2018|4567511|
|                SSSS|02/2018| 187589|
|                Dddd|02/2018|  41508|
</code>```

I want to plot the data like in this below image.

enter image description here

How to achieve this with stacked area chart in Pandas python. ( my x-axis should have both my label and year values and based on that grouping of y-axis should plot values )

The code I tried with seaborn as well normal

```<code>dF.plot(figsize=(20,8), x ='Label', y ='Total', kind = 'area', stacked = True)
</code>```
```<code>ax = df.plot(x="label", y="Total", legend=False, figsize=(10,8))
ax2 = ax.twinx()
df.plot(x="label", y="Dst_Port", ax=ax2, legend=False, color="r", figsize=(10,8))
ax.figure.legend()
plt.show()
</code>```

My current graph can plot with single x-axis column value.

Body:
I have set of data with 3 columns Label, Year and Total. My total count is based on the group of label and year.

+--------------------+-------+-------+
|               Label|   Year|  Total|
+--------------------+-------+-------+
|                 FTP|02/2018| 193360|
|              BBBB  |01/1970|     14|
|              BBBB  |02/2018|4567511|
|                SSSS|02/2018| 187589|
|                Dddd|02/2018|  41508|

I want to plot the data like in this below image.

enter image description here

How to achieve this with stacked area chart in Pandas python. ( my x-axis should have both my label and year values and based on that grouping of y-axis should plot values )

The code I tried with seaborn as well normal

dF.plot(figsize=(20,8), x ='Label', y ='Total', kind = 'area', stacked = True)

ax = df.plot(x="label", y="Total", legend=False, figsize=(10,8))
ax2 = ax.twinx()
df.plot(x="label", y="Dst_Port", ax=ax2, legend=False, color="r", figsize=(10,8))
ax.figure.legend()
plt.show()

My current graph can plot with single x-axis column value.


问:
How can I work with a parameter that has a * in front of it in pyton?
I have a class Com

```<code>class Com:
    def __init__(self, a: float, b: float):
        self.a = a
        self.b = b
</code>```

and in the class this function:

```<code>def add(comp: "Comp", *comps: "Com") -> "Com":
</code>```

with this input:

```<code>c1 = Com(5.0, 10.0)
c2 = Com(7.0, 100.0)
c_sum = Com.add(c1, c1, c2, Com(33.75, -14.25))
</code>```

I don't understand how I can access the parameters of the add() function and work with them. Can someone explain it?

Body:
I have a class Com

class Com:
    def __init__(self, a: float, b: float):
        self.a = a
        self.b = b

and in the class this function:

def add(comp: "Comp", *comps: "Com") -> "Com":

with this input:

c1 = Com(5.0, 10.0)
c2 = Com(7.0, 100.0)
c_sum = Com.add(c1, c1, c2, Com(33.75, -14.25))

I don't understand how I can access the parameters of the add() function and work with them. Can someone explain it?


问:
Error in `select()`: ! object 'Sibling_1' not found
I am trying to change the name of a variable within a loop using select(). This is the code:

```<code> sibling_list2 = paste0("Sibling_", unlist(sibling2))
 for(s in 2:length(sibling_list2))  {

      dbAppendTable(conPrueba, paste0("EW_x", y),
                    dat %>%
                      inner_join(child2 %>% filter(relcode == 1) %>%
                                   select(rel_f_person_id = person_id, person_id = sibling_list[s], (sibling_list[s] = Sibling_1), sibling_list),
                                 by = c("person_id", "rel_f_person_id")))

    }
</code>```

However I get the error "Error in select():
! object 'Sibling_1' not found
Run rlang::last_error() to see where the error occurred." even though the object Sibling_1 exists.

The problem seems to be in "(sibling_list[s] = Sibling_1)". If i delete the parentheses I get another error saying "Error: unexpected '=' in:...". I also tried using the functions mutate() and rename(), but they have the same error.

Body:
I am trying to change the name of a variable within a loop using select(). This is the code:

 sibling_list2 = paste0("Sibling_", unlist(sibling2))
 for(s in 2:length(sibling_list2))  {

      dbAppendTable(conPrueba, paste0("EW_x", y),
                    dat %>%
                      inner_join(child2 %>% filter(relcode == 1) %>%
                                   select(rel_f_person_id = person_id, person_id = sibling_list[s], (sibling_list[s] = Sibling_1), sibling_list),
                                 by = c("person_id", "rel_f_person_id")))

    }

However I get the error "Error in select():
! object 'Sibling_1' not found
Run rlang::last_error() to see where the error occurred." even though the object Sibling_1 exists.

The problem seems to be in "(sibling_list[s] = Sibling_1)". If i delete the parentheses I get another error saying "Error: unexpected '=' in:...". I also tried using the functions mutate() and rename(), but they have the same error.


问:
RStudio server on AWS has a white screen, can't access data to remove .RData/.RHistory
I have been running an RStudio Server for a few months and when I tried to login again it gave me a white screen (after the login page). I can't access the code or files on the AWS instance.

I am happy to install a fresh RStudio server but I would like to access the files (before I was accessing them through RStudio file manager.

I have tried connecting to the instance online but I get the following error.

I have tried many things but nothing seems to have worked.

In session manager I get the following:

```<code>We weren't able to connect to your instance. Common reasons for this include:
SSM Agent isn't installed on the instance. You can install the agent on both Windows instances and Linux instances.
The required IAM instance profile isn't attached to the instance. You can attach a profile using AWS Systems Manager Quick Setup.
Session Manager setup is incomplete. For more information, see Session Manager Prerequisites.
</code>```

I also have not been able to SSH into my instance. I have tried creating pem files to try and access it, changing permissions and security groups but I can't seem to acess it. In my terminal I have the following error:

```<code>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'id_rsa.pub.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "id_rsa.pub.pem": bad permissions
ubuntu@ec2-35-181-152-160.eu-west-3.compute.amazonaws.com: Permission denied (publickey).
</code>```

After running: ssh -i "id_rsa.pub.pem" ubuntu@ec2-00-000-000-000.eu-west-3.compute.amazonaws.com

EDIT 1:

I get the following:

```<code>(base) bscuser@localhost:myfolder/s3_AWS/s3_AWS> chmod 600 id_rsa.pub.pem
(base) bscuser@localhost:myfolder/s3_AWS> ssh -i "id_rsa.pub.pem" ubuntu@ec2-00-000-000-000.eu-west-3.compute.amazonaws.com
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'id_rsa.pub.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "id_rsa.pub.pem": bad permissions
ubuntu@ec2-00-000-000-00.eu-west-3.compute.amazonaws.com: Permission denied (publickey).
(base) bscuser@localhost:myfolder/s3_AWS/s3_AWS>
</code>```

Body:
I have been running an RStudio Server for a few months and when I tried to login again it gave me a white screen (after the login page). I can't access the code or files on the AWS instance.

I am happy to install a fresh RStudio server but I would like to access the files (before I was accessing them through RStudio file manager.

I have tried connecting to the instance online but I get the following error.

I have tried many things but nothing seems to have worked.

In session manager I get the following:

We weren't able to connect to your instance. Common reasons for this include:
SSM Agent isn't installed on the instance. You can install the agent on both Windows instances and Linux instances.
The required IAM instance profile isn't attached to the instance. You can attach a profile using AWS Systems Manager Quick Setup.
Session Manager setup is incomplete. For more information, see Session Manager Prerequisites.

I also have not been able to SSH into my instance. I have tried creating pem files to try and access it, changing permissions and security groups but I can't seem to acess it. In my terminal I have the following error:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'id_rsa.pub.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "id_rsa.pub.pem": bad permissions
ubuntu@ec2-35-181-152-160.eu-west-3.compute.amazonaws.com: Permission denied (publickey).

After running: ssh -i "id_rsa.pub.pem" ubuntu@ec2-00-000-000-000.eu-west-3.compute.amazonaws.com

EDIT 1:

I get the following:

(base) bscuser@localhost:myfolder/s3_AWS/s3_AWS> chmod 600 id_rsa.pub.pem
(base) bscuser@localhost:myfolder/s3_AWS> ssh -i "id_rsa.pub.pem" ubuntu@ec2-00-000-000-000.eu-west-3.compute.amazonaws.com
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'id_rsa.pub.pem' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "id_rsa.pub.pem": bad permissions
ubuntu@ec2-00-000-000-00.eu-west-3.compute.amazonaws.com: Permission denied (publickey).
(base) bscuser@localhost:myfolder/s3_AWS/s3_AWS>


问:
Should I use std::pmr::vector of pointers or std::pmr::deque of objects?
Recently, I asked for a code review of my Graph class where I use std::pmr::monotonic_buffer_resource with std::pmr::vector of pointers to Nodes Edges and Pins classes.

struct Node;
struct Edge;
struct Pin;

struct Graph {
    //Same approach with ArenaAllocate is used for allocating edges and pins
    Node* AddNode(const std::string_view name)
    {
        auto node = ArenaAllocate<Node>(*this, name);
        nodes.push_back(node);
        return node;
    }

    template<typename T, size_t alignment = alignof(T), typename ... Args>
    [[nodiscard]] T* ArenaAllocate(Args&& ... args)
    {
        void* const p = linearArena.allocate(sizeof(T), alignment);
        return p ? new(p) T(std::forward<Args>(args)...) : nullptr;
    }

    std::pmr::monotonic_buffer_resource arena{ 1024 * 1024 };
    std::pmr::vector<Node*> nodes{&arena};
    std::pmr::vector<Pin*> pins{&arena};
    std::pmr::vector<Edge*> edges{&arena};
};
```
<p>and the answer was to use <code>std::pmr::deque</code> or <code>std::pmr::list</code> instead of <code>std::pmr::vector</code> to have stable memory addresses and objects instead of pointers.</p>
<p>https://codereview.stackexchange.com/a/281841/266548 -> see the first statement</p>
<p>So I did a quick benchmark. I keep the more/less original <code>Node</code> implementation, because its size may be important</p>
<pre class="lang-cpp prettyprint-override"><code>#include <benchmark/benchmark.h>

#include <memory_resource>
#include <deque>

struct Node
{
    Node(const std::size_t id, std::string_view name)
        : name(name), id(id)
    {}

    std::vector<std::size_t> inputs{ 1, 2, 3, 4, 5 };
    std::vector<std::size_t> outputs{ 5, 4, 3, 2, 1 };

    const std::string name;

    std::uint32_t refCount = 0;
    const std::size_t id = 0;
    bool target = false;
};

static constexpr size_t count = 10000;

static void BM_PMRVectorIterator(benchmark::State& state) {
    std::pmr::monotonic_buffer_resource arena{ 1024 * 1024 };
    std::pmr::vector<Node*> nodes{ &arena };

    for (std::size_t i = 0; i < count; ++i) {
        void* const p = arena.allocate(sizeof(Node), alignof(Node));
        auto node = new (p) Node(i, "hello");
        nodes.push_back(node);
    }

    for (auto _ : state) {
        for (int i = 0; i < count; ++i) {
            nodes[i]->refCount = i;
            nodes[i]->refCount++;
        }
    }
}
BENCHMARK(BM_PMRVectorIterator);

static void BM_PMRDequeIterator(benchmark::State& state) {
    std::pmr::monotonic_buffer_resource arena{ 1024 * 1024 };
    std::pmr::deque<Node> nodes(&arena);

    for (int i = 0; i < count; ++i) nodes.emplace_back(i, "Hello");

    for (auto _ : state) {
        for (int i = 0; i < count; ++i) {
            nodes[i].refCount = i;
            nodes[i].refCount++;
        }
    }
}
BENCHMARK(BM_PMRDequeIterator);

BENCHMARK_MAIN();
</code>```

and iterating over std::pmr::deque<Node> is much more slower:

---------------------------------------------------------------
Benchmark                     Time             CPU   Iterations
---------------------------------------------------------------
BM_PMRVectorIterator     131711 ns        92076 ns        11200
BM_PMRDequeIterator     1288377 ns      1293945 ns          640
```

I don't know what to think about it, because both std::pmr::vector<Node*> and std::pmr::deqeue<Node> don't change much in code usage, but these benchmarks scared me.

The linear allocator should assure that Node*s are allocated next to each other, I guess, so there won't be a cache miss.

I want to build a graphical editor for these nodes, pins and edges, so I can't go without iterating over nodes, pins and edges.

What should I do to have a fast and memory-friendly system?

Body:
Recently, I asked for a code review of my Graph class where I use std::pmr::monotonic_buffer_resource with std::pmr::vector of pointers to Nodes Edges and Pins classes.

struct Node;
struct Edge;
struct Pin;

struct Graph {
    //Same approach with ArenaAllocate is used for allocating edges and pins
    Node* AddNode(const std::string_view name)
    {
        auto node = ArenaAllocate<Node>(*this, name);
        nodes.push_back(node);
        return node;
    }

    template<typename T, size_t alignment = alignof(T), typename ... Args>
    [[nodiscard]] T* ArenaAllocate(Args&& ... args)
    {
        void* const p = linearArena.allocate(sizeof(T), alignment);
        return p ? new(p) T(std::forward<Args>(args)...) : nullptr;
    }

    std::pmr::monotonic_buffer_resource arena{ 1024 * 1024 };
    std::pmr::vector<Node*> nodes{&arena};
    std::pmr::vector<Pin*> pins{&arena};
    std::pmr::vector<Edge*> edges{&arena};
};

and the answer was to use std::pmr::deque or std::pmr::list instead of std::pmr::vector to have stable memory addresses and objects instead of pointers.

https://codereview.stackexchange.com/a/281841/266548 -> see the first statement

So I did a quick benchmark. I keep the more/less original Node implementation, because its size may be important

#include <benchmark/benchmark.h>

#include <memory_resource>
#include <deque>

struct Node
{
    Node(const std::size_t id, std::string_view name)
        : name(name), id(id)
    {}

    std::vector<std::size_t> inputs{ 1, 2, 3, 4, 5 };
    std::vector<std::size_t> outputs{ 5, 4, 3, 2, 1 };

    const std::string name;

    std::uint32_t refCount = 0;
    const std::size_t id = 0;
    bool target = false;
};

static constexpr size_t count = 10000;

static void BM_PMRVectorIterator(benchmark::State& state) {
    std::pmr::monotonic_buffer_resource arena{ 1024 * 1024 };
    std::pmr::vector<Node*> nodes{ &arena };

    for (std::size_t i = 0; i < count; ++i) {
        void* const p = arena.allocate(sizeof(Node), alignof(Node));
        auto node = new (p) Node(i, "hello");
        nodes.push_back(node);
    }

    for (auto _ : state) {
        for (int i = 0; i < count; ++i) {
            nodes[i]->refCount = i;
            nodes[i]->refCount++;
        }
    }
}
BENCHMARK(BM_PMRVectorIterator);

static void BM_PMRDequeIterator(benchmark::State& state) {
    std::pmr::monotonic_buffer_resource arena{ 1024 * 1024 };
    std::pmr::deque<Node> nodes(&arena);

    for (int i = 0; i < count; ++i) nodes.emplace_back(i, "Hello");

    for (auto _ : state) {
        for (int i = 0; i < count; ++i) {
            nodes[i].refCount = i;
            nodes[i].refCount++;
        }
    }
}
BENCHMARK(BM_PMRDequeIterator);

BENCHMARK_MAIN();

and iterating over std::pmr::deque<Node> is much more slower:

---------------------------------------------------------------
Benchmark                     Time             CPU   Iterations
---------------------------------------------------------------
BM_PMRVectorIterator     131711 ns        92076 ns        11200
BM_PMRDequeIterator     1288377 ns      1293945 ns          640

I don't know what to think about it, because both std::pmr::vector<Node*> and std::pmr::deqeue<Node> don't change much in code usage, but these benchmarks scared me.

The linear allocator should assure that Node*s are allocated next to each other, I guess, so there won't be a cache miss.

I want to build a graphical editor for these nodes, pins and edges, so I can't go without iterating over nodes, pins and edges.

What should I do to have a fast and memory-friendly system?


问:
Emit Socket Io send event from diffrent files with SvelteKit Websocket implementation
I have followed this tutorial
https://joyofcode.xyz/using-websockets-with-sveltekit
and implemented a basic websocket server that sends a message to the client when he connects.
I want to also send a message when someone submits a form.

```<code>

// socketIo.ts.js
import { Server } from 'socket.io';
let io
export function injectSocketIO(server) {
    io = new Server(server);

    io.on('connection', (socket) => {
      socket.emit('eventFromServer', 'Hello, World ')
    });

    console.log('SocketIO injected');
}

export function send(sms){
  io.emit('eventFromServer', sms);
}
export function getIO(){return io}

</code>```
```<code>//vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';

import { injectSocketIO } from './socketIo.js';
import { Server } from 'socket.io'
const webSocketServer = {
  name: 'webSocketServer',
  configureServer(server) {
    injectSocketIO(server.httpServer);
  },
}

const config: UserConfig = {
    plugins: [sveltekit(), webSocketServer]
};

export default config;

</code>```
```<code>//my form action

import { send } from './socketIo.ts'
export const actions = {
  default: async({ request }) =>{
    console.log(send('da'))
</code>```

I'm getting this error

```<code>Cannot read properties of undefined (reading 'emit')
TypeError: Cannot read properties of undefined (reading 'emit')
    at Module.send (/home/runner/sveltekit-cpp/socketIo.ts:17:5)
    at default (/home/runner/sveltekit-cpp/src/routes/+page.server.ts:10:16)
    at call_action (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js:204:9)
    at handle_action_request (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js:134:22)
    at render_page (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/page/index.js:65:26)
    at async resolve (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/index.js:247:17)
    at async respond (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/index.js:298:20)
    at async file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:418:22
</code>```

I have tried exporting a send function from my socketIo file but it didn't work

Body:
I have followed this tutorial
https://joyofcode.xyz/using-websockets-with-sveltekit
and implemented a basic websocket server that sends a message to the client when he connects.
I want to also send a message when someone submits a form.

// socketIo.ts.js
import { Server } from 'socket.io';
let io
export function injectSocketIO(server) {
    io = new Server(server);

    io.on('connection', (socket) => {
      socket.emit('eventFromServer', 'Hello, World ')
    });

    console.log('SocketIO injected');
}

export function send(sms){
  io.emit('eventFromServer', sms);
}
export function getIO(){return io}

//vite.config.ts
import { sveltekit } from '@sveltejs/kit/vite';
import type { UserConfig } from 'vite';

import { injectSocketIO } from './socketIo.js';
import { Server } from 'socket.io'
const webSocketServer = {
  name: 'webSocketServer',
  configureServer(server) {
    injectSocketIO(server.httpServer);
  },
}

const config: UserConfig = {
    plugins: [sveltekit(), webSocketServer]
};

export default config;

//my form action

import { send } from './socketIo.ts'
export const actions = {
  default: async({ request }) =>{
    console.log(send('da'))

I'm getting this error

Cannot read properties of undefined (reading 'emit')
TypeError: Cannot read properties of undefined (reading 'emit')
    at Module.send (/home/runner/sveltekit-cpp/socketIo.ts:17:5)
    at default (/home/runner/sveltekit-cpp/src/routes/+page.server.ts:10:16)
    at call_action (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js:204:9)
    at handle_action_request (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/page/actions.js:134:22)
    at render_page (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/page/index.js:65:26)
    at async resolve (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/index.js:247:17)
    at async respond (file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/runtime/server/index.js:298:20)
    at async file:///home/runner/sveltekit-cpp/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:418:22

I have tried exporting a send function from my socketIo file but it didn't work


问:
How does gridDB ensures that 100% of the data is persisted?
How does gridDB ensures that 100% of the data is persisted on storage as it follows memory first and storage second approach? or is it susceptible to data loss in case of sudden shutdowns?

The gridDB documentation is not very clear on it or may be I didn’t find anything related.


问:
Changing datetime64[ns] data type to timestamp with am pm
I have data in this format ... 2022-11-29 16:15:02

When I run print(df.dtypes) command on my dataset, it shows me data type as datetime64[ns].

I need to change it to show in AM / PM format... like...

"2022-11-29 04:15:02 PM"

Please support.

I have tried using... df['Order Completed At'] = pd.to_datetime(df['Order Completed At']).strftime('%I:%M:%S')

But, I am getting error...

AttributeError: 'Series' object has no attribute 'strftime'


问:
How to check for correct MongoDb collection name
The MongoDb client.db.collection("collectionName") method automatically creates the collection if it does not exist, which is great for the first time one accesses it, and not helpful in catching errors in the future.

I was bitten by a spelling error in the collection name, e.g. client.db.collection("colectionName"), and want to check the return value before then performing the CRUD action.

It seems as though there are CollectionOptions I can pass in, but there is no obvious option that specifies "return null / throw error if collection does not exist", which makes me think I'm doing it wrong.


问:
Not geeting data in formData append in Angular using jspdf
`
I am using jspdf to generate pdf would like to send to node server for file upload but not getting correct formData value after appending blob from jspdf.  What am I doing wrong ?
``

```<code>    let DATA: any = document.getElementById('htmlData');
    html2canvas(DATA).then((canvas) => {
      let fileWidth = 208;
      let fileHeight = (canvas.height * fileWidth) / canvas.width;
      const FILEURI = canvas.toDataURL('image/png');
      let PDF: any = new jsPDF('p', 'mm', 'a4');
      let position = 0;
      //PDF.addImage(FILEURI, 'JPEG', 10, position, fileWidth, fileHeight);
      PDF.addImage(FILEURI, 'PNG', 10, position, fileWidth, fileHeight);
      // Save the pdf as a blob
      const blob = PDF.output('blob');
      const formData:FormData = new FormData()
      formData.append('file', blob, 'hello-world.pdf');

      console.log(formData) // getting blank that is => FormData {}
    });
  }```
```

I have tried different approaches suggested by different answers but could not get desired formData with appended value.

Body:
`
I am using jspdf to generate pdf would like to send to node server for file upload but not getting correct formData value after appending blob from jspdf.  What am I doing wrong ?
``

    let DATA: any = document.getElementById('htmlData');
    html2canvas(DATA).then((canvas) => {
      let fileWidth = 208;
      let fileHeight = (canvas.height * fileWidth) / canvas.width;
      const FILEURI = canvas.toDataURL('image/png');
      let PDF: any = new jsPDF('p', 'mm', 'a4');
      let position = 0;
      //PDF.addImage(FILEURI, 'JPEG', 10, position, fileWidth, fileHeight);
      PDF.addImage(FILEURI, 'PNG', 10, position, fileWidth, fileHeight);
      // Save the pdf as a blob
      const blob = PDF.output('blob');
      const formData:FormData = new FormData()
      formData.append('file', blob, 'hello-world.pdf');

      console.log(formData) // getting blank that is => FormData {}
    });
  }```

I have tried different approaches suggested by different answers but could not get desired formData with appended value.


问:
how to change return value type declarations when the method rewrite with decorator in typescript
```<code>const Addon = (target, name) => {
  Object.defineProperty(target, name, {
    value() {
      return {
        a: 1,
        b: 2,
      };
    },
  });
};

class Test {
  @Addon
  public fn() {
    return {
      a: 1,
    };
  }
}

const test = new Test();

const result = test.fn();

console.log(result.b);

</code>```

thats code, when i call fn, it weill return {a: 1, b: 2}, if i take fn.b, typescript will throw an Error: Property 'b' does not exist on type '{ a: number; }'

though i can use any to pass the error... but thats not a good way...

how can i fix that?

thank

Body:
const Addon = (target, name) => {
  Object.defineProperty(target, name, {
    value() {
      return {
        a: 1,
        b: 2,
      };
    },
  });
};

class Test {
  @Addon
  public fn() {
    return {
      a: 1,
    };
  }
}

const test = new Test();

const result = test.fn();

console.log(result.b);

thats code, when i call fn, it weill return {a: 1, b: 2}, if i take fn.b, typescript will throw an Error: Property 'b' does not exist on type '{ a: number; }'

though i can use any to pass the error... but thats not a good way...

how can i fix that?

thank


问:
Parsing json data in flutter
Hi I have a json file from where I am retrieving data I have different keys in different json array
I wanna show the key along side data inside that

Main to focus is appDetails Like in first json array It has 3 keys systemOverview benefits and mainFeatures.

But in next array it doesn't have system overview have other keys.

What I wanna do is show both key and data correspondance to that

{
  "name": "Parts",
  "category": "Production",
  "subcategory": "Productivity",
  "imageUrl": "PI-Banner.jpg",
  "logo": "PI.png",
  "description": "(PI) is an application for easy & effective Quality.The application is supported on Android tablet devices and iPads.",
  "appDetails": [
    {
      "systemOverview": "pi_overview.jpg",
      "Benefits": [
        {
          "label": "Multi-lingual support"
        },
        {
          "label": "Support for different screen sizes"
        }
      ],
      "mainFeatures": [

        {
          "label": "Import details"
        }

      ]
    }

  ]
},
{
  "name": "Feedback System",
  "category": "Production",
  "subcategory": "Productivity",
  "imageUrl": "ADFbanner.jpg",
  "description": "A smartphone and tablet-based solution to register",
  "appDetails": [
    {

      "testing": [
        {
          "label": "Multi-Device"
        },
        {
          "label": "Multi-Lingual"
        },
        {
          "label": "Multi-Database"
        }
      ],
      "mainScreen": [

        {
          "label": "Select failure codes"
        },
        {
          "label": "Add comments & take evidence Pictures"
        },

      ]
    }
  ]
},
```
<p><strong>ProductModel</strong> is the Model class generated by </p>
```import 'package:flutter/material.dart';

import '../../models/models.dart';
class TestingScreen extends StatefulWidget {
  final ProductModel item;
  const TestingScreen({Key? key, required this.item}) : super(key: key);

  @override
  State<TestingScreen> createState() => _TestingScreenState();
}

class _TestingScreenState extends State<TestingScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:  Container(
        decoration: const BoxDecoration(
            border: Border(
                left: BorderSide(
                    width: 5,
                    color: Color(0xffD9D9D9)))),
        child: Padding(
          padding: const EdgeInsets.symmetric(
              horizontal: 10.0),
          child: Expanded(
            child: SizedBox(
              width: 240,
              height: 130,
              child: ListView.builder(
                itemCount:
                widget.item.appDetails?.length,
                itemBuilder: (context, index) {
                  final detail =
                  widget.item.appDetails?[index];
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment:
                      CrossAxisAlignment.start,
                      children:
                      (detail?.mainFeatures ?? [])
                          .map((e) {
                        // final index = (details?.multiDeviceSupport ?? []).indexOf(e);
                        return Row(
                          children: [
                            SizedBox(
                                width: 20,
                                child: Text(
                                    '${index + 1}.',
                                    style: Theme.of(
                                        context)
                                        .textTheme
                                        .bodyText1!
                                        .copyWith(
                                        fontWeight:
                                        FontWeight
                                            .w300))),
                            Expanded(
                              flex: 2,
                              child: Text('${e.label}',
                                  style: Theme.of(
                                      context)
                                      .textTheme
                                      .bodyText1!
                                      .copyWith(
                                      fontWeight:
                                      FontWeight
                                          .w300,
                                      overflow:
                                      TextOverflow
                                          .clip)),
                            ),
                          ],
                        );
                      }).toList(),
                    ),
                  );
                  // BuildProduct(: detail);
                  //buildProduct(detail);
                },
              ),
            ),
          ),
        ),

      ),
    );
  }
}

```
<p>Currently this is what I have done so far i.e. <strong>using map Check listview</strong></p>
```class ProductModel {
  ProductModel({
    String? name,
    String? category,
    String? subcategory,
    String? imageUrl,
    String? logo,
    String? description,
    List<AppDetails>? appDetails,
    List<Region>? region,
  }) {
    _name = name;
    _category = category;
    _subcategory = subcategory;
    _imageUrl = imageUrl;
    _logo = logo;
    _description = description;
    _appDetails = appDetails;
    _region = region;
  }

  ProductModel.fromJson(dynamic json) {
    _name = json['name'];
    _category = json['category'];
    _subcategory = json['subcategory'];
    _imageUrl = json['imageUrl'];
    _logo = json['logo'];
    _description = json['description'];
    if (json['appDetails'] != null) {
      _appDetails = [];
      json['appDetails'].forEach((v) {
        _appDetails?.add(AppDetails.fromJson(v));
      });
    }
    if (json['region'] != null) {
      _region = [];
      json['region'].forEach((v) {
        _region?.add(Region.fromJson(v));
      });
    }
  }
  String? _name;
  String? _category;
  String? _subcategory;
  String? _imageUrl;
  String? _logo;
  String? _description;
  List<AppDetails>? _appDetails;
  List<Region>? _region;
  ProductModel copyWith({
    String? name,
    String? category,
    String? subcategory,
    String? imageUrl,
    String? logo,
    String? description,
    List<AppDetails>? appDetails,
    List<Region>? region,
  }) =>
      ProductModel(
        name: name ?? _name,
        category: category ?? _category,
        subcategory: subcategory ?? _subcategory,
        imageUrl: imageUrl ?? _imageUrl,
        logo: logo ?? _logo,
        description: description ?? _description,
        appDetails: appDetails ?? _appDetails,
        region: region ?? _region,
      );
  String? get name => _name;
  String? get category => _category;
  String? get subcategory => _subcategory;
  String? get imageUrl => _imageUrl;
  String? get logo => _logo;
  String? get description => _description;
  List<AppDetails>? get appDetails => _appDetails;
  List<Region>? get region => _region;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['name'] = _name;
    map['category'] = _category;
    map['subcategory'] = _subcategory;
    map['imageUrl'] = _imageUrl;
    map['logo'] = _logo;
    map['description'] = _description;
    if (_appDetails != null) {
      map['appDetails'] = _appDetails?.map((v) => v.toJson()).toList();
    }
    if (_region != null) {
      map['region'] = _region?.map((v) => v.toJson()).toList();
    }
    return map;
  }
}
```

Title: Parsing json data in flutter

Body:
Hi I have a json file from where I am retrieving data I have different keys in different json array
I wanna show the key along side data inside that

Main to focus is appDetails Like in first json array It has 3 keys systemOverview benefits and mainFeatures.

But in next array it doesn't have system overview have other keys.

What I wanna do is show both key and data correspondance to that

{
  "name": "Parts",
  "category": "Production",
  "subcategory": "Productivity",
  "imageUrl": "PI-Banner.jpg",
  "logo": "PI.png",
  "description": "(PI) is an application for easy & effective Quality.The application is supported on Android tablet devices and iPads.",
  "appDetails": [
    {
      "systemOverview": "pi_overview.jpg",
      "Benefits": [
        {
          "label": "Multi-lingual support"
        },
        {
          "label": "Support for different screen sizes"
        }
      ],
      "mainFeatures": [

        {
          "label": "Import details"
        }

      ]
    }

  ]
},
{
  "name": "Feedback System",
  "category": "Production",
  "subcategory": "Productivity",
  "imageUrl": "ADFbanner.jpg",
  "description": "A smartphone and tablet-based solution to register",
  "appDetails": [
    {

      "testing": [
        {
          "label": "Multi-Device"
        },
        {
          "label": "Multi-Lingual"
        },
        {
          "label": "Multi-Database"
        }
      ],
      "mainScreen": [

        {
          "label": "Select failure codes"
        },
        {
          "label": "Add comments & take evidence Pictures"
        },

      ]
    }
  ]
},

ProductModel is the Model class generated by

import 'package:flutter/material.dart';

import '../../models/models.dart';
class TestingScreen extends StatefulWidget {
  final ProductModel item;
  const TestingScreen({Key? key, required this.item}) : super(key: key);

  @override
  State<TestingScreen> createState() => _TestingScreenState();
}

class _TestingScreenState extends State<TestingScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:  Container(
        decoration: const BoxDecoration(
            border: Border(
                left: BorderSide(
                    width: 5,
                    color: Color(0xffD9D9D9)))),
        child: Padding(
          padding: const EdgeInsets.symmetric(
              horizontal: 10.0),
          child: Expanded(
            child: SizedBox(
              width: 240,
              height: 130,
              child: ListView.builder(
                itemCount:
                widget.item.appDetails?.length,
                itemBuilder: (context, index) {
                  final detail =
                  widget.item.appDetails?[index];
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment:
                      CrossAxisAlignment.start,
                      children:
                      (detail?.mainFeatures ?? [])
                          .map((e) {
                        // final index = (details?.multiDeviceSupport ?? []).indexOf(e);
                        return Row(
                          children: [
                            SizedBox(
                                width: 20,
                                child: Text(
                                    '${index + 1}.',
                                    style: Theme.of(
                                        context)
                                        .textTheme
                                        .bodyText1!
                                        .copyWith(
                                        fontWeight:
                                        FontWeight
                                            .w300))),
                            Expanded(
                              flex: 2,
                              child: Text('${e.label}',
                                  style: Theme.of(
                                      context)
                                      .textTheme
                                      .bodyText1!
                                      .copyWith(
                                      fontWeight:
                                      FontWeight
                                          .w300,
                                      overflow:
                                      TextOverflow
                                          .clip)),
                            ),
                          ],
                        );
                      }).toList(),
                    ),
                  );
                  // BuildProduct(: detail);
                  //buildProduct(detail);
                },
              ),
            ),
          ),
        ),

      ),
    );
  }
}

Currently this is what I have done so far i.e. using map Check listview

class ProductModel {
  ProductModel({
    String? name,
    String? category,
    String? subcategory,
    String? imageUrl,
    String? logo,
    String? description,
    List<AppDetails>? appDetails,
    List<Region>? region,
  }) {
    _name = name;
    _category = category;
    _subcategory = subcategory;
    _imageUrl = imageUrl;
    _logo = logo;
    _description = description;
    _appDetails = appDetails;
    _region = region;
  }

  ProductModel.fromJson(dynamic json) {
    _name = json['name'];
    _category = json['category'];
    _subcategory = json['subcategory'];
    _imageUrl = json['imageUrl'];
    _logo = json['logo'];
    _description = json['description'];
    if (json['appDetails'] != null) {
      _appDetails = [];
      json['appDetails'].forEach((v) {
        _appDetails?.add(AppDetails.fromJson(v));
      });
    }
    if (json['region'] != null) {
      _region = [];
      json['region'].forEach((v) {
        _region?.add(Region.fromJson(v));
      });
    }
  }
  String? _name;
  String? _category;
  String? _subcategory;
  String? _imageUrl;
  String? _logo;
  String? _description;
  List<AppDetails>? _appDetails;
  List<Region>? _region;
  ProductModel copyWith({
    String? name,
    String? category,
    String? subcategory,
    String? imageUrl,
    String? logo,
    String? description,
    List<AppDetails>? appDetails,
    List<Region>? region,
  }) =>
      ProductModel(
        name: name ?? _name,
        category: category ?? _category,
        subcategory: subcategory ?? _subcategory,
        imageUrl: imageUrl ?? _imageUrl,
        logo: logo ?? _logo,
        description: description ?? _description,
        appDetails: appDetails ?? _appDetails,
        region: region ?? _region,
      );
  String? get name => _name;
  String? get category => _category;
  String? get subcategory => _subcategory;
  String? get imageUrl => _imageUrl;
  String? get logo => _logo;
  String? get description => _description;
  List<AppDetails>? get appDetails => _appDetails;
  List<Region>? get region => _region;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};
    map['name'] = _name;
    map['category'] = _category;
    map['subcategory'] = _subcategory;
    map['imageUrl'] = _imageUrl;
    map['logo'] = _logo;
    map['description'] = _description;
    if (_appDetails != null) {
      map['appDetails'] = _appDetails?.map((v) => v.toJson()).toList();
    }
    if (_region != null) {
      map['region'] = _region?.map((v) => v.toJson()).toList();
    }
    return map;
  }
}


问:
How to enable qgrid extension for jupyter notebook without me interacting with windows command prompt?
qgrid requires me to run this line "jupyter nbextension enable — py qgrid — sys-prefix" from CMD, in order to enable this extension in Jupyter Notebook.

However, this qgrid module is not stored in the default python installation folder, but is located in a designated folder within my windows computer.

What would be the code to instruct Jupyter to search for qgrid module from a designated folder and to enable this extension? The code has to be processed from either .py or .ipynb file without needing me to directly key into command prompt.

I have thought of indirectly running the command line from Jupyter Notebook using this code:
subprocess.call('jupyter nbextension enable — py qgrid — sys-prefix',shell=True)

But how do I instruct Jupyter to search for qgrid module from my designated folder as part of the above command line?


问:
When I change the value of a variable, why does it not affect the array I put it in?
I tried several different methods none work, I was trying to get the values to change on the fly so I can change the HSV values live to adjust for noise and inaccuracies. The values change fine but it doesn't update the color mask thresholds, I really dont know what else to try, any help would be greatly appreciated!</p>
```<code>import numpy as np
import cv2 as cv

def change_hueL(value1L):
    global hueL
    hueL = value1L
    print("huel: ", hueL)

def change_satL(value2L):
    global satL
    satL = value2L
    print("satL:", satL)

def change_valL(value3L):
    global valL
    valL = value3L
    print("valL: ", valL)

def change_hueU(value1U):
    global hueU
    hueU = value1U
    print("hueU: ", hueU)

def change_satU(value2U):
    global satU
    satU = value2U
    print("satU: ", satU)

def change_valU(value3U):
    global valU
    valU = value3U
    print("valU: ", valU)

hueL = 50
satL = 50
valL = 150
hueU = 180
satU = 255
valU = 255

cv.namedWindow('panel')
cv.createTrackbar('hue lower', 'panel', hueL, 255, change_hueL)
cv.createTrackbar('sat lower', 'panel', satL, 255, change_satL)
cv.createTrackbar('val lower', 'panel', valL, 255, change_valL)
cv.createTrackbar('hue upper', 'panel', hueU, 255, change_hueU)
cv.createTrackbar('sat upper', 'panel', satU, 255, change_satU)
cv.createTrackbar('val upper', 'panel', valU, 255, change_valU)

lower = np.array([hueL, satL, valL])
upper = np.array([hueU, satU, valU])

cap = cv.VideoCapture(0)

while (True):

    # Capture frame
    ret, frame = cap.read()

    if ret:

        color = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        mask = cv.inRange(color, lower, upper)

        cv.imshow("raw", frame)
        cv.imshow("msk", mask)

        k = cv.waitKey(5) & 0xFF
        if k == 27:
            break
cv.destroyAllWindows()
cap.release()
</code>```

Body:
I tried several different methods none work, I was trying to get the values to change on the fly so I can change the HSV values live to adjust for noise and inaccuracies. The values change fine but it doesn't update the color mask thresholds, I really dont know what else to try, any help would be greatly appreciated!

import numpy as np
import cv2 as cv

def change_hueL(value1L):
    global hueL
    hueL = value1L
    print("huel: ", hueL)

def change_satL(value2L):
    global satL
    satL = value2L
    print("satL:", satL)

def change_valL(value3L):
    global valL
    valL = value3L
    print("valL: ", valL)

def change_hueU(value1U):
    global hueU
    hueU = value1U
    print("hueU: ", hueU)

def change_satU(value2U):
    global satU
    satU = value2U
    print("satU: ", satU)

def change_valU(value3U):
    global valU
    valU = value3U
    print("valU: ", valU)

hueL = 50
satL = 50
valL = 150
hueU = 180
satU = 255
valU = 255

cv.namedWindow('panel')
cv.createTrackbar('hue lower', 'panel', hueL, 255, change_hueL)
cv.createTrackbar('sat lower', 'panel', satL, 255, change_satL)
cv.createTrackbar('val lower', 'panel', valL, 255, change_valL)
cv.createTrackbar('hue upper', 'panel', hueU, 255, change_hueU)
cv.createTrackbar('sat upper', 'panel', satU, 255, change_satU)
cv.createTrackbar('val upper', 'panel', valU, 255, change_valU)

lower = np.array([hueL, satL, valL])
upper = np.array([hueU, satU, valU])

cap = cv.VideoCapture(0)

while (True):

    # Capture frame
    ret, frame = cap.read()

    if ret:

        color = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
        mask = cv.inRange(color, lower, upper)

        cv.imshow("raw", frame)
        cv.imshow("msk", mask)

        k = cv.waitKey(5) & 0xFF
        if k == 27:
            break
cv.destroyAllWindows()
cap.release()


问:
Query on deploying Django and angular on the same server
I have deployed the angular dist on port 80 using Nginx.
On the same server my api is running on port 81.
If I am allowing the outside traffic on port 81,
then the application is working as expected.
As port 81 is a non standard port I need to give clarification to port that port.

Is there any way (some configurational changes in Nginx), that without opening the port 81,
The application can work fine.

frontend (angular) : running on port 80

backend  (Django)  : running on port 81

*** Note: can not use multiple servers to deploy frontend and backend separately

Please let me know if any clarification is required on the requirement.
Please suggest.