问:
Can't collect data when run python coverage in exec statement
I execute python script with exec and I want to evaluate the coverage in script

```<code>if __name__ == '__main__':
    script = '''
import coverage
def test(a):
    if a > 1:
        return 1
    return 0
cov = coverage.coverage()
cov.start()
test(ctx)
cov.stop()
cov.save()
'''
    glob = {"ctx": 0}
    exec(script, glob)

</code>```

but got the following result:

```<code>/Users/jim/python/coverage_test/venv/lib/python3.8/site-packages/coverage/control.py:801: CoverageWarning: No data was collected. (no-data-collected)
  self._warn("No data was collected.", slug="no-data-collected")
</code>```

I try to run coverage in shell, it works，but how can use coverage in exec func?

```<code>if __name__ == '__main__':
    import os
    script = '''
def test(ctx):
    a = ctx.a
    if ctx.b > 2:
        return a
    return a + 1
test(5)
'''
    fp = tempfile.NamedTemporaryFile()
    fp.write(script.encode())
    fp.seek(0)
    os.system("coverage run " + fp.name)
    fp.close()
</code>```

Body:
I execute python script with exec and I want to evaluate the coverage in script

if __name__ == '__main__':
    script = '''
import coverage
def test(a):
    if a > 1:
        return 1
    return 0
cov = coverage.coverage()
cov.start()
test(ctx)
cov.stop()
cov.save()
'''
    glob = {"ctx": 0}
    exec(script, glob)

but got the following result:

/Users/jim/python/coverage_test/venv/lib/python3.8/site-packages/coverage/control.py:801: CoverageWarning: No data was collected. (no-data-collected)
  self._warn("No data was collected.", slug="no-data-collected")

I try to run coverage in shell, it works，but how can use coverage in exec func?

if __name__ == '__main__':
    import os
    script = '''
def test(ctx):
    a = ctx.a
    if ctx.b > 2:
        return a
    return a + 1
test(5)
'''
    fp = tempfile.NamedTemporaryFile()
    fp.write(script.encode())
    fp.seek(0)
    os.system("coverage run " + fp.name)
    fp.close()


来源: stackexchange

问:
GrapesJS countdown and navbar plugin doesn't render correctly
I have react-grapesjs project and grapesjs-react version is 4.0.1. This is correctly store when I click SAVE button and generated page is looks good when I open it in browswer. But the problem is, the builder styles are broken when I come back to builder. Default components works fine well, but external plugins(so I have installed this "grapesjs-component-countdown": "^1.0.1", "grapesjs-navbar": "^1.0.1") doesn't show correctly which I saved. Here are my codes for this.

```<code>componentDidMount() {
        this.props.init();
        let editor = grapesjs.init({
            fromElement: true,
            container: '#gjs',
            storageManager: {
                type: 'local',
                autoload: true,
                autosave: true,
                stepsBeforeSave: 1,
                storeComponents: true,
                storeStyles: true,
                storeHtml: true,
                storeCss: true,
                autorender: false
            },
            plugins: [
                basic, plugin, forms, navbar, countdown, pgexport
            ],
            pluginsOpts: {
                [pgexport]: {
                    addExportBtn: true,
                    btnLabel: 'export',
                    css: {
                        'style.css': ed => ed.getCss(),
                        'some-file.txt': 'My custom content',
                    },
                    img: async ed => {
                        const images = await ed.getComponents();
                        return images;
                    },
                    'index.html': ed => `<body>${ed.getHtml()}</body>`
                },
            }
        });

        editor.load();

        this.setState({
            ...this.state,
            editor: editor
        });
    }
</code>```

And saved localStorage like this.

```<code>'{"assets":[],"styles":[{"selectors":["#ieaj"],"style":{"background-color":"#ffffff"},"wrapper":1},{"selectors":[{"name":"gjs-row","private":1}],"style":{"display":"table","padding-top":"10px","padding-right":"10px","padding-bottom":"10px","padding-left":"10px","width":"100%"}},{"selectors":[{"name":"gjs-cell","private":1}],"style":{"width":"100%","display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media"},{"selectors":["gjs-cell30"],"style":{"width":"100%","display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media"},{"selectors":["gjs-cell70"],"style":{"width":"100%","display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media"},{"selectors":[{"name":"gjs-cell","private":1}],"style":{"width":"8%","display":"table-cell","height":"75px"}},{"selectors":["countdown"],"style":{"text-align":"center"},"group":"cmp:countdown"},{"selectors":["countdown-block"],"style":{"display":"inline-block","margin-top":"0px","margin-right":"10px","margin-bottom":"0px","margin-left":"10px","padding-top":"10px","padding-right":"10px","padding-bottom":"10px","padding-left":"10px"},"group":"cmp:countdown"},{"selectors":["countdown-digit"],"style":{"font-size":"5rem","font-family":"Georgia, serif"},"group":"cmp:countdown"},{"selectors":["countdown-endtext"],"style":{"font-size":"5rem"},"group":"cmp:countdown"},{"selectors":["countdown-cont"],"style":{"display":"inline-block"},"group":"cmp:countdown"},{"selectors":["navbar"],"style":{"background-color":"rgb(34, 34, 34)","color":"rgb(221, 221, 221)","min-height":"50px","width":"100%"},"group":"cmp:navbar"},{"selectors":["navbar-container"],"style":{"max-width":"950px","margin-top":"0px","margin-right":"auto","margin-bottom":"0px","margin-left":"auto","width":"95%"},"group":"cmp:navbar"},{"selectors":["navbar-items-c"],"style":{"display":"inline-block","float":"right"},"group":"cmp:navbar"},{"selectors":["navbar-container"],"style":{"content":"\\"\\"","clear":"both","display":"block"},"state":":after","group":"cmp:navbar"},{"selectors":["navbar-brand"],"style":{"vertical-align":"top","display":"inline-block","padding-top":"5px","padding-right":"5px","padding-bottom":"5px","padding-left":"5px","min-height":"50px","min-width":"50px","color":"inherit","text-decoration-line":"none","text-decoration-thickness":"initial","text-decoration-style":"initial","text-decoration-color":"initial"},"group":"cmp:navbar"},{"selectors":["navbar-menu"],"style":{"padding-top":"10px","padding-right":"0px","padding-bottom":"10px","padding-left":"0px","display":"block","float":"right","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"},"group":"cmp:navbar"},{"selectors":["navbar-menu-link"],"style":{"margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","color":"inherit","text-decoration-line":"none","text-decoration-thickness":"initial","text-decoration-style":"initial","text-decoration-color":"initial","display":"inline-block","padding-top":"10px","padding-right":"15px","padding-bottom":"10px","padding-left":"15px"},"group":"cmp:navbar"},{"selectors":["navbar-burger"],"style":{"margin-top":"10px","margin-right":"0px","margin-bottom":"10px","margin-left":"0px","width":"45px","padding-top":"5px","padding-right":"10px","padding-bottom":"5px","padding-left":"10px","display":"none","float":"right","cursor":"pointer"},"group":"cmp:navbar"},{"selectors":["navbar-burger-line"],"style":{"padding-top":"1px","padding-right":"1px","padding-bottom":"1px","padding-left":"1px","background-color":"white","margin-top":"5px","margin-right":"0px","margin-bottom":"5px","margin-left":"0px"},"group":"cmp:navbar"},{"selectors":["navbar-items-c"],"style":{"display":"none","width":"100%"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"},{"selectors":["navbar-burger"],"style":{"display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"},{"selectors":["navbar-menu"],"style":{"width":"100%"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"},{"selectors":["navbar-menu-link"],"style":{"display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"}],"pages":[{"frames":[{"component":{"type":"wrapper","stylable":["background","background-color","background-image","background-repeat","background-attachment","background-position","background-size"],"attributes":{"id":"ieaj"},"_undoexc":["status","open"],"components":[{"type":"navbar","classes":["navbar"],"attributes":{},"components":[{"type":"navbar-container","classes":["navbar-container"],"attributes":{"data-gjs":"navbar"},"components":[{"type":"link","classes":["navbar-brand"],"attributes":{"href":"/"},"_undoexc":["status","open"]},{"type":"navbar-burger-menu","classes":["navbar-burger"],"attributes":{},"components":[{"type":"navbar-burger-menu-line","classes":["navbar-burger-line"],"attributes":{}},{"type":"navbar-burger-menu-line","classes":["navbar-burger-line"],"attributes":{}},{"type":"navbar-burger-menu-line","classes":["navbar-burger-line"],"attributes":{}}]},{"classes":["navbar-items-c"],"attributes":{"data-gjs":"navbar-items"},"_undoexc":["status","open"],"components":[{"type":"navbar-nav-menu","classes":["navbar-menu"],"attributes":{},"components":[{"type":"navbar-nav-menu-link","classes":["navbar-menu-link"],"attributes":{},"components":[{"type":"textnode","content":"Home","_undoexc":["status","open"]}]},{"type":"navbar-nav-menu-link","classes":["navbar-menu-link"],"attributes":{},"components":[{"type":"textnode","content":"About","_undoexc":["status","open"]}]},{"type":"navbar-nav-menu-link","classes":["navbar-menu-link"],"attributes":{},"components":[{"type":"textnode","content":"Contact","_undoexc":["status","open"]}]}]}]}]}]},{"name":"Row","droppable":".gjs-cell","resizable":{"tl":0,"tc":0,"tr":0,"cl":0,"cr":0,"bl":0,"br":0,"minDim":1},"classes":[{"name":"gjs-row","private":1}],"attributes":{"id":"ixd5"},"_undoexc":["status","open"]},{"type":"countdown","classes":["countdown"],"startfrom":"2022-12-21","components":[{"tagName":"span","classes":["countdown-cont"],"attributes":{"data-js":"countdown"},"_undoexc":["status","open"],"components":[{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-day"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"days","_undoexc":["status","open"]}]}]},{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-hour"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"hours","_undoexc":["status","open"]}]}]},{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-minute"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"minutes","_undoexc":["status","open"]}]}]},{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-second"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"seconds","_undoexc":["status","open"]}]}]}]},{"tagName":"span","classes":["countdown-endtext"],"attributes":{"data-js":"countdown-endtext"},"_undoexc":["status","open"]}]}]}}],"type":"main","id":"tgL0P4sa4kpzDZGt"}]}'
</code>```

Anything help me.

ContentLicense: CC BY-SA 4.0

Body:
I have react-grapesjs project and grapesjs-react version is 4.0.1. This is correctly store when I click SAVE button and generated page is looks good when I open it in browswer. But the problem is, the builder styles are broken when I come back to builder. Default components works fine well, but external plugins(so I have installed this "grapesjs-component-countdown": "^1.0.1", "grapesjs-navbar": "^1.0.1") doesn't show correctly which I saved. Here are my codes for this.

componentDidMount() {
        this.props.init();
        let editor = grapesjs.init({
            fromElement: true,
            container: '#gjs',
            storageManager: {
                type: 'local',
                autoload: true,
                autosave: true,
                stepsBeforeSave: 1,
                storeComponents: true,
                storeStyles: true,
                storeHtml: true,
                storeCss: true,
                autorender: false
            },
            plugins: [
                basic, plugin, forms, navbar, countdown, pgexport
            ],
            pluginsOpts: {
                [pgexport]: {
                    addExportBtn: true,
                    btnLabel: 'export',
                    css: {
                        'style.css': ed => ed.getCss(),
                        'some-file.txt': 'My custom content',
                    },
                    img: async ed => {
                        const images = await ed.getComponents();
                        return images;
                    },
                    'index.html': ed => `<body>${ed.getHtml()}</body>`
                },
            }
        });

        editor.load();

        this.setState({
            ...this.state,
            editor: editor
        });
    }

And saved localStorage like this.

'{"assets":[],"styles":[{"selectors":["#ieaj"],"style":{"background-color":"#ffffff"},"wrapper":1},{"selectors":[{"name":"gjs-row","private":1}],"style":{"display":"table","padding-top":"10px","padding-right":"10px","padding-bottom":"10px","padding-left":"10px","width":"100%"}},{"selectors":[{"name":"gjs-cell","private":1}],"style":{"width":"100%","display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media"},{"selectors":["gjs-cell30"],"style":{"width":"100%","display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media"},{"selectors":["gjs-cell70"],"style":{"width":"100%","display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media"},{"selectors":[{"name":"gjs-cell","private":1}],"style":{"width":"8%","display":"table-cell","height":"75px"}},{"selectors":["countdown"],"style":{"text-align":"center"},"group":"cmp:countdown"},{"selectors":["countdown-block"],"style":{"display":"inline-block","margin-top":"0px","margin-right":"10px","margin-bottom":"0px","margin-left":"10px","padding-top":"10px","padding-right":"10px","padding-bottom":"10px","padding-left":"10px"},"group":"cmp:countdown"},{"selectors":["countdown-digit"],"style":{"font-size":"5rem","font-family":"Georgia, serif"},"group":"cmp:countdown"},{"selectors":["countdown-endtext"],"style":{"font-size":"5rem"},"group":"cmp:countdown"},{"selectors":["countdown-cont"],"style":{"display":"inline-block"},"group":"cmp:countdown"},{"selectors":["navbar"],"style":{"background-color":"rgb(34, 34, 34)","color":"rgb(221, 221, 221)","min-height":"50px","width":"100%"},"group":"cmp:navbar"},{"selectors":["navbar-container"],"style":{"max-width":"950px","margin-top":"0px","margin-right":"auto","margin-bottom":"0px","margin-left":"auto","width":"95%"},"group":"cmp:navbar"},{"selectors":["navbar-items-c"],"style":{"display":"inline-block","float":"right"},"group":"cmp:navbar"},{"selectors":["navbar-container"],"style":{"content":"\\"\\"","clear":"both","display":"block"},"state":":after","group":"cmp:navbar"},{"selectors":["navbar-brand"],"style":{"vertical-align":"top","display":"inline-block","padding-top":"5px","padding-right":"5px","padding-bottom":"5px","padding-left":"5px","min-height":"50px","min-width":"50px","color":"inherit","text-decoration-line":"none","text-decoration-thickness":"initial","text-decoration-style":"initial","text-decoration-color":"initial"},"group":"cmp:navbar"},{"selectors":["navbar-menu"],"style":{"padding-top":"10px","padding-right":"0px","padding-bottom":"10px","padding-left":"0px","display":"block","float":"right","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px"},"group":"cmp:navbar"},{"selectors":["navbar-menu-link"],"style":{"margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","color":"inherit","text-decoration-line":"none","text-decoration-thickness":"initial","text-decoration-style":"initial","text-decoration-color":"initial","display":"inline-block","padding-top":"10px","padding-right":"15px","padding-bottom":"10px","padding-left":"15px"},"group":"cmp:navbar"},{"selectors":["navbar-burger"],"style":{"margin-top":"10px","margin-right":"0px","margin-bottom":"10px","margin-left":"0px","width":"45px","padding-top":"5px","padding-right":"10px","padding-bottom":"5px","padding-left":"10px","display":"none","float":"right","cursor":"pointer"},"group":"cmp:navbar"},{"selectors":["navbar-burger-line"],"style":{"padding-top":"1px","padding-right":"1px","padding-bottom":"1px","padding-left":"1px","background-color":"white","margin-top":"5px","margin-right":"0px","margin-bottom":"5px","margin-left":"0px"},"group":"cmp:navbar"},{"selectors":["navbar-items-c"],"style":{"display":"none","width":"100%"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"},{"selectors":["navbar-burger"],"style":{"display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"},{"selectors":["navbar-menu"],"style":{"width":"100%"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"},{"selectors":["navbar-menu-link"],"style":{"display":"block"},"mediaText":"(max-width: 768px)","atRuleType":"media","group":"cmp:navbar"}],"pages":[{"frames":[{"component":{"type":"wrapper","stylable":["background","background-color","background-image","background-repeat","background-attachment","background-position","background-size"],"attributes":{"id":"ieaj"},"_undoexc":["status","open"],"components":[{"type":"navbar","classes":["navbar"],"attributes":{},"components":[{"type":"navbar-container","classes":["navbar-container"],"attributes":{"data-gjs":"navbar"},"components":[{"type":"link","classes":["navbar-brand"],"attributes":{"href":"/"},"_undoexc":["status","open"]},{"type":"navbar-burger-menu","classes":["navbar-burger"],"attributes":{},"components":[{"type":"navbar-burger-menu-line","classes":["navbar-burger-line"],"attributes":{}},{"type":"navbar-burger-menu-line","classes":["navbar-burger-line"],"attributes":{}},{"type":"navbar-burger-menu-line","classes":["navbar-burger-line"],"attributes":{}}]},{"classes":["navbar-items-c"],"attributes":{"data-gjs":"navbar-items"},"_undoexc":["status","open"],"components":[{"type":"navbar-nav-menu","classes":["navbar-menu"],"attributes":{},"components":[{"type":"navbar-nav-menu-link","classes":["navbar-menu-link"],"attributes":{},"components":[{"type":"textnode","content":"Home","_undoexc":["status","open"]}]},{"type":"navbar-nav-menu-link","classes":["navbar-menu-link"],"attributes":{},"components":[{"type":"textnode","content":"About","_undoexc":["status","open"]}]},{"type":"navbar-nav-menu-link","classes":["navbar-menu-link"],"attributes":{},"components":[{"type":"textnode","content":"Contact","_undoexc":["status","open"]}]}]}]}]}]},{"name":"Row","droppable":".gjs-cell","resizable":{"tl":0,"tc":0,"tr":0,"cl":0,"cr":0,"bl":0,"br":0,"minDim":1},"classes":[{"name":"gjs-row","private":1}],"attributes":{"id":"ixd5"},"_undoexc":["status","open"]},{"type":"countdown","classes":["countdown"],"startfrom":"2022-12-21","components":[{"tagName":"span","classes":["countdown-cont"],"attributes":{"data-js":"countdown"},"_undoexc":["status","open"],"components":[{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-day"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"days","_undoexc":["status","open"]}]}]},{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-hour"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"hours","_undoexc":["status","open"]}]}]},{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-minute"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"minutes","_undoexc":["status","open"]}]}]},{"classes":["countdown-block"],"_undoexc":["status","open"],"components":[{"classes":["countdown-digit"],"attributes":{"data-js":"countdown-second"},"_undoexc":["status","open"]},{"type":"text","classes":["countdown-label"],"_undoexc":["status","open"],"components":[{"type":"textnode","content":"seconds","_undoexc":["status","open"]}]}]}]},{"tagName":"span","classes":["countdown-endtext"],"attributes":{"data-js":"countdown-endtext"},"_undoexc":["status","open"]}]}]}}],"type":"main","id":"tgL0P4sa4kpzDZGt"}]}'

Anything help me.


问:
How to use Python to analyze the rules of data?
I have a set of data, I want to use Python to help analyze it by inputting a new set of data (x_new) and deciding the next most likely number. Currently I just replaced the data of iris flower, using SVC, but it seems still not accurate enough, the following is my code, can anyone help me improve it?

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris_data = load_iris()
X_train,X_test,y_train,y_test = train_test_split(
    iris_data['data'],iris_data['target'],random_state=0)

# make predictions
X_new = np.array([[6,0,5,22]])

from sklearn.svm import SVC
svmClf = SVC(random_state=42)
svmClf.fit(X_train, y_train)
all_pre_and_get_score = svmClf.decision_function(X_new)
all_pre_and_get_score

# Softmax
def Softmax(s : list or np.ndarray):
    S = np.array([np.exp(i) for i in s])
    u = np.sum(S)
    for j in S:
        yield j/u

# Convert to see the probability of the next number appearing
for i in Softmax(all_pre_and_get_score):
    print(i)
    aa = np.array(i)
    bb = aa.tolist()
    m2=bb.copy()
    m2.remove(max(bb))
    m3=max(m2)
    m4=m2.copy()
    m4.remove(max(m2))
    m5=max(m4)
    print()
    print(max(i), '{}'.format(bb.index(max(bb))))
    print(m3,'{}'.format(bb.index(max(m2))))
    print(m5,'{}'.format(bb.index(max(m4))))
```

the data is here:
https://drive.google.com/file/d/1JJW35qcaHmOcNCUDxidRYYAOGiJk_M1_/view?usp=share_link

Body:
I have a set of data, I want to use Python to help analyze it by inputting a new set of data (x_new) and deciding the next most likely number. Currently I just replaced the data of iris flower, using SVC, but it seems still not accurate enough, the following is my code, can anyone help me improve it?

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

iris_data = load_iris()
X_train,X_test,y_train,y_test = train_test_split(
    iris_data['data'],iris_data['target'],random_state=0)

# make predictions
X_new = np.array([[6,0,5,22]])

from sklearn.svm import SVC
svmClf = SVC(random_state=42)
svmClf.fit(X_train, y_train)
all_pre_and_get_score = svmClf.decision_function(X_new)
all_pre_and_get_score

# Softmax
def Softmax(s : list or np.ndarray):
    S = np.array([np.exp(i) for i in s])
    u = np.sum(S)
    for j in S:
        yield j/u

# Convert to see the probability of the next number appearing
for i in Softmax(all_pre_and_get_score):
    print(i)
    aa = np.array(i)
    bb = aa.tolist()
    m2=bb.copy()
    m2.remove(max(bb))
    m3=max(m2)
    m4=m2.copy()
    m4.remove(max(m2))
    m5=max(m4)
    print()
    print(max(i), '{}'.format(bb.index(max(bb))))
    print(m3,'{}'.format(bb.index(max(m2))))
    print(m5,'{}'.format(bb.index(max(m4))))

the data is here:
https://drive.google.com/file/d/1JJW35qcaHmOcNCUDxidRYYAOGiJk_M1_/view?usp=share_link


问:
How to exclude specific dependencies version on sbt project
I have list of dependencies

```<code>libraryDependencies ++= Seq(
  ws,
  evolutions,
  lombok,
  guice,
  jackson213,
  logstashLogEncoder,
  awsSecretsmanagerJdbc,
  configProperty,
  wireMock,
  restAssured,
  commonsLang3
}
</code>```

but I want to exclude for specific dependencies version for example for exclude

```<code>snakeyaml-1.26.jar
</code>```

how to do that ?

thanks

Body:
I have list of dependencies

libraryDependencies ++= Seq(
  ws,
  evolutions,
  lombok,
  guice,
  jackson213,
  logstashLogEncoder,
  awsSecretsmanagerJdbc,
  configProperty,
  wireMock,
  restAssured,
  commonsLang3
}

but I want to exclude for specific dependencies version for example for exclude

snakeyaml-1.26.jar

how to do that ?

thanks


问:
There were missing values in resampled performance measures
I need to do a classification task on this dataset. As the following code shows, I tried to implement xgboost using caret package. Since my dataset is imbalanced, I prefer to use Fscore as performance measure. Furthermore, I need to use the first 700000 instances as the train set and the remaining 150000 instances as the test set. As the commented part of my code shows, I read this post and other related posts. However, I could not solve the issue.

```<code>mytrainvalid <- read.csv("mytrainvalid.csv")
library(xgboost)
library(dplyr)
library(caret)

mytrainvalid$DEFAULT <- ifelse(mytrainvalid$DEFAULT != 0,
                               "one",
                               "zero")
mytrainvalid$DEFAULT <- as.factor(mytrainvalid$DEFAULT)

input_x <- as.matrix(select(mytrainvalid, -DEFAULT))
## Use the validation index in the trainControl
ind=as.integer(rownames(mytrainvalid))
vi=c(700001:850000)

# modelling
grid_default <- expand.grid(
  nrounds = c(100,200),
  max_depth = 6,
  eta = 0.1,
  gamma = 0,
  colsample_bytree = 1,
  min_child_weight = 1,
  subsample = 1
)
## use fScore as data is imbalance: 20:1
f1 <- function (data, lev = NULL, model = NULL) {
  precision <- posPredValue(data$pred, data$obs, positive = "pass")
  recall  <- sensitivity(data$pred, data$obs, postive = "pass")
  f1_val <- (2 * precision * recall) / (precision + recall)
  names(f1_val) <- c("F1")
  f1_val
}
##
data.ctrl <- trainControl(method = "cv",
                          number = 1,
                          allowParallel=TRUE,
                          returnData = FALSE,
                          index = list(Fold1=(1:ind)[-vi]),
                          sampling = "smote",
                          classProbs = TRUE,
                          summaryFunction = f1,
                          savePredictions = "final",
                          verboseIter=TRUE,
                          search = "random",
                          #savePred=T
)

xgb_model <-caret::train (input_x,
                          mytrainvalid$DEFAULT,
                          method="xgbTree",
                          trControl=data.ctrl,
                          #tuneGrid=grid_default,
                          verbose=FALSE,
                          metric = "F1",
                          classProbs=TRUE,
                          #linout=FALSE,
                          #threshold = 0.3,
                          #scale_pos_weight = sum(input_y$DEFAULT == "no")/sum(input_y$DEFAULT == "yes"),
                          #maximize = FALSE,
                          tuneLength = 2,
)
</code>```

Unfortunately, the following error is produced:

```<code>Something is wrong; all the F1 metric values are missing:
       F1
 Min.   : NA
 1st Qu.: NA
 Median : NA
 Mean   :NaN
 3rd Qu.: NA
 Max.   : NA
 NA's   :2
Error: Stopping
In addition: Warning messages:
1: model fit failed for Fold1: eta=0.09121, max_depth=8, gamma=7.227, colsample_bytree=0.6533, min_child_weight=15, subsample=0.9783, nrounds=800 Error in createModel(x = subset_x(x, modelIndex), y = y[modelIndex], wts = wts[modelIndex],  :
  formal argument "classProbs" matched by multiple actual arguments

2: model fit failed for Fold1: eta=0.15119, max_depth=8, gamma=8.877, colsample_bytree=0.4655, min_child_weight= 3, subsample=0.9515, nrounds=536 Error in createModel(x = subset_x(x, modelIndex), y = y[modelIndex], wts = wts[modelIndex],  :
  formal argument "classProbs" matched by multiple actual arguments

3: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.
</code>```

Body:
I need to do a classification task on this dataset. As the following code shows, I tried to implement xgboost using caret package. Since my dataset is imbalanced, I prefer to use Fscore as performance measure. Furthermore, I need to use the first 700000 instances as the train set and the remaining 150000 instances as the test set. As the commented part of my code shows, I read this post and other related posts. However, I could not solve the issue.

mytrainvalid <- read.csv("mytrainvalid.csv")
library(xgboost)
library(dplyr)
library(caret)

mytrainvalid$DEFAULT <- ifelse(mytrainvalid$DEFAULT != 0,
                               "one",
                               "zero")
mytrainvalid$DEFAULT <- as.factor(mytrainvalid$DEFAULT)

input_x <- as.matrix(select(mytrainvalid, -DEFAULT))
## Use the validation index in the trainControl
ind=as.integer(rownames(mytrainvalid))
vi=c(700001:850000)

# modelling
grid_default <- expand.grid(
  nrounds = c(100,200),
  max_depth = 6,
  eta = 0.1,
  gamma = 0,
  colsample_bytree = 1,
  min_child_weight = 1,
  subsample = 1
)
## use fScore as data is imbalance: 20:1
f1 <- function (data, lev = NULL, model = NULL) {
  precision <- posPredValue(data$pred, data$obs, positive = "pass")
  recall  <- sensitivity(data$pred, data$obs, postive = "pass")
  f1_val <- (2 * precision * recall) / (precision + recall)
  names(f1_val) <- c("F1")
  f1_val
}
##
data.ctrl <- trainControl(method = "cv",
                          number = 1,
                          allowParallel=TRUE,
                          returnData = FALSE,
                          index = list(Fold1=(1:ind)[-vi]),
                          sampling = "smote",
                          classProbs = TRUE,
                          summaryFunction = f1,
                          savePredictions = "final",
                          verboseIter=TRUE,
                          search = "random",
                          #savePred=T
)

xgb_model <-caret::train (input_x,
                          mytrainvalid$DEFAULT,
                          method="xgbTree",
                          trControl=data.ctrl,
                          #tuneGrid=grid_default,
                          verbose=FALSE,
                          metric = "F1",
                          classProbs=TRUE,
                          #linout=FALSE,
                          #threshold = 0.3,
                          #scale_pos_weight = sum(input_y$DEFAULT == "no")/sum(input_y$DEFAULT == "yes"),
                          #maximize = FALSE,
                          tuneLength = 2,
)

Unfortunately, the following error is produced:

Something is wrong; all the F1 metric values are missing:
       F1
 Min.   : NA
 1st Qu.: NA
 Median : NA
 Mean   :NaN
 3rd Qu.: NA
 Max.   : NA
 NA's   :2
Error: Stopping
In addition: Warning messages:
1: model fit failed for Fold1: eta=0.09121, max_depth=8, gamma=7.227, colsample_bytree=0.6533, min_child_weight=15, subsample=0.9783, nrounds=800 Error in createModel(x = subset_x(x, modelIndex), y = y[modelIndex], wts = wts[modelIndex],  :
  formal argument "classProbs" matched by multiple actual arguments

2: model fit failed for Fold1: eta=0.15119, max_depth=8, gamma=8.877, colsample_bytree=0.4655, min_child_weight= 3, subsample=0.9515, nrounds=536 Error in createModel(x = subset_x(x, modelIndex), y = y[modelIndex], wts = wts[modelIndex],  :
  formal argument "classProbs" matched by multiple actual arguments

3: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.


问:
Trying to run terrier.bat file through window cmd
I am trying to follow the terrier quick start guide but am facing an issue, I try to run the bin\terrier.bat on windows cmd but I get the following

"Error: Could not find or load main class
Caused by: java.lang.ClassNotFoundException:"

I am in the terrier directory which is in my downloads folder, I have java version 11, my system path environment variables are all set. According to the guide it should show me the terrier version and all the commands available. Here is a link to the quick start guide https://github.com/terrier-org/terrier-core/blob/5.x/doc/quickstart_experiments.md


问:
Python sequential instance names from variables
been searching in vain for many hours.  This should be simple.  I'm doing a select from a SQL database and want to create a class instance for each row that is returned. I also need to iterate through each object later, so I'm guessing I'll need to stow the variables in a list or dict.

Here's a mock up of what I'm trying to accomplish. Didn't want to make everyone suffer through the original code so I'm pared it down to just what I want to accomplish.

```<code>class Dynamic_Class:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

name_list = []
for i in range(1,6):
    obj_name = ("person" + str(i))
    name_list.append(obj_name)
    obj_name = Dynamic_Class("Joel", "Robinson")

    print(person1.fname)
</code>```

I think I've seen some brute force methods out there that I could get to work, but I think I should use something more pythonic.  Thanks.

EDIT:  I've been pointed to a solution "How do I create variable variables?" (How do I create variable variables?) but that still doesn't accomplish what I want.  Here are the class instantiations when creating a dictionary and instatianting with variables from that dict:

```<code>class Dynamic_Class:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

heddy = Dynamic_Class("Tom", "Servo")
print(heddy.fname)

name_dict = {}
for i in range(1,6):
    obj_name = ("person" + str(i))
    obj_name2 = ("person" + str(i))
    print(("obj name is ",obj_name))
    name_dict[obj_name] = obj_name2
    name_dict[obj_name] = Dynamic_Class("Joel", "Robinson")
    print(name_dict["person1"].fname)

    print(person1.fname)
</code>```

The output:

```<code>C:\Users\bucky\OneDrive\Python_Installs\PycharmProjects\ReadSQLWireNFIRS\Scripts\python.exe C:\Users\bucky\OneDrive\Python_Installs\PycharmProjects\ReadSQLWireNFIRS\scratch.py
Tom
('obj name is ', 'person1')
Joel
Traceback (most recent call last):
  File "C:\Users\bucky\OneDrive\Python_Installs\PycharmProjects\ReadSQLWireNFIRS\scratch.py", line 20, in <module>
    print(person1.fname)
          ^^^^^^^
NameError: name 'person1' is not defined

Process finished with exit code 1
</code>```

All of the solutions in that linked question start with constants:  i.e. making a dictionary from a list of contants...which sort of defeats the purpose.  In english, to boil it down:

I want to read 200,000 rows from a sql database and create 200,000 class objects referenceable by "Person1" through Person200000. I would think this is basic, but I just don't know how to ask this question on teh google.

Body:
been searching in vain for many hours.  This should be simple.  I'm doing a select from a SQL database and want to create a class instance for each row that is returned. I also need to iterate through each object later, so I'm guessing I'll need to stow the variables in a list or dict.

Here's a mock up of what I'm trying to accomplish. Didn't want to make everyone suffer through the original code so I'm pared it down to just what I want to accomplish.

class Dynamic_Class:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

name_list = []
for i in range(1,6):
    obj_name = ("person" + str(i))
    name_list.append(obj_name)
    obj_name = Dynamic_Class("Joel", "Robinson")

    print(person1.fname)

I think I've seen some brute force methods out there that I could get to work, but I think I should use something more pythonic.  Thanks.

EDIT:  I've been pointed to a solution "How do I create variable variables?" (How do I create variable variables?) but that still doesn't accomplish what I want.  Here are the class instantiations when creating a dictionary and instatianting with variables from that dict:

class Dynamic_Class:
    def __init__(self, fname, lname):
        self.fname = fname
        self.lname = lname

heddy = Dynamic_Class("Tom", "Servo")
print(heddy.fname)

name_dict = {}
for i in range(1,6):
    obj_name = ("person" + str(i))
    obj_name2 = ("person" + str(i))
    print(("obj name is ",obj_name))
    name_dict[obj_name] = obj_name2
    name_dict[obj_name] = Dynamic_Class("Joel", "Robinson")
    print(name_dict["person1"].fname)

    print(person1.fname)

The output:

C:\Users\bucky\OneDrive\Python_Installs\PycharmProjects\ReadSQLWireNFIRS\Scripts\python.exe C:\Users\bucky\OneDrive\Python_Installs\PycharmProjects\ReadSQLWireNFIRS\scratch.py
Tom
('obj name is ', 'person1')
Joel
Traceback (most recent call last):
  File "C:\Users\bucky\OneDrive\Python_Installs\PycharmProjects\ReadSQLWireNFIRS\scratch.py", line 20, in <module>
    print(person1.fname)
          ^^^^^^^
NameError: name 'person1' is not defined

Process finished with exit code 1

All of the solutions in that linked question start with constants:  i.e. making a dictionary from a list of contants...which sort of defeats the purpose.  In english, to boil it down:

I want to read 200,000 rows from a sql database and create 200,000 class objects referenceable by "Person1" through Person200000. I would think this is basic, but I just don't know how to ask this question on teh google.


问:
Running Mahout in Hadoop Cluster - java.lang.ClassNotFoundException
I am trying to run the mahout code in the Hadoop cluster, it is throwing the below error.

Error: java.lang.ClassNotFoundException:
org.apache.mahout.cf.taste.model.DataModel    at
java.net.URLClassLoader.findClass(URLClassLoader.java:387)    at
java.lang.ClassLoader.loadClass(ClassLoader.java:418)     at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)     at
java.lang.ClassLoader.loadClass(ClassLoader.java:351)     at
java.lang.Class.forName0(Native Method)   at
java.lang.Class.forName(Class.java:348)   at
org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2625)
at
org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2590)
at
org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2686)
at
org.apache.hadoop.mapreduce.task.JobContextImpl.getReducerClass(JobContextImpl.java:211)
at
org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:614)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:390)     at
org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:178)  at
java.security.AccessController.doPrivileged(Native Method)    at
javax.security.auth.Subject.doAs(Subject.java:422)    at
org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:172)

Although it's working fine in local. Here's my pom.xml

```<code>    <dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.mahout</groupId>
        <artifactId>mahout-core</artifactId>
        <version>0.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-math3</artifactId>
        <version>3.6.1</version>
    </dependency>

</dependencies>
</code>```

Body:
I am trying to run the mahout code in the Hadoop cluster, it is throwing the below error.

Error: java.lang.ClassNotFoundException:
org.apache.mahout.cf.taste.model.DataModel    at
java.net.URLClassLoader.findClass(URLClassLoader.java:387)    at
java.lang.ClassLoader.loadClass(ClassLoader.java:418)     at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)     at
java.lang.ClassLoader.loadClass(ClassLoader.java:351)     at
java.lang.Class.forName0(Native Method)   at
java.lang.Class.forName(Class.java:348)   at
org.apache.hadoop.conf.Configuration.getClassByNameOrNull(Configuration.java:2625)
at
org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:2590)
at
org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2686)
at
org.apache.hadoop.mapreduce.task.JobContextImpl.getReducerClass(JobContextImpl.java:211)
at
org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:614)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:390)     at
org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:178)  at
java.security.AccessController.doPrivileged(Native Method)    at
javax.security.auth.Subject.doAs(Subject.java:422)    at
org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1878)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:172)

Although it's working fine in local. Here's my pom.xml

    <dependencies>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-client</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>1.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.mahout</groupId>
        <artifactId>mahout-core</artifactId>
        <version>0.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-math3</artifactId>
        <version>3.6.1</version>
    </dependency>

</dependencies>


问:
Exception! need both FlutterFragmentActivity vs FlutterActivity
I have a situation where I need to use local_auth which expects FlutterFragmentActivity as main activity, but on the other hand I also wanna use video_player package which expects FlutterActivity as main activity.

Main Activity for local_auth:

```<code>package //your package name for eg.com.example.filename

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}
</code>```

Main Activity for video_player:

```<code>package //your package name for eg.com.example.filename
import android.content.Context
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.videoplayer.*

class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine:
 FlutterEngine) {

   super.configureFlutterEngine(flutterEngine)

   flutterEngine.getPlugins().add(VideoPlayerPlugin())

    }
}
</code>```

Is there a way to combine both activities so that both packages get their own required FlutterActivity and FlutterFragmentActivity for functioning?

If I use main activity as FlutterFragmentActivity app crashes while compiling and video_player package works smoothly, and if I use FlutterActivity app compiles successfully, but local_auth didn't worked because it requires FlutterFragmentActivity for auth apis to function.

Body:
I have a situation where I need to use local_auth which expects FlutterFragmentActivity as main activity, but on the other hand I also wanna use video_player package which expects FlutterActivity as main activity.

Main Activity for local_auth:

package //your package name for eg.com.example.filename

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterFragmentActivity() {
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }
}

Main Activity for video_player:

package //your package name for eg.com.example.filename
import android.content.Context
import android.os.Bundle
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.videoplayer.*

class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(@NonNull flutterEngine:
 FlutterEngine) {

   super.configureFlutterEngine(flutterEngine)

   flutterEngine.getPlugins().add(VideoPlayerPlugin())

    }
}

Is there a way to combine both activities so that both packages get their own required FlutterActivity and FlutterFragmentActivity for functioning?

If I use main activity as FlutterFragmentActivity app crashes while compiling and video_player package works smoothly, and if I use FlutterActivity app compiles successfully, but local_auth didn't worked because it requires FlutterFragmentActivity for auth apis to function.


问:
How do I create a moving average in sql that restarts from variables
I'm trying to create rolling averages for a data set like

```<code>data have;
  do cat1 = 1 to 10;
    do cat2 = 'A', 'B', 'C';
      do seq = 1 to 20;
        value = cat1 * 10 + seq;
        output;
      end;
    end;
  end;
run;
</code>```

I have tried to used proc expand and it works when I manually filter a set of variables I want it to be done on. My problem is one, I cant get the variables to be organized with dates like the last table. Two, I cant get the rolling average to restart every time the variable "group" changes.

Body:
I'm trying to create rolling averages for a data set like

data have;
  do cat1 = 1 to 10;
    do cat2 = 'A', 'B', 'C';
      do seq = 1 to 20;
        value = cat1 * 10 + seq;
        output;
      end;
    end;
  end;
run;

I have tried to used proc expand and it works when I manually filter a set of variables I want it to be done on. My problem is one, I cant get the variables to be organized with dates like the last table. Two, I cant get the rolling average to restart every time the variable "group" changes.


问:
Links in golang comments to reference markdown
I'm using vs code and want to add a link into golang comment like this:

```<code>// See reference: [.doc/guide/readme.md#L50]
func whatever() {

}
</code>```

So, the idea it's adding a link in comment, and when I will click on link, take me to readme file to line 50.

There is any way to do this? any external library or something?

Thank you in advance!

I tried vscode extensions like LinkComments but I didn't achieve it

Body:
I'm using vs code and want to add a link into golang comment like this:

// See reference: [.doc/guide/readme.md#L50]
func whatever() {

}

So, the idea it's adding a link in comment, and when I will click on link, take me to readme file to line 50.

There is any way to do this? any external library or something?

Thank you in advance!

I tried vscode extensions like LinkComments but I didn't achieve it


问:
How to find the cause of HTTP 500 Error for GKE deployment?
I have deployed a Spring Boot application onto a Google Kubernetes Engine workload. First, I pushed an image to Artifact Registry. Then, I ran the image using the docker run command in the gcloud command line. My GET request worked perfectly fine then, but once I deployed the image to a Kubernetes workload, the same GET request to the LoadBalancer returned a 500 Internal Server HTTP error.

Everytime I try going on Google's Error Reporting, it tells me to setup Error Reporting, but I don't really understand how to, and besides I thought HTTP errors automatically went to Error Reporting.

I'm sorry if there's too many extra details, I mainly want to know how to see the cause of an HTTP 500 error on a GKE deployment?


问:
cross-platform private keys storage for nodejs

Question

I tried to search for a solution, with google and here at StackOverflow, but no success.
What I looking for:

I need API to generate a new keypair, like

//publicKey is either Buffer or string, so I can use it in `createPublicKey` call.
let publicKey = await impl.generate("keypairUniqueName");
```
<ol start="2">
<li>Decrypt some data with key by key name</li>
</ol>
<pre class="lang-js prettyprint-override"><code>let decryptedBuffer = await impl.decrypt("keypairUniqueName", encryptedBuffer);
</code>```

sign data with private key

let signatureBuffer = await impl.sign("keypairUniqueName", rawDataBuffer);
```
<ol start="4">
<li>delete key by unique name</li>
</ol>
<pre class="lang-js prettyprint-override"><code>await impl.deleteKeypair("keypairUniqueName");
</code>```

keys storage should be scoped to specific device, local user account, and (my) app, and ideally, with some other string parameter like in-app account or profile id, so I can call on Electron installation:

let implHive = await ImplFactory.ensureForKeysHive();
```
<p>and later on adding local user record:</p>
<pre class="lang-js prettyprint-override"><code>let impl = await implHive.createKeystore(userAccountId, localPinCode);
</code>```

and on login:

let impl = await implHive.openKeystore(userAccountId, localPinCode);
```
<ol start="6">
<li>ideal requirement: I should be able to do it at Windows desktop, Linux desktop, Android, iOS. Most likely context is Electron App or nodejs based CLI.</li>
</ol>
<p>I understand I can save an encrypted files to paths like <code>~/.appName/keystore/userId.slot</code>, but I need to be sure this file can not be used on other device if copied to other device with ctrl+c - ctrl+v or <code>cp</code> command. So for file-based impl anyway question comes where to save password or other device-scoped encryption data or device-specific keypair to make sure only my app can use that device-scoped keypair.</p>
<p>Does the <code>safeStorage</code> of <code>electron</code> is what I looking for regarding per-device and <code>per platform user</code> as way to store something that only and instance of my app on same machine can save and load?</p>
<p>From documentation I understood <code>electron</code> 's <code>safeStorage</code> is specific to user, not to <code>device-user-app</code> intersection.</p>
<p>In this regard I can implement something like <code>larger password</code> model, where account-specific key of my app stored as original password with some app-specific salt added, like</p>
<pre class="lang-js prettyprint-override"><code>//example purposes-only
let fullAppSpecificKeysVaultPassword = "vendor-alias/my-app/account_${localPinCode}_${purposeCode}";
</code>```

inside storage represented by safeStorage provided electron, but I not sure is this strategy good enough, or may be there some npm package or electron API I overlooked?
It is important that local keys vault for the app under question should be usable across installations/deinstallations/re-installations/upgrades of same app.

Is something like that exists with exact features?

All this resembles very much the Android Keystore - https://developer.android.com/training/articles/keystore#WhichShouldIUse
Especially per-app scoping.
But it is unclear is there something like that to be used in cross-platform manner by an electron and/or nodejs app.

Context, goals, Purpose, and Why

For self-education purposes I thinking about making some small app with 2 features:

public keys mapping to user aliases, random device ids and optional readable device aliases, with small profiles like name, avatar, and 1 sentence user-self description, may be more fields in profiles eventually - limited variation of keybase, with federation like Mastodon, but with rule to keep keys catalogue in sync across federation relays when joining to "relays federation" to make sure profiles intact if relay server who created them gone offline or left keys federation, or relays not available, and only profiles cached by clients are available. I find it interesting to make in context of keybase being eaten by Zoom.

end-to-end encrypted chat app that would work in environments like LAN, WiFi, and Bluetooth, and other local networking to be used both with internet and when standard internet access not available. You may say that such projects are exists already like Serval or Thali or some other, and yeah, I was inspired by them to some extent.

So, self-education aspect, and question like How much of that can I do myself using only Electron or nodejs? are main motivations behind this idea.

Body:
Question

I tried to search for a solution, with google and here at StackOverflow, but no success.
What I looking for:

I need API to generate a new keypair, like

//publicKey is either Buffer or string, so I can use it in `createPublicKey` call.
let publicKey = await impl.generate("keypairUniqueName");

Decrypt some data with key by key name

let decryptedBuffer = await impl.decrypt("keypairUniqueName", encryptedBuffer);

sign data with private key

let signatureBuffer = await impl.sign("keypairUniqueName", rawDataBuffer);

delete key by unique name

await impl.deleteKeypair("keypairUniqueName");

keys storage should be scoped to specific device, local user account, and (my) app, and ideally, with some other string parameter like in-app account or profile id, so I can call on Electron installation:

let implHive = await ImplFactory.ensureForKeysHive();

and later on adding local user record:

let impl = await implHive.createKeystore(userAccountId, localPinCode);

and on login:

let impl = await implHive.openKeystore(userAccountId, localPinCode);

ideal requirement: I should be able to do it at Windows desktop, Linux desktop, Android, iOS. Most likely context is Electron App or nodejs based CLI.

I understand I can save an encrypted files to paths like ~/.appName/keystore/userId.slot, but I need to be sure this file can not be used on other device if copied to other device with ctrl+c - ctrl+v or cp command. So for file-based impl anyway question comes where to save password or other device-scoped encryption data or device-specific keypair to make sure only my app can use that device-scoped keypair.

Does the safeStorage of electron is what I looking for regarding per-device and per platform user as way to store something that only and instance of my app on same machine can save and load?

From documentation I understood electron 's safeStorage is specific to user, not to device-user-app intersection.

In this regard I can implement something like larger password model, where account-specific key of my app stored as original password with some app-specific salt added, like

//example purposes-only
let fullAppSpecificKeysVaultPassword = "vendor-alias/my-app/account_${localPinCode}_${purposeCode}";

inside storage represented by safeStorage provided electron, but I not sure is this strategy good enough, or may be there some npm package or electron API I overlooked?
It is important that local keys vault for the app under question should be usable across installations/deinstallations/re-installations/upgrades of same app.

Is something like that exists with exact features?

All this resembles very much the Android Keystore - https://developer.android.com/training/articles/keystore#WhichShouldIUse
Especially per-app scoping.
But it is unclear is there something like that to be used in cross-platform manner by an electron and/or nodejs app.

Context, goals, Purpose, and Why

For self-education purposes I thinking about making some small app with 2 features:

public keys mapping to user aliases, random device ids and optional readable device aliases, with small profiles like name, avatar, and 1 sentence user-self description, may be more fields in profiles eventually - limited variation of keybase, with federation like Mastodon, but with rule to keep keys catalogue in sync across federation relays when joining to "relays federation" to make sure profiles intact if relay server who created them gone offline or left keys federation, or relays not available, and only profiles cached by clients are available. I find it interesting to make in context of keybase being eaten by Zoom.

end-to-end encrypted chat app that would work in environments like LAN, WiFi, and Bluetooth, and other local networking to be used both with internet and when standard internet access not available. You may say that such projects are exists already like Serval or Thali or some other, and yeah, I was inspired by them to some extent.

So, self-education aspect, and question like How much of that can I do myself using only Electron or nodejs? are main motivations behind this idea.


问:
Flutter Record (3.0.0) plugin no sound recorded in iOS sometimes
I have tried to record an audio using the Flutter Record plugin(3.0.0) and there was an issue where the recorded files (.aac) of some users didn't have any sound. The bitrate of those files were very low (4478). I haven't set any bitrate from the code, so it should be the default (128000) by the plugin.

And also, the reported issue were from iphone users who were using above iOS 15.6.1.

Any thoughts on what could go wrong here?

```<code>if (await _audioRecorder.hasPermission()) {
    await _audioRecorder.start(
        encoder: AudioEncoder.AAC, path: audioPath);

    bool isRecording = await _audioRecorder.isRecording();
    setState(() {
      if (isRecording) {
        _isRecording = true;
      }
      _recordDuration = 0;
    });

    _startTimer();
  }
}
</code>```

Body:
I have tried to record an audio using the Flutter Record plugin(3.0.0) and there was an issue where the recorded files (.aac) of some users didn't have any sound. The bitrate of those files were very low (4478). I haven't set any bitrate from the code, so it should be the default (128000) by the plugin.

And also, the reported issue were from iphone users who were using above iOS 15.6.1.

Any thoughts on what could go wrong here?

if (await _audioRecorder.hasPermission()) {
    await _audioRecorder.start(
        encoder: AudioEncoder.AAC, path: audioPath);

    bool isRecording = await _audioRecorder.isRecording();
    setState(() {
      if (isRecording) {
        _isRecording = true;
      }
      _recordDuration = 0;
    });

    _startTimer();
  }
}


问:
localhost/:1 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'srcObject') at SocketContext.js:27:1
Unable to get the video in my webapp

Showing error in line

```<code>myVideo.current.srcObject = currentStream;
</code>```

My SocketContext cod

```<code>import React,{createContext,useState,useRef,useEffect} from "react";
import {io} from 'socket.io-client'
import Peer from 'simple-peer'

const SocketContext = createContext()

const socket = io('http://localhost:5000')

const ContextProvider = ({children}) => {

    const [stream, setStream] = useState()
    const [me,setMe] = useState('')
    const [call, setCall] = useState({})
    const [callAccepted, setCallAccepted] = useState(false)
    const [callEnded, setCallEnded] = useState(false)
    const [name, setName] = useState('')

    const myVideo = useRef()
    const userVideo = useRef()
    const connectionRef = useRef()

    useEffect(() => {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
          .then((currentStream) => {
            setStream(currentStream);

            myVideo.current.srcObject = currentStream;
        });

        socket.on('me', (id) => setMe(id));

        socket.on('callUser', ({ from, name: callerName, signal }) => {
          setCall({ isReceivingCall: true, from, name: callerName, signal });
        });
      }, []);

    const answerCall = () => {
        setCallAccepted(true)

        const peer = new Peer({initiator:false,trickle:false,stream})

        peer.on('signal', (data) => {
            socket.emit('answerCall',{signal: data,to:call.from})
        })

        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream
        })

        peer.signal(call.signal)

        connectionRef.current = peer
    }

    const callUser = (id) => {
        const peer = new Peer({initiator:true,trickle:false,stream})

        peer.on('signal', (data) => {
            socket.emit('calluser',{userToCall:id,signalData:data,from:me,name})
        })

        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream
        })

        socket.on('callAccepted',(signal) => {
            setCallAccepted(true)

            peer.signal(signal)
        })

        connectionRef.current = peer
    }

    const leaveCall = () => {
        setCallEnded(true)

        connectionRef.current.destroy()

        window.location.reload()
    }

    return (
        <SocketContext.Provider value={{call,callAccepted,myVideo,userVideo,stream,name,me,callEnded,setName,answerCall,callUser,leaveCall}}>
            {children}
        </SocketContext.Provider>
    )
}

export {ContextProvider,SocketContext}
</code>```

enter image description here

enter image description here

Body:
Unable to get the video in my webapp

Showing error in line

myVideo.current.srcObject = currentStream;

My SocketContext cod

import React,{createContext,useState,useRef,useEffect} from "react";
import {io} from 'socket.io-client'
import Peer from 'simple-peer'

const SocketContext = createContext()

const socket = io('http://localhost:5000')

const ContextProvider = ({children}) => {

    const [stream, setStream] = useState()
    const [me,setMe] = useState('')
    const [call, setCall] = useState({})
    const [callAccepted, setCallAccepted] = useState(false)
    const [callEnded, setCallEnded] = useState(false)
    const [name, setName] = useState('')

    const myVideo = useRef()
    const userVideo = useRef()
    const connectionRef = useRef()

    useEffect(() => {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
          .then((currentStream) => {
            setStream(currentStream);

            myVideo.current.srcObject = currentStream;
        });

        socket.on('me', (id) => setMe(id));

        socket.on('callUser', ({ from, name: callerName, signal }) => {
          setCall({ isReceivingCall: true, from, name: callerName, signal });
        });
      }, []);

    const answerCall = () => {
        setCallAccepted(true)

        const peer = new Peer({initiator:false,trickle:false,stream})

        peer.on('signal', (data) => {
            socket.emit('answerCall',{signal: data,to:call.from})
        })

        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream
        })

        peer.signal(call.signal)

        connectionRef.current = peer
    }

    const callUser = (id) => {
        const peer = new Peer({initiator:true,trickle:false,stream})

        peer.on('signal', (data) => {
            socket.emit('calluser',{userToCall:id,signalData:data,from:me,name})
        })

        peer.on('stream', (currentStream) => {
            userVideo.current.srcObject = currentStream
        })

        socket.on('callAccepted',(signal) => {
            setCallAccepted(true)

            peer.signal(signal)
        })

        connectionRef.current = peer
    }

    const leaveCall = () => {
        setCallEnded(true)

        connectionRef.current.destroy()

        window.location.reload()
    }

    return (
        <SocketContext.Provider value={{call,callAccepted,myVideo,userVideo,stream,name,me,callEnded,setName,answerCall,callUser,leaveCall}}>
            {children}
        </SocketContext.Provider>
    )
}

export {ContextProvider,SocketContext}

enter image description here

enter image description here


问:
HTML file with CSS/JavaScript controlling a drop-down menu, but when I reference the CSS and JavaScript from .css and .js. files, menu stays expanded
I have an HTML file with CSS/JavaScript controlling a collapsible drop-down menu, but when I reference the CSS and JavaScript from .css and .js files, the drop-down menu will not collapse and stays expanded.

``
References within the HTML:

```<code>barmenu.js

    $( document ).ready(function()
      {
        // Hide SubMenus.
        $(".subMenu").hide();

        // Shows SubMenu when it's parent is hovered.

        $(".subMenu").parent("li").hover(function ()
        {
          $(this).find(">.subMenu").not(':animated').slideDown(250);
          $(this).toggleClass("active ");
        });

        // Hides SubMenu when mouse leaves the zone.

        $(".subMenu").parent("li").mouseleave(function ()
        {
          $(this).find(">.subMenu").slideUp(250);
        });

        // Prevents scroll to top when clicking on <a href="#">

        $("a[href=\"#\"]").click(function ()
        {
          return false;
        });
    });

</code>```

Body:
I have an HTML file with CSS/JavaScript controlling a collapsible drop-down menu, but when I reference the CSS and JavaScript from .css and .js files, the drop-down menu will not collapse and stays expanded.

``
References within the HTML:

barmenu.js

    $( document ).ready(function()
      {
        // Hide SubMenus.
        $(".subMenu").hide();

        // Shows SubMenu when it's parent is hovered.

        $(".subMenu").parent("li").hover(function ()
        {
          $(this).find(">.subMenu").not(':animated').slideDown(250);
          $(this).toggleClass("active ");
        });

        // Hides SubMenu when mouse leaves the zone.

        $(".subMenu").parent("li").mouseleave(function ()
        {
          $(this).find(">.subMenu").slideUp(250);
        });

        // Prevents scroll to top when clicking on

        $("a[href=\"#\"]").click(function ()
        {
          return false;
        });
    });


问:
How to add custom labels to X axis
I'm trying to display a bar chart using System.Windows.Forms.DataVisualization.Charting in WPF
But i'm unable to change the label of each series on this graph.

Code behind ->

I have used one file to read the data and display those values onto the graph

```<code>public MainWindow()
  {
      InitializeComponent();

      string[] split = new string[6];
      var table = new List<string[]>();
      List<string[]> headers = new List<string[]>();

      using (var r = new StreamReader(@"C:\Users\ee212551\Desktop\Sheet.csv"))
      {
          while (!r.EndOfStream)
          {
              string line = r.ReadLine();
              split = line.Split(',');
              if (split[0].All(char.IsLetter))
              {
                  headers.Add(split);
              }
              table.Add(split);
          }
          r.Close();
      }

      this.Chart.Series.Clear();
      Chart.Titles.Add("TCB progress");

      for (int i = 0; i < 7; i++)
      {
          Series series = this.Chart.Series.Add(headers[0][i]);
          if (!headers[0][i].Contains("Batch"))
              Chart.Legends.Add(new Legend(headers[0][i]));

          for (int j = 1; j <= 6; j++)
          {
              if (table[i][j].All(char.IsDigit) && Convert.ToInt32(table[i][j]) > 10)
              {
                  series.Points.AddXY(table[i][j], table[i][j]);
              }
          }
      }
  }
</code>```

XAML ->

```<code><WindowsFormsHost>
        <wf:Chart x:Name="Chart">
            <wf:Chart.Series>
                <wf:Series Name="TCB" ChartType="Column" />
            </wf:Chart.Series>
            <wf:Chart.ChartAreas>
                <wf:ChartArea />
            </wf:Chart.ChartAreas>
        </wf:Chart>
    </WindowsFormsHost>
</code>```

The Result ->

Title: How to add custom labels to X axis

Body:
I'm trying to display a bar chart using System.Windows.Forms.DataVisualization.Charting in WPF
But i'm unable to change the label of each series on this graph.

Code behind ->

I have used one file to read the data and display those values onto the graph

public MainWindow()
  {
      InitializeComponent();

      string[] split = new string[6];
      var table = new List<string[]>();
      List<string[]> headers = new List<string[]>();

      using (var r = new StreamReader(@"C:\Users\ee212551\Desktop\Sheet.csv"))
      {
          while (!r.EndOfStream)
          {
              string line = r.ReadLine();
              split = line.Split(',');
              if (split[0].All(char.IsLetter))
              {
                  headers.Add(split);
              }
              table.Add(split);
          }
          r.Close();
      }

      this.Chart.Series.Clear();
      Chart.Titles.Add("TCB progress");

      for (int i = 0; i < 7; i++)
      {
          Series series = this.Chart.Series.Add(headers[0][i]);
          if (!headers[0][i].Contains("Batch"))
              Chart.Legends.Add(new Legend(headers[0][i]));

          for (int j = 1; j <= 6; j++)
          {
              if (table[i][j].All(char.IsDigit) && Convert.ToInt32(table[i][j]) > 10)
              {
                  series.Points.AddXY(table[i][j], table[i][j]);
              }
          }
      }
  }

XAML ->

<WindowsFormsHost>
        <wf:Chart x:Name="Chart">
            <wf:Chart.Series>
                <wf:Series Name="TCB" ChartType="Column" />
            </wf:Chart.Series>
            <wf:Chart.ChartAreas>
                <wf:ChartArea />
            </wf:Chart.ChartAreas>
        </wf:Chart>
    </WindowsFormsHost>

The Result ->


问:
how to show upcoming data in Lightning datatable in aura lightning?
Apex class code-

```<code>public class DesignAttClass {

    @AuraEnabled public static sObject[] getRecords(String query) {
        return Database.query(query);

    }
}
</code>```

helper code-

```<code>({
    getRecrdHelper : function(component, event, helper) {
        var action = component.get('c.getRecords');
        action.setParams({'query' : component.get('v.Query')});
        action.setCallback(this, function (res){
            if(res.getState() === 'SUCCESS'){
                console.log('Received = '+JSON.stringify(res.getReturnValue()));
                component.set('v.recordsData',res.getReturnValue());

            }else{
                console.log('Something went wrong...!!!!');
            }
        });
        $A.enqueueAction(action);
    }
})
</code>```

Now i wanted to try the upcoming data show in lightning datatable dynamically.

Body:
Apex class code-

public class DesignAttClass {

    @AuraEnabled public static sObject[] getRecords(String query) {
        return Database.query(query);

    }
}

helper code-

({
    getRecrdHelper : function(component, event, helper) {
        var action = component.get('c.getRecords');
        action.setParams({'query' : component.get('v.Query')});
        action.setCallback(this, function (res){
            if(res.getState() === 'SUCCESS'){
                console.log('Received = '+JSON.stringify(res.getReturnValue()));
                component.set('v.recordsData',res.getReturnValue());

            }else{
                console.log('Something went wrong...!!!!');
            }
        });
        $A.enqueueAction(action);
    }
})

Now i wanted to try the upcoming data show in lightning datatable dynamically.


问:
Android 12 How to open web link in browser with deep link setup
in my Android app, I have deep link setup and it is working fine.

now I want to open the web link in browser from the app

```<code> startActivity(
            Intent(
                Intent.ACTION_VIEW,
                Uri.parse(CHANGE_PASSWORD_URL)
            )
        )
</code>```

and my deep link setup

```<code>intent.data?.toString()?.let { deeplinkUrl ->
        try {
            Url(deeplinkUrl)
        } catch (exception: URLParserException) {
            crashManager.logException(exception)
            null
        }?.let { url ->
            deepLinkManager.navigateToScreen(
                activity = this,
                url = url,
            ) { deepLink ->
                when (deepLink) {
                    Basket -> navigateBasket()
                    HomePage -> navigateDashboard()
                    Notifications -> navigateNotifications()
                    Search -> moveToSearchFragment()

                    else -> backToDashboard()
                }
            }
        }
    }
</code>```

when I click on the change password button I want to open the link in web browser, but instead, it is open the dashboard of the app.

my question is is there a way to open browser directly without going through the deeplink process.

Body:
in my Android app, I have deep link setup and it is working fine.

now I want to open the web link in browser from the app

 startActivity(
            Intent(
                Intent.ACTION_VIEW,
                Uri.parse(CHANGE_PASSWORD_URL)
            )
        )

and my deep link setup

intent.data?.toString()?.let { deeplinkUrl ->
        try {
            Url(deeplinkUrl)
        } catch (exception: URLParserException) {
            crashManager.logException(exception)
            null
        }?.let { url ->
            deepLinkManager.navigateToScreen(
                activity = this,
                url = url,
            ) { deepLink ->
                when (deepLink) {
                    Basket -> navigateBasket()
                    HomePage -> navigateDashboard()
                    Notifications -> navigateNotifications()
                    Search -> moveToSearchFragment()

                    else -> backToDashboard()
                }
            }
        }
    }

when I click on the change password button I want to open the link in web browser, but instead, it is open the dashboard of the app.

my question is is there a way to open browser directly without going through the deeplink process.


问:
I'm not getting any output from firebase to telegram
I'm trying to retrieve value from firebase database which is RTDB

it doesnt send any error or output any error as i know of so im really confused as to why.
it worked fine a minute ago.

below is my code to retrieve value from table and send through telegram

```<code>import * as functions from "firebase-functions";
import * as express from "express";
import * as cors from "cors";
import * as admin from "firebase-admin";

admin.initializeApp();
const bot = express();

bot.use(cors({origin: true}));

bot.post("/", async function(req, res) {
  if (
    req.body &&
    req.body.message &&
    req.body.message.chat &&
    req.body.message.chat.id &&
    req.body.message.from &&
    req.body.message.from.first_name
  ) {
    const chatId = req.body.message.chat.id;
    const firstName = req.body.message.from.first_name;
    const receivedMessage = req.body.message.text;

    // Check if the received message is the "/start" command
    if (receivedMessage === "/start") {
      // Define your RTDB Reference to point to the "Sensor MQ7" parent node
      const rtdbReference = admin.database().ref("Sensor MQ7");

      // Read the latest unknown child node of "Sensor MQ7"
      const wildcardNodeSnapshot = await rtdbReference
          .limitToLast(1)
          .once("child_added");

      // Read the known child nodes of the unknown child node
      const coConcentrationSnapshot = wildcardNodeSnapshot.child("MQ7");
      const latSnapshot = wildcardNodeSnapshot.child("latitude");
      const longSnapshot = wildcardNodeSnapshot.child("longitude");
      const timeSnapshot = wildcardNodeSnapshot.child("time");

      // Get the values of the known child nodes
      const coConcentration = coConcentrationSnapshot.val();
      const time = timeSnapshot.val();
      const latitude = latSnapshot.val();
      const longtitude = longSnapshot.val();

      // Check if the known child node value is above 100
      if (coConcentration > 100) {
        // Return the response with a button interface
        return res.status(200).send({
          method: "sendMessage",
          chatId,
          text: `${firstName} is in danger! Carbon Monoxide Concentration is too high: ${coConcentration}. Last known location is at (${latitude},${longtitude}) approximately ${time} o clock.`,
          reply_markup: {
            inline_keyboard: [
              [
                {
                  text: `Call ${firstName}`,
                  callback_data: "call_user",
                },
              ],
            ],
          },
        });
      }
    }
  } else {
    // Return an error message if the request body is missing the required information
    return res.status(400).send({
      status: "An error occurred. The request body is missing the required information.",
    });
  }
  // Return an empty response
  return res.status(200).send({});
});

export const router = functions.https.onRequest(bot);

</code>```

expected output should be like this: output

its strange because when i do /start it doesnt even send a blank reply
i was supposed to output the database value

Body:
I'm trying to retrieve value from firebase database which is RTDB

it doesnt send any error or output any error as i know of so im really confused as to why.
it worked fine a minute ago.

below is my code to retrieve value from table and send through telegram

import * as functions from "firebase-functions";
import * as express from "express";
import * as cors from "cors";
import * as admin from "firebase-admin";

admin.initializeApp();
const bot = express();

bot.use(cors({origin: true}));

bot.post("/", async function(req, res) {
  if (
    req.body &&
    req.body.message &&
    req.body.message.chat &&
    req.body.message.chat.id &&
    req.body.message.from &&
    req.body.message.from.first_name
  ) {
    const chatId = req.body.message.chat.id;
    const firstName = req.body.message.from.first_name;
    const receivedMessage = req.body.message.text;

    // Check if the received message is the "/start" command
    if (receivedMessage === "/start") {
      // Define your RTDB Reference to point to the "Sensor MQ7" parent node
      const rtdbReference = admin.database().ref("Sensor MQ7");

      // Read the latest unknown child node of "Sensor MQ7"
      const wildcardNodeSnapshot = await rtdbReference
          .limitToLast(1)
          .once("child_added");

      // Read the known child nodes of the unknown child node
      const coConcentrationSnapshot = wildcardNodeSnapshot.child("MQ7");
      const latSnapshot = wildcardNodeSnapshot.child("latitude");
      const longSnapshot = wildcardNodeSnapshot.child("longitude");
      const timeSnapshot = wildcardNodeSnapshot.child("time");

      // Get the values of the known child nodes
      const coConcentration = coConcentrationSnapshot.val();
      const time = timeSnapshot.val();
      const latitude = latSnapshot.val();
      const longtitude = longSnapshot.val();

      // Check if the known child node value is above 100
      if (coConcentration > 100) {
        // Return the response with a button interface
        return res.status(200).send({
          method: "sendMessage",
          chatId,
          text: `${firstName} is in danger! Carbon Monoxide Concentration is too high: ${coConcentration}. Last known location is at (${latitude},${longtitude}) approximately ${time} o clock.`,
          reply_markup: {
            inline_keyboard: [
              [
                {
                  text: `Call ${firstName}`,
                  callback_data: "call_user",
                },
              ],
            ],
          },
        });
      }
    }
  } else {
    // Return an error message if the request body is missing the required information
    return res.status(400).send({
      status: "An error occurred. The request body is missing the required information.",
    });
  }
  // Return an empty response
  return res.status(200).send({});
});

export const router = functions.https.onRequest(bot);

expected output should be like this: output

its strange because when i do /start it doesnt even send a blank reply
i was supposed to output the database value


问:
Google cloud - IoT core devices - how to create separate alerts for each device with 1 policy
Use Case - We're using IoT core with lot of devices. Each device have lot of logs and we want to create an alert for a specific log message. I can create a metric and a metric alert and send notifications to slack, which is working.

But, the notifications are not specific to a device. We want to separate the alerts for each device. Something like, each device have to create a separate incident/alert. Please let me know if this possible in GCP.

Tried creating a new metric for the log message. Created an alert for the metric. The alerts are generating in slack. but the notifications are not device specific. Since we have lot of devices in production it'd be ideal to have separate notification for each device.

We don't want to create too many metrics/alerts by making a 1:1 with devices. Looking for creating 1 metric 1 alert for all the devices.


问:
SMS getting received after a long delay (using SIMCOM SIM900A and Raspberry Pi 4)
I am trying to read messages from sim900a as they get received and filter them to get the required messages. But most of the times the message are getting delayed (10-60 min). I need the delay to be as minimum as possible.

The AT commands I am using to initialize the connection are:

```<code>ATZ

AT+CMGF=1

AT+CSDH=1

AT+CLTS=1

AT+CPMS="SM","SM","SM"

AT+CNMI=1,1,0,0,0

AT+CSCS=\"GSM\"

AT+CSAS
</code>```

And to read messages I am using

```<code>AT+CMGL=\"ALL\"
</code>```

I have used different and same carrier sims but the delay largely remains same (slightly reduced in case of same carriers). I used the sims in two mobile phones and the messages are received almost instantly.

Body:
I am trying to read messages from sim900a as they get received and filter them to get the required messages. But most of the times the message are getting delayed (10-60 min). I need the delay to be as minimum as possible.

The AT commands I am using to initialize the connection are:

ATZ

AT+CMGF=1

AT+CSDH=1

AT+CLTS=1

AT+CPMS="SM","SM","SM"

AT+CNMI=1,1,0,0,0

AT+CSCS=\"GSM\"

AT+CSAS

And to read messages I am using

AT+CMGL=\"ALL\"

I have used different and same carrier sims but the delay largely remains same (slightly reduced in case of same carriers). I used the sims in two mobile phones and the messages are received almost instantly.


问:
Unable to determine the relationship represented by navigation
In this project, I have lots of devices, for example, d1, d2, d3. If d1.currentVaue > 100, then d2 write value 30, d3 write value 80.

This is the class:

```<code>public class Device
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Operator { get; set; }
    public  string CurrentValue { get; set; }
    public List<Linkage> Linkages { get; set; }
}
</code>```

and LinkAge:

```<code>public class Linkage
{
    public int Id { get; set; }
    public Device BelongPoint { get; set; }
    public Device WritePoint { get; set; }
    public string WriteValue { get; set; }
}
</code>```

user Entity FrameworkCore，and add-migration, Error Infomation:

Unable to determine the relationship represented by navigation
'Device.Linkages' of type 'List'. Either manually
configure the relationship, or ignore this property using the
'[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
'OnModelCreating'.

Google tells me use InverseProperty, but the Sample user 2 different collect, here only one collection, how to fix the problem?

Body:
In this project, I have lots of devices, for example, d1, d2, d3. If d1.currentVaue > 100, then d2 write value 30, d3 write value 80.

This is the class:

public class Device
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Operator { get; set; }
    public  string CurrentValue { get; set; }
    public List<Linkage> Linkages { get; set; }
}

and LinkAge:

public class Linkage
{
    public int Id { get; set; }
    public Device BelongPoint { get; set; }
    public Device WritePoint { get; set; }
    public string WriteValue { get; set; }
}

user Entity FrameworkCore，and add-migration, Error Infomation:

Unable to determine the relationship represented by navigation
'Device.Linkages' of type 'List'. Either manually
configure the relationship, or ignore this property using the
'[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in
'OnModelCreating'.

Google tells me use InverseProperty, but the Sample user 2 different collect, here only one collection, how to fix the problem?


问:
converting c# REST API consuming code to python
I have a piece of code in C# which consumes REST API successfully,
This API provider provided to me the below parameters:

In addition to that they provided a very poor documentation
the code in C# which is working is :

```<code>private HttpClient GetClientPrepared()
        {
            var client = new HttpClient();
            PrepareHttpClient(client);
            client.BaseAddress = new Uri(API_ROOT_URL);
            client.DefaultRequestHeaders.Accept.Clear();
            return client;
        }

        public void PrepareHttpClient(HttpClient client)
        {
            string CurrentOTP = this.CurrentOTP;
            var Digest = HashHMACString($"{API_SECRET}{CurrentOTP}", this.JWT_TOKEN);
            client.DefaultRequestHeaders.Add("Authorization", this.JWT_TOKEN);
            client.DefaultRequestHeaders.Add("OTP", CurrentOTP);
            client.DefaultRequestHeaders.Add("UPAD", Digest);
        }
        public static string HashHMACString(string key_string, string message_string)
        {
            return ByteArrayToString(HashHMAC(key_string, message_string));
        }
        public static byte[] HashHMAC(string key_string, string message_string)
        {
            byte[] key = Encoding.ASCII.GetBytes(key_string);
            byte[] message = Encoding.ASCII.GetBytes(message_string);
            var hash = new HMACSHA256(key);
            return hash.ComputeHash(message);
        }
        public static string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

        public bool Login()
        {
            var reso = InternalLogin();
            if (reso.ErrorCode != 0)
                return false;
            if (ValidateOTP(reso.Result.OTP))// Server Authentication You Can Hash This Part
            {
                this.JWT_TOKEN = reso.Result.Token;
                this.LastAuthTime = DateTime.Now;
                return true;
            }
            return false;
        }
        private ResponseContainer<AuthenticateResponse> InternalLogin()
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(API_ROOT_URL);
            client.DefaultRequestHeaders.Accept.Clear();
            var outPayload = new AuthenticateRequest
            {
                API_KEY = this.API_KEY,
                API_USER = this.API_USER,
                API_PASSWORD = this.API_PASSWORD,
            };
            var p = client.PostAsJsonAsync(
                $"{this.API_ROOT_URL}/Users/authenticate", outPayload);
            p.Wait();
            var pStringX = p.Result.Content.ReadAsStringAsync();
            pStringX.Wait();
            if (!p.Result.IsSuccessStatusCode)
            {
                ResponseContainer<AuthenticateResponse> result = new();
                result.ErrorCode = 1;
                result.ErrorMessage = "LOGIN ERROR";
                result.Result = null;
                return result;
            }
            var pString = p.Result.Content.ReadAsStringAsync();
            pString.Wait();
            return JsonConvert.DeserializeObject<ResponseContainer<AuthenticateResponse>>(pString.Result);
        }
        public bool ValidateOTP(string incomingOTP)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            return tfa.ValidateTwoFactorPIN
                (
                this.API_OTP_SECRET,
                incomingOTP,
                TimeSpan.FromSeconds(SERVER_OTP_VALIDATION_WINDOW)
                );
        }
        public string CurrentOTP
        {
            get
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                return tfa.GetCurrentPIN(this.API_OTP_SECRET, false);
            }
        }
    }
</code>```

I have to convert this to python version 3

I could managed to authenticate with he below function and i receive token and otp successfully
by using this function

```<code>def upa_login():
    import jwt
    base_url = "https://staging.upa.gov.eg"
    method = "/Users/authenticate"
    apiKey = '#############'
    apiUser = '##################'
    apiPassword = '#############'
    str_byte = bytes(f"'API_KEY':{apiKey}, 'API_USER':{apiUser}, 'API_PASSWORD':{apiPassword}", 'utf-8')

    auth = b64encode(str_byte).decode("ascii")

    headers = { 'Authorization' : f'Bearer {auth}',
                'Content-Type': "application/json,text/json,application/*+json"}
    body = {"API_KEy":apiKey, 'API_USER':apiUser, 'API_PASSWORD':apiPassword}

    response = requests.post(base_url+method,headers=headers, json=body)

    return {'token':response.json().get('result').get('token'), 'otp':response.json().get('result').get('otp')}
</code>```

and according to the documentation i can make a po search using this method:
/Vendor/poSearch

and i am trying to do with below functions but always it gives me unauthorized

```<code>def poSearch():
    base_url = "https://xxxxx"
    method = "/Vendor/poSearch"
    auth = upa_login()
    otp = auth['otp']
    token = auth['token']
    apiSecret = '#################'
    apiOtpSecret = '#################'

    totp = pyotp.TOTP(apiOtpSecret)

    headers = { 'Authorization' : f'Bearer {token}',
                'OTP': otp,
                'UPAD': create_signature(token, apiSecret+totp.now()),
                'Content-Type': "application/json,text/json,application/*+json"}
    body = {
        'offset':   10,
        'maxCount': 25,
        'fromDate': None,
        'toDate': None,
        'poStatus': 3
    }
    response = requests.post(base_url+method,headers=headers, data= body)
    return response.json()

def create_signature(data_to_sign: str, secret_key: str, encoding='utf-8') -> str:
    secret_key = secret_key.encode(encoding) # convert to bytes
    data_to_sign = data_to_sign.encode(encoding) # convert to bytes
    secret_key = b64decode(secret_key) # this is still bytes

    digest = hmac.new(secret_key, data_to_sign, digestmod=hashlib.sha256).digest() # still bytes

    digest_b64 = b64encode(digest) # bytes again

    return digest_b64.decode(encoding) # that's now str

def get_hotp_token(secret, intervals_no):
    key = b32decode(secret, True)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

def get_totp_token(secret):
    return get_hotp_token(secret, intervals_no=int(time.time())//30)
</code>```

how can i do in python correctly?

Body:
I have a piece of code in C# which consumes REST API successfully,
This API provider provided to me the below parameters:

In addition to that they provided a very poor documentation
the code in C# which is working is :

private HttpClient GetClientPrepared()
        {
            var client = new HttpClient();
            PrepareHttpClient(client);
            client.BaseAddress = new Uri(API_ROOT_URL);
            client.DefaultRequestHeaders.Accept.Clear();
            return client;
        }

        public void PrepareHttpClient(HttpClient client)
        {
            string CurrentOTP = this.CurrentOTP;
            var Digest = HashHMACString($"{API_SECRET}{CurrentOTP}", this.JWT_TOKEN);
            client.DefaultRequestHeaders.Add("Authorization", this.JWT_TOKEN);
            client.DefaultRequestHeaders.Add("OTP", CurrentOTP);
            client.DefaultRequestHeaders.Add("UPAD", Digest);
        }
        public static string HashHMACString(string key_string, string message_string)
        {
            return ByteArrayToString(HashHMAC(key_string, message_string));
        }
        public static byte[] HashHMAC(string key_string, string message_string)
        {
            byte[] key = Encoding.ASCII.GetBytes(key_string);
            byte[] message = Encoding.ASCII.GetBytes(message_string);
            var hash = new HMACSHA256(key);
            return hash.ComputeHash(message);
        }
        public static string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

        public bool Login()
        {
            var reso = InternalLogin();
            if (reso.ErrorCode != 0)
                return false;
            if (ValidateOTP(reso.Result.OTP))// Server Authentication You Can Hash This Part
            {
                this.JWT_TOKEN = reso.Result.Token;
                this.LastAuthTime = DateTime.Now;
                return true;
            }
            return false;
        }
        private ResponseContainer<AuthenticateResponse> InternalLogin()
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri(API_ROOT_URL);
            client.DefaultRequestHeaders.Accept.Clear();
            var outPayload = new AuthenticateRequest
            {
                API_KEY = this.API_KEY,
                API_USER = this.API_USER,
                API_PASSWORD = this.API_PASSWORD,
            };
            var p = client.PostAsJsonAsync(
                $"{this.API_ROOT_URL}/Users/authenticate", outPayload);
            p.Wait();
            var pStringX = p.Result.Content.ReadAsStringAsync();
            pStringX.Wait();
            if (!p.Result.IsSuccessStatusCode)
            {
                ResponseContainer<AuthenticateResponse> result = new();
                result.ErrorCode = 1;
                result.ErrorMessage = "LOGIN ERROR";
                result.Result = null;
                return result;
            }
            var pString = p.Result.Content.ReadAsStringAsync();
            pString.Wait();
            return JsonConvert.DeserializeObject<ResponseContainer<AuthenticateResponse>>(pString.Result);
        }
        public bool ValidateOTP(string incomingOTP)
        {
            TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
            return tfa.ValidateTwoFactorPIN
                (
                this.API_OTP_SECRET,
                incomingOTP,
                TimeSpan.FromSeconds(SERVER_OTP_VALIDATION_WINDOW)
                );
        }
        public string CurrentOTP
        {
            get
            {
                TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
                return tfa.GetCurrentPIN(this.API_OTP_SECRET, false);
            }
        }
    }

I have to convert this to python version 3

I could managed to authenticate with he below function and i receive token and otp successfully
by using this function

def upa_login():
    import jwt
    base_url = "https://staging.upa.gov.eg"
    method = "/Users/authenticate"
    apiKey = '#############'
    apiUser = '##################'
    apiPassword = '#############'
    str_byte = bytes(f"'API_KEY':{apiKey}, 'API_USER':{apiUser}, 'API_PASSWORD':{apiPassword}", 'utf-8')

    auth = b64encode(str_byte).decode("ascii")

    headers = { 'Authorization' : f'Bearer {auth}',
                'Content-Type': "application/json,text/json,application/*+json"}
    body = {"API_KEy":apiKey, 'API_USER':apiUser, 'API_PASSWORD':apiPassword}

    response = requests.post(base_url+method,headers=headers, json=body)

    return {'token':response.json().get('result').get('token'), 'otp':response.json().get('result').get('otp')}

and according to the documentation i can make a po search using this method:
/Vendor/poSearch

and i am trying to do with below functions but always it gives me unauthorized

def poSearch():
    base_url = "https://xxxxx"
    method = "/Vendor/poSearch"
    auth = upa_login()
    otp = auth['otp']
    token = auth['token']
    apiSecret = '#################'
    apiOtpSecret = '#################'

    totp = pyotp.TOTP(apiOtpSecret)

    headers = { 'Authorization' : f'Bearer {token}',
                'OTP': otp,
                'UPAD': create_signature(token, apiSecret+totp.now()),
                'Content-Type': "application/json,text/json,application/*+json"}
    body = {
        'offset':   10,
        'maxCount': 25,
        'fromDate': None,
        'toDate': None,
        'poStatus': 3
    }
    response = requests.post(base_url+method,headers=headers, data= body)
    return response.json()

def create_signature(data_to_sign: str, secret_key: str, encoding='utf-8') -> str:
    secret_key = secret_key.encode(encoding) # convert to bytes
    data_to_sign = data_to_sign.encode(encoding) # convert to bytes
    secret_key = b64decode(secret_key) # this is still bytes

    digest = hmac.new(secret_key, data_to_sign, digestmod=hashlib.sha256).digest() # still bytes

    digest_b64 = b64encode(digest) # bytes again

    return digest_b64.decode(encoding) # that's now str

def get_hotp_token(secret, intervals_no):
    key = b32decode(secret, True)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = ord(h[19]) & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

def get_totp_token(secret):
    return get_hotp_token(secret, intervals_no=int(time.time())//30)

how can i do in python correctly?