问:
Helm not adding timeout param in API server call
When we use helm to create Istio VirtualService or DestinationRules, it takes more than 30seconds. So we have set up a higher timeout of 5m.

Command used
helm upgrade --install --wait --timeout 5m --v 9 helloworld ./templateDir

However, I see that helm is not passing the new timeout value in APIserver call.
When we use kubectl to create the same, we set --request-timeout param for kubectl and everything is fine

Since it is a timeout from apiserver, is it possible to set a higher timeout value for all API server requests from helm? Is there any other workaround you can suggest for this problem ?

```<code>I0528 17:52:57.664992   11148 round_trippers.go:423] curl -k -v -XPOST  -H "Content-Type: application/json" -H "Accept: application/json" 'https://aaaa.sk1.us-east-1.eks.amazonaws.com/apis/networking.istio.io/v1beta1/namespaces/default/destinationrules '
I0528 17:53:27.981691   11148 round_trippers.go:443] POST https://aaaa.sk1.us-east-1.eks.amazonaws.com/apis/networking.istio.io/v1beta1/namespaces/default/destinationrules  504 Gateway Timeout in 30316 milliseconds
I0528 17:53:27.981691   11148 round_trippers.go:449] Response Headers:
I0528 17:53:27.981691   11148 round_trippers.go:452]     Audit-Id: cba23005-b8db-47f7-8801-4c89e6447cd3
I0528 17:53:27.981691   11148 round_trippers.go:452]     Content-Type: application/json
I0528 17:53:27.981691   11148 round_trippers.go:452]     Content-Length: 187
I0528 17:53:27.981691   11148 round_trippers.go:452]     Date: Thu, 28 May 2020 12:23:27 GMT
I0528 17:53:27.981691   11148 request.go:1017] Response Body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Timeout: request did not complete within requested timeout 30s","reason":"Timeout","details":{},"code":504}
I0528 17:53:27.982759   11148 request.go:1017] Request Body: {"apiVersion":"networking.istio.io/v1beta1","kind":"VirtualService","metadata":{"name":"mbrsvc","namespace":"default"},"spec":{"hosts":["mbrsvc"],"http":[{"route":[{"destination":{"host":"mbrsvc","subset":"1.0.0"},"weight":100}]}]}}
</code>```

答:
Documentation states that the --timeout should be in seconds.

--timeout: A value in seconds to wait for Kubernetes commands to complete This defaults to 5m0s

--wait: Waits until all Pods are in a ready state, PVCs are bound, Deployments have minimum (Desired minus maxUnavailable) Pods in ready state and Services have an IP address (and Ingress if a LoadBalancer) before marking the release as successful. It will wait for as long as the --timeout value. If timeout is reached, the release will be marked as FAILED. Note: In scenario where Deployment has replicas set to 1 and maxUnavailable is not set to 0 as part of rolling update strategy, --wait will return as ready as it has satisfied the minimum Pod in ready condition.

Hope that helps.

Body:
When we use helm to create Istio VirtualService or DestinationRules, it takes more than 30seconds. So we have set up a higher timeout of 5m.

Command used
helm upgrade --install --wait --timeout 5m --v 9 helloworld ./templateDir

However, I see that helm is not passing the new timeout value in APIserver call.
When we use kubectl to create the same, we set --request-timeout param for kubectl and everything is fine

Since it is a timeout from apiserver, is it possible to set a higher timeout value for all API server requests from helm? Is there any other workaround you can suggest for this problem ?

I0528 17:52:57.664992   11148 round_trippers.go:423] curl -k -v -XPOST  -H "Content-Type: application/json" -H "Accept: application/json" 'https://aaaa.sk1.us-east-1.eks.amazonaws.com/apis/networking.istio.io/v1beta1/namespaces/default/destinationrules '
I0528 17:53:27.981691   11148 round_trippers.go:443] POST https://aaaa.sk1.us-east-1.eks.amazonaws.com/apis/networking.istio.io/v1beta1/namespaces/default/destinationrules  504 Gateway Timeout in 30316 milliseconds
I0528 17:53:27.981691   11148 round_trippers.go:449] Response Headers:
I0528 17:53:27.981691   11148 round_trippers.go:452]     Audit-Id: cba23005-b8db-47f7-8801-4c89e6447cd3
I0528 17:53:27.981691   11148 round_trippers.go:452]     Content-Type: application/json
I0528 17:53:27.981691   11148 round_trippers.go:452]     Content-Length: 187
I0528 17:53:27.981691   11148 round_trippers.go:452]     Date: Thu, 28 May 2020 12:23:27 GMT
I0528 17:53:27.981691   11148 request.go:1017] Response Body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Timeout: request did not complete within requested timeout 30s","reason":"Timeout","details":{},"code":504}
I0528 17:53:27.982759   11148 request.go:1017] Request Body: {"apiVersion":"networking.istio.io/v1beta1","kind":"VirtualService","metadata":{"name":"mbrsvc","namespace":"default"},"spec":{"hosts":["mbrsvc"],"http":[{"route":[{"destination":{"host":"mbrsvc","subset":"1.0.0"},"weight":100}]}]}}


来源: stackexchange

问:
Typescript: Filter Object by Interface or Class
I would like to sync an object that is provided by an API to a table.
The table is defined in Sequelize and has an interface and a class:

declare interface SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}
```

<pre class="lang-js prettyprint-override"><code>class SampleClass implements SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}
</code>```

The response of the API is not always the same, but could look something like this:

const sampleResponse = {
  value2: "..."
  value3: 0
  value4: "..."
}
```

<p>Now, I would only like create a new object that can be passed to sequelize that has the matching contents, for example:</p>

<pre class="lang-js prettyprint-override"><code>const filteredResponse = {
  value2: "..."
  value3: 0
}
</code>```

How can I match the object properties keys to the interface or class?

Thanks!

答:
If I understand you right, you:

Have: API which produces not 100% predictable response.

Want: to create a concrete instance of the class from this untrusted source

If I am right you have two options:

If input object is not very big and dynamic you could do everything explicitly:

const unreliableObject = fetchFromApi();
const result = new Result();

if (typeof unreliableObject.name  === 'string') {
    result.name = unreliableObject.name;
}
```
<p>This code is more-less OK except it is <strong>toooo</strong> verbose.</p>
<p>As a bit more advanced solution, you can create TransformationMapper, something like this:</p>
<pre class="lang-js prettyprint-override"><code>class MyClass {
    name: string;
}

const expectedKeys: (keyof MyClass)[] = ['name'];
const data: any = { v: 1, name: '13212' };

const res = expectedKeys.reduce((result, fieldName) => {

    const value = data[fieldName];
    if (value != null) {
        result[fieldName] = data[fieldName]
    }

    return result;
}, new MyClass());

console.log(res);
</code>```

UPDATE

Is there any way, I could the get keyof MyClass programmatically

The main idea is to get a scheme to parse the original response. Luckily, you already got it.

So you need to: create an instance of the desired class, and get keys from it:

This can be done using:

Object.keys()

Object.entries()

const data: any = {};

let result = new MyClass();
result = Object.keys(result).reduce((result, fieldName) => {

    const value = data[fieldName];
    if (value != null) {
        result[fieldName] = data[fieldName]
    }

    return result;
}, result)
```

But I also have to warn you. If you don't trust API, you should not only parse, but also validate values you are parsing. In another case, incorrect types provided via API may break your app.

You can write your own validation (it is not that hard) or take something existing like yup

ContentLicense: CC BY-SA 4.0

Body:
I would like to sync an object that is provided by an API to a table.
The table is defined in Sequelize and has an interface and a class:

declare interface SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}

class SampleClass implements SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}

The response of the API is not always the same, but could look something like this:

const sampleResponse = {
  value2: "..."
  value3: 0
  value4: "..."
}

Now, I would only like create a new object that can be passed to sequelize that has the matching contents, for example:

const filteredResponse = {
  value2: "..."
  value3: 0
}

How can I match the object properties keys to the interface or class?

Thanks!

Body:
If I understand you right, you:

Have: API which produces not 100% predictable response.

Want: to create a concrete instance of the class from this untrusted source

If I am right you have two options:

If input object is not very big and dynamic you could do everything explicitly:

const unreliableObject = fetchFromApi();
const result = new Result();

if (typeof unreliableObject.name  === 'string') {
    result.name = unreliableObject.name;
}

This code is more-less OK except it is toooo verbose.

As a bit more advanced solution, you can create TransformationMapper, something like this:

class MyClass {
    name: string;
}

const expectedKeys: (keyof MyClass)[] = ['name'];
const data: any = { v: 1, name: '13212' };

const res = expectedKeys.reduce((result, fieldName) => {

    const value = data[fieldName];
    if (value != null) {
        result[fieldName] = data[fieldName]
    }

    return result;
}, new MyClass());

console.log(res);

UPDATE

Is there any way, I could the get keyof MyClass programmatically

The main idea is to get a scheme to parse the original response. Luckily, you already got it.

So you need to: create an instance of the desired class, and get keys from it:

This can be done using:

Object.keys()

Object.entries()

const data: any = {};

let result = new MyClass();
result = Object.keys(result).reduce((result, fieldName) => {

    const value = data[fieldName];
    if (value != null) {
        result[fieldName] = data[fieldName]
    }

    return result;
}, result)

But I also have to warn you. If you don't trust API, you should not only parse, but also validate values you are parsing. In another case, incorrect types provided via API may break your app.

You can write your own validation (it is not that hard) or take something existing like yup


问:
window.location in a tabbed website
I'm dealing with a website that uses tabs. The outer tab, is facebook.com. The inner tab is a facebook application.

When I run the following function:

```<code> $(document).ready(function() {
    // to show it in an alert window
    alert(window.location);

    // to store it in a variable
    var loc = window.location;
});
</code>```

The returned value is the url of the inner tab, the host. Is there a way to produce the url of the outer tab using a JQuery function?

答:
I guess your page is displayed using Iframes? In that case, you cannot do anything with the parent due to Same Origin Policy restriction. More info can be found on: http://en.wikipedia.org/wiki/Same_origin_policy.

If inner and outer tab are on same domain, use:

```<code>    var parentLoc = parent.location;
</code>```

Please note that above JavaScript statement won't work in case page url is for instance 'blah.facebook.com' and the facebook application is load from 'foo.facebook.com'.

ContentLicense: CC BY-SA 3.0

Title: window.location in a tabbed website

Body:
I'm dealing with a website that uses tabs. The outer tab, is facebook.com. The inner tab is a facebook application.

When I run the following function:

 $(document).ready(function() {
    // to show it in an alert window
    alert(window.location);

    // to store it in a variable
    var loc = window.location;
});

The returned value is the url of the inner tab, the host. Is there a way to produce the url of the outer tab using a JQuery function?

Body:
I guess your page is displayed using Iframes? In that case, you cannot do anything with the parent due to Same Origin Policy restriction. More info can be found on: http://en.wikipedia.org/wiki/Same_origin_policy.

If inner and outer tab are on same domain, use:

    var parentLoc = parent.location;

Please note that above JavaScript statement won't work in case page url is for instance 'blah.facebook.com' and the facebook application is load from 'foo.facebook.com'.


问:
IndentationError: expected an indented block Can someone help me
I get indentation error (IndentationError: expected an indented block)
can someone help at
def downloadVideo():

```<code>x = entry.get()

logging.debug(x + " - Done")
ydl_opts = {} --------------------------------------- I get error here
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([x])
</code>```

the code is again ()def downloadVideo():

```<code>x = entry.get()

logging.debug(x + " - Done")
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([x])
</code>```

答:
You need to indent this line:

```<code>ydl.download([x])
</code>```

So the resulting code should be something like:

```<code>x = entry.get()

logging.debug(x + " - Done")
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([x])
</code>```

Python requires indentation rather than curly braces like other programming languages you may be used to.

Body:
I get indentation error (IndentationError: expected an indented block)
can someone help at
def downloadVideo():

x = entry.get()

logging.debug(x + " - Done")
ydl_opts = {} --------------------------------------- I get error here
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([x])

the code is again ()def downloadVideo():

x = entry.get()

logging.debug(x + " - Done")
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([x])

Body:
You need to indent this line:

ydl.download([x])

So the resulting code should be something like:

x = entry.get()

logging.debug(x + " - Done")
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([x])

Python requires indentation rather than curly braces like other programming languages you may be used to.


问:
Kapt options are not recognized by any processor
I can't figure out why the kotlin annotation processor cannot resolve these arguments.

Relevant parts of my build.gradle.kts

```<code>plugins {
    id("kotlin-kapt")
}

android {
    defaultConfig {
        kapt {
            arguments {
                arg("room.incremental", "true")
                arg("room.schemaLocation", "$projectDir/schemas")
            }
        }
    }
}

dependencies {
    implementation("androidx.room:room-runtime:${Versions.room_version}") // room_version = "2.2.4"
    kapt("androidx.room:room-compiler:${Versions.room_version}")
    implementation("androidx.room:room-ktx:${Versions.room_version}")
}

</code>```

The exact warning I get is

```<code>> Task :app:kaptDebugKotlin
warning: The following options were not recognized by any processor: '[room.schemaLocation, kapt.kotlin.generated, room.incremental]'
The following options were not recognized by any processor: '[room.schemaLocation, kapt.kotlin.generated, room.incremental]'
</code>```

答: If your code does not use any of your Annotation processor's annotation then the kapt task will be skipped and no annotation processor will be invoked hence, options you passed will be ignored since no invoked annotation processor (if any) is interested in them.

Body:
I can't figure out why the kotlin annotation processor cannot resolve these arguments.

Relevant parts of my build.gradle.kts

plugins {
    id("kotlin-kapt")
}

android {
    defaultConfig {
        kapt {
            arguments {
                arg("room.incremental", "true")
                arg("room.schemaLocation", "$projectDir/schemas")
            }
        }
    }
}

dependencies {
    implementation("androidx.room:room-runtime:${Versions.room_version}") // room_version = "2.2.4"
    kapt("androidx.room:room-compiler:${Versions.room_version}")
    implementation("androidx.room:room-ktx:${Versions.room_version}")
}

The exact warning I get is

> Task :app:kaptDebugKotlin
warning: The following options were not recognized by any processor: '[room.schemaLocation, kapt.kotlin.generated, room.incremental]'
The following options were not recognized by any processor: '[room.schemaLocation, kapt.kotlin.generated, room.incremental]'


问:
Kafka s3 sink connector - many jsons in one json
I'm having an issue with the s3 sink connector. I set my flush-size to 3 (for tests) and my s3 is receiving properly the json file. But when I open the json, I don't have a list of jsons, I only have one after other. Is there any way to get "properly" the jsons in a list when they are sent to my bucket? I want to try a "good way" to solve that, else I'll fix this in a lambda function (but I wouldn't like to do it...)

What I have:

```<code>{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
</code>```

What I want

```<code>[{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}]
</code>```

答:
The S3 sink connector sends each message to S3 as its own message.

You're wanting to do something different, which is to batch messages together into discrete array objects.

To do this you'll need some kind of stream processing. For example, you could write a Kafka Streams processor that would process the topic and merge each batch of x messages into one message holding an array as you want.

Body:
I'm having an issue with the s3 sink connector. I set my flush-size to 3 (for tests) and my s3 is receiving properly the json file. But when I open the json, I don't have a list of jsons, I only have one after other. Is there any way to get "properly" the jsons in a list when they are sent to my bucket? I want to try a "good way" to solve that, else I'll fix this in a lambda function (but I wouldn't like to do it...)

What I have:

{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}

What I want

[{"before":null,"after":{"id":10230,"nome":"John","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10231,"nome":"Alan","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"},
{"before":null,"after":{"id":10232,"nome":"Rodrigo","idade":30,"cidade":"São Paulo","estado":"SP","sexo":"M"}]


问:
convert opengl Window to std::size_t and back again works in Linux, but not OS X
I have successfully converted an OpenGL Window to an std::size_t variable and then converted it back to an OpenGL Window in Linux.  However, when I try to do the same thing in Mac OS X it isn't working.  Here's what I'm doing:

```<code>/* our window instance(This is an X Window System Window!) */
    Window window_;
.
.

.
.
std::size_t OSXGLWindow::getWindowHandle() {
    return window_;
}
.
.
</code>```

Calling 'getWindowHandle()' just returns the Window as an std::size_t.

I pass this size_t window handle into the following function:

```<code>IInputManager* InputFactory::getInputMgr(std::size_t winHandle) {

    IInputManager* retObj = 0;
#ifdef _WIN32
    // todo: windows input implementation
#endif

#ifdef linux
    Window win = winHandle;
    retObj = new lwis::linuxos::LinuxInputManager(win);
#endif

#ifdef __APPLE__
    Window win = winHandle;
    retObj = new lwis::osx::OSXInputManager(win);
#endif

    return retObj;
}
</code>```

The LinuxInputManager and OSXInputManager both call the following bit of code:

```<code>XSelectInput(display_, theWindow,
            KeyPressMask | KeyReleaseMask | KeymapStateMask) == BadWindow)
</code>```

where 'theWindow' is the Window that was sent to the respective objects' constructor from the 'InputFactory::getInputMgr(..)' function.

The 'XSelectInput' is successful in the LinuxInputManager object for Linux, but not in the OSXInputManager for OS X.

Another important piece of information is that the Window is being passed between 2 static libraries, which is why it is converted to an std::size_t in the first place (to make it easy to pass between the libraries).

Anyone have any idea why this is?  Is there a better way to pass a handle between libraries?  Would a 'void*' be a better option?

答:
Well, why do you expect some other, unrelated type Window to be convertible to std::size_t and back without any losses? I would guess that you wouldn't be surprised to see that unsigned char does not work in that role, would you? If so, why are you surprised to see size_t fail?

size_t is just some unsigned integer type, with certain size and range. If you are converting some unrelated type to size_t, the conversion result might fit into size_t or it might not fit into it, depending on the platform, on the properties of the source type etc. Apparently, this is exactly what happens in your case.

Body:
I have successfully converted an OpenGL Window to an std::size_t variable and then converted it back to an OpenGL Window in Linux.  However, when I try to do the same thing in Mac OS X it isn't working.  Here's what I'm doing:

/* our window instance(This is an X Window System Window!) */
    Window window_;
.
.

.
.
std::size_t OSXGLWindow::getWindowHandle() {
    return window_;
}
.
.

Calling 'getWindowHandle()' just returns the Window as an std::size_t.

I pass this size_t window handle into the following function:

IInputManager* InputFactory::getInputMgr(std::size_t winHandle) {

    IInputManager* retObj = 0;
#ifdef _WIN32
    // todo: windows input implementation
#endif

#ifdef linux
    Window win = winHandle;
    retObj = new lwis::linuxos::LinuxInputManager(win);
#endif

#ifdef __APPLE__
    Window win = winHandle;
    retObj = new lwis::osx::OSXInputManager(win);
#endif

    return retObj;
}

The LinuxInputManager and OSXInputManager both call the following bit of code:

XSelectInput(display_, theWindow,
            KeyPressMask | KeyReleaseMask | KeymapStateMask) == BadWindow)

where 'theWindow' is the Window that was sent to the respective objects' constructor from the 'InputFactory::getInputMgr(..)' function.

The 'XSelectInput' is successful in the LinuxInputManager object for Linux, but not in the OSXInputManager for OS X.

Another important piece of information is that the Window is being passed between 2 static libraries, which is why it is converted to an std::size_t in the first place (to make it easy to pass between the libraries).

Anyone have any idea why this is?  Is there a better way to pass a handle between libraries?  Would a 'void*' be a better option?


问:
Linking Related IDs together through two other ID columns
I have a table of about 100k rows with the following layout:

```<code>+----+-----------+------------+-------------------+
| ID |    PIN    |    RAID    | Desired Output ID |
+----+-----------+------------+-------------------+
|  1 | 80602627  | 1737852-1  |                 1 |
|  2 | 80602627  | 34046655-1 |                 1 |
|  3 | 351418172 | 33661      |                 2 |
|  4 | 351418172 | 33661      |                 2 |
|  5 | 351418172 | 33661      |                 2 |
|  6 | 351418172 | 34443321-1 |                 2 |
|  7 | 491863017 | 26136      |                 3 |
|  8 | 491863017 | 34575      |                 3 |
|  9 | 491863017 | 34575      |                 3 |
| 10 | 661254727 | 26136      |                 3 |
| 11 | 661254727 | 26136      |                 3 |
| 12 | NULL      | 7517       |                 4 |
| 13 | NULL      | 7517       |                 4 |
| 14 | NULL      | 7517       |                 4 |
| 15 | NULL      | 7517       |                 4 |
| 16 | NULL      | 7517       |                 4 |
| 17 | 554843813 | 33661      |                 2 |
| 18 | 554843813 | 33661      |                 2 |
+----+-----------+------------+-------------------+
</code>```

The ID column has unique values, with the PIN and RAID columns being two separate identifying numbers used to group linked IDs together. The Desired Output ID column is what I would like SQL to do, essentially looking at both the PIN and RAID columns to spot where there are any relationships between them.

So for example Where Desired Output ID = 2, IDs 3-6 match on PIN = 351418172, and then IDs 17-18 also match as the RAID of 33661 was in the rows for IDs 3-5.

To add as well, NULLs will be in the PIN Column but not in any others.

I did spot a similar question Text however as it is in BigQuery I wasnt sure it would help.

Have been trying to crack this one for a while with no luck, any help massively appreciated.

答:
I suppose DENSE_RANK can solve your problem.  Not sure what the combination of PIN and RAID should be, but I think you'll be able to figure it out how to do it like this:</p>

```<code>SELECT *,DENSE_RANK( )  over (ORDER BY isnull(pin,id) ),DENSE_RANK( )  over (ORDER BY raid)
FROM accounts
</code>```

Body:
I have a table of about 100k rows with the following layout:

+----+-----------+------------+-------------------+
| ID |    PIN    |    RAID    | Desired Output ID |
+----+-----------+------------+-------------------+
|  1 | 80602627  | 1737852-1  |                 1 |
|  2 | 80602627  | 34046655-1 |                 1 |
|  3 | 351418172 | 33661      |                 2 |
|  4 | 351418172 | 33661      |                 2 |
|  5 | 351418172 | 33661      |                 2 |
|  6 | 351418172 | 34443321-1 |                 2 |
|  7 | 491863017 | 26136      |                 3 |
|  8 | 491863017 | 34575      |                 3 |
|  9 | 491863017 | 34575      |                 3 |
| 10 | 661254727 | 26136      |                 3 |
| 11 | 661254727 | 26136      |                 3 |
| 12 | NULL      | 7517       |                 4 |
| 13 | NULL      | 7517       |                 4 |
| 14 | NULL      | 7517       |                 4 |
| 15 | NULL      | 7517       |                 4 |
| 16 | NULL      | 7517       |                 4 |
| 17 | 554843813 | 33661      |                 2 |
| 18 | 554843813 | 33661      |                 2 |
+----+-----------+------------+-------------------+

The ID column has unique values, with the PIN and RAID columns being two separate identifying numbers used to group linked IDs together. The Desired Output ID column is what I would like SQL to do, essentially looking at both the PIN and RAID columns to spot where there are any relationships between them.

So for example Where Desired Output ID = 2, IDs 3-6 match on PIN = 351418172, and then IDs 17-18 also match as the RAID of 33661 was in the rows for IDs 3-5.

To add as well, NULLs will be in the PIN Column but not in any others.

I did spot a similar question Text however as it is in BigQuery I wasnt sure it would help.

Have been trying to crack this one for a while with no luck, any help massively appreciated.

Body:
I suppose DENSE_RANK can solve your problem.  Not sure what the combination of PIN and RAID should be, but I think you'll be able to figure it out how to do it like this:

SELECT *,DENSE_RANK( )  over (ORDER BY isnull(pin,id) ),DENSE_RANK( )  over (ORDER BY raid)
FROM accounts


问:
Angular - How to get data from subscribed service few times and not overwrite previous results
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }
```

<p>room-component.ts:</p>

<pre class="lang-js prettyprint-override"><code>@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });
</code>```

room-component.html

```

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?

答:
You can fetch the data once in your parent and pass the data to your child components.
That child component (RoomsComponent) should be dumb and not doing requests</p>

Body:
I have a service which has following method:

room-service.ts

@Injectable()
export class RoomService {
  private readonly _equipment: BehaviorSubject<EquipmentDto[]> = new BehaviorSubject([]);
  public equipment$ = this._equipment.asObservable();

  getEquipmentForRoom(roomId: number) {
    this.restService.getEquipmentForRoom(roomId).subscribe(res => {
      this._equipment.next(res);
    });
  }

room-component.ts:

@Component()
export class RoomsComponent implements OnInit {
  @Input() room: RoomEntity;
  equipment$: Observable < EquipmentDto[] > ;
  equipmentList: Array < EquipmentDto > ;

  constructor(private equipmentService: EquipmentService) {}

  ngOnInit() {
      this.equipment$ = this.equipmentService.equipment$;
      this.equipmentService.getEquipmentForRoom(this.room.id);

      this.equipment$.subscribe(items => {
        this.equipmentList = items;
      });

room-component.html

Now I have a parent component which contains multiple Room Components (those are added programmatically based on the amount of rooms). Anyway, list of equipment is the same for each of the rooms. It looks like once subscribed, the data in first components is overwritten by the component created as the last one.

My question is, how can I get a proper data for each of the rooms using the observable from my service?


问:
SCSS Animated checkbox : dynamic width
I have an animated flip SCSS checkbox, and I have 2 issues I cannot solve:

a) I wish to have a dynamic width, based on content and not static.
The problem is that I have 2 contents, one for 'checked' and one for 'unchecked'

b) I wish to add both icons (using fontawesome 5) and text, not exclusive (I mean an Icon+Text).
In the worst case, I wish a way to use either the icon, either the text

Here is how I define it:

```<code><input class="btn-toggle btn-toggle-flip" id="cb5" type="checkbox" />
<label class="btn-toggle-label" data-tg-off="UNSAVED" data-tg-on="SAVED" for="cb5"></label>
</code>```

The SCSS is too long, the best is to look at the sample here:

https://codepen.io/cdemez/pen/QWjXRjw

For both issues, search for the text 'data-tg-off' into the SCSS please ;-)

Do you have any idea?

Thx

答:
In order for :before and :after content to appear you need to set the width on your label element as there is no content inside your label (logically empty), only then you should be able to see the pseudo elements as the pseudo elements are rendered inside the element before and after the content of the element.
Also, for font-awesome to appear you need the unicodes of the icons that you want to show so that you can pass them as html attribute to css, but also you need to explicitly set the font-family for the pseudo elements which will make your text look weird. Two main things that solve your use cases are:

For icon to appear inside label & for dynamic widths of pseudo elements:

HTML

```<code><label class="btn-toggle-label" data-tg-off="UNSAVED &#xf004" data-tg-on="SAVED &#xf004 " for="cb5"></label>
</code>```

CSS

```<code>.btn-toggle-flip {
+ .btn-toggle-label {
    &:after,
    &:before {
       width: auto;
       max-width: 100%;
       font-family: "Font Awesome 5 Free";
    }
}
.btn-toggle-label {
    width: 200px;
}
</code>```

I've tried this workaround for both your use cases here, checkout this pen:

https://codepen.io/mudassirzr/pen/XWmvrWp

Title: SCSS Animated checkbox : dynamic width

Body:
I have an animated flip SCSS checkbox, and I have 2 issues I cannot solve:

a) I wish to have a dynamic width, based on content and not static.
The problem is that I have 2 contents, one for 'checked' and one for 'unchecked'

b) I wish to add both icons (using fontawesome 5) and text, not exclusive (I mean an Icon+Text).
In the worst case, I wish a way to use either the icon, either the text

Here is how I define it:

<input class="btn-toggle btn-toggle-flip" id="cb5" type="checkbox" />

The SCSS is too long, the best is to look at the sample here:

https://codepen.io/cdemez/pen/QWjXRjw

For both issues, search for the text 'data-tg-off' into the SCSS please ;-)

Do you have any idea?

Thx

Body:
In order for :before and :after content to appear you need to set the width on your label element as there is no content inside your label (logically empty), only then you should be able to see the pseudo elements as the pseudo elements are rendered inside the element before and after the content of the element.
Also, for font-awesome to appear you need the unicodes of the icons that you want to show so that you can pass them as html attribute to css, but also you need to explicitly set the font-family for the pseudo elements which will make your text look weird. Two main things that solve your use cases are:

For icon to appear inside label & for dynamic widths of pseudo elements:

HTML

<label class="btn-toggle-label" data-tg-off="UNSAVED &#xf004" data-tg-on="SAVED &#xf004 " for="cb5"></label>

CSS

.btn-toggle-flip {
+ .btn-toggle-label {
    &:after,
    &:before {
       width: auto;
       max-width: 100%;
       font-family: "Font Awesome 5 Free";
    }
}
.btn-toggle-label {
    width: 200px;
}

I've tried this workaround for both your use cases here, checkout this pen:

https://codepen.io/mudassirzr/pen/XWmvrWp


问:
Automatically tick checkbox when clicking on another form input field
I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

```<code><input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>
</code>```

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

答:
you can use jquery to achieve this:

HTML:

```<code><input type="checkbox" id="box">
<label for="box"></label>
<input type="text" id="mytextinput">
</code>```

JQuery:

```<code>$('#mytextinput').focus(function(){
$('#box').prop( "checked", true ); // true checks the checkbox false unchecks.
});
</code>```

Body:
I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

<input type="checkbox" id="box">

  <input type="text">

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

Body:
you can use jquery to achieve this:

HTML:

<input type="checkbox" id="box">
<label for="box"></label>
<input type="text" id="mytextinput">

JQuery:

$('#mytextinput').focus(function(){
$('#box').prop( "checked", true ); // true checks the checkbox false unchecks.
});


问:
Jupyter notebook not trusted
I am using Anaconda to work on a Jupyter notebook which displays "Not Trusted" (see on screenshot below).

What does it mean? Is it a problem? How can I solve it?

答: This can also happen when you create a notebook in a docker container with mounted volume (the file is owned by the root user) and then open in in jupyter running on the host machine. Changing file owner to the host user helps.</p>

Title: Jupyter notebook not trusted


问:
I want to run two or more simulink model in parallel and synchronisation.
Hi I want to run two or more simulink model in parallel and synchronisation. is there any way to do it? One way I think is by creating a subsystem and put all models inside it. It should run parallely. This one is not prefered for me. I want to open two matlab instances and run two different model in synchronisation. is this possible? I want to do it programmatically. Any help is appreciable.</p>

答:
The best way to run parallel simulink simulations is probably the parsim command. Their is a complete article on the Mathworks website explaining how to do it:

Run Parallel Simulations


问:
Visual Studio code - cannot connect to runtime process timeout after 10000 ms
I was trying to launch the program from the debug console in VS Code but got the error on cannot connect to runtime process timeout after 10000 ms

launch.json

```<code>   "version": "0.2.0",
    "configurations": [

        {
            "type": "node",
            "request": "attach",
            "protocol": "inspector",
            "name": "Attach by Process ID",
            "processId": "${command:PickProcess}"
        },
        {
            "type": "node",
            "request": "attach",
            "protocol": "inspector",
            "name": "Attach",
            "port": 9229
        },
        {
            "type": "node",
            "request": "launch",
            "port":9230,
            "name": "Launch Program",
            "program": "${workspaceFolder}\\bin\\www"
        }
    ]
}
</code>```

I am trying to debug with VS Code but got hit by the error as below. Am I configuring my launch.json correctly ?

答: Delete launch.json file and go to debug and create new launch.json file</p>

Body:
I was trying to launch the program from the debug console in VS Code but got the error on cannot connect to runtime process timeout after 10000 ms

launch.json

   "version": "0.2.0",
    "configurations": [

        {
            "type": "node",
            "request": "attach",
            "protocol": "inspector",
            "name": "Attach by Process ID",
            "processId": "${command:PickProcess}"
        },
        {
            "type": "node",
            "request": "attach",
            "protocol": "inspector",
            "name": "Attach",
            "port": 9229
        },
        {
            "type": "node",
            "request": "launch",
            "port":9230,
            "name": "Launch Program",
            "program": "${workspaceFolder}\\bin\\www"
        }
    ]
}

I am trying to debug with VS Code but got hit by the error as below. Am I configuring my launch.json correctly ?


问:
Error: `data` and `reference` should be factors with the same levels. Confusion matrix for Logistic Regression
I have seen lots of answers with regards to this particular error. I haven't found any answer to it with specifics to my particular issue. Therefore, my problem

This is what I do:

```<code>    shortness_breath_data <- data_categ_nosev %>%
dplyr::select(shortness_breath, obesity, asthma, diabetes_type_one, diabetes_type_two, obesity, hypertension, heart_disease, lung_condition, liver_disease, kidney_disease, Covid_tested, Gender)
</code>```

And this is put(head(shortness_breath_data)):

```<code>structure(list(shortness_breath = structure(c(1L, 2L, 1L, 1L,
1L, 2L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(1L,
1L, 2L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    asthma = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    diabetes_type_two = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), hypertension = structure(c(1L,
    1L, 1L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), lung_condition = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), kidney_disease = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative",
    "positive"), class = "factor"), Gender = structure(c(2L,
    1L, 2L, 1L, 1L, 2L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), problems = structure(list(row = c(2910L,
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double",
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))
</code>```

And I divide this into training and testing dataset.

```<code>shortness_breath_data$shortness_breath <- as.factor(shortness_breath_data$shortness_breath)

n <- nrow(shortness_breath_data)
set.seed(22)
trainingdx <- sample(1:n, 0.7 * n)

train <- shortness_breath_data[trainingdx,]
validate <- shortness_breath_data[-trainingdx,]

train %>% distinct(shortness_breath)
validate %>% distinct(shortness_breath)
</code>```

And just to do the same in case it will ease you job in finding the issue, I provided dput(head(train)) and dput(head(validate))

train dataset:

```<code>structure(list(shortness_breath = structure(c(1L, 1L, 1L, 1L,
1L, 1L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(2L,
1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    asthma = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    diabetes_type_two = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), hypertension = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), lung_condition = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), kidney_disease = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative",
    "positive"), class = "factor"), Gender = structure(c(1L,
    1L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), problems = structure(list(row = c(2910L,
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double",
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))
</code>```

validate dataset:

```<code>structure(list(shortness_breath = structure(c(1L, 2L, 2L, 1L,
1L, 1L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    asthma = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    diabetes_type_two = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), hypertension = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), lung_condition = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), kidney_disease = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative",
    "positive"), class = "factor"), Gender = structure(c(2L,
    1L, 2L, 2L, 1L, 1L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), problems = structure(list(row = c(2910L,
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double",
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))
</code>```

And then, I build my logistic regression model with stepwise, forward method.

```<code>null_model <- glm(shortness_breath ~ 1, data = train, family = "binomial")

fm_shortness_breath <- glm(shortness_breath ~., data = train, family = "binomial")

stepmodel <- step(null_model, scope = list(lower = null_model, upper = fm_shortness_breath), direction = "forward")
</code>```

Then I get my summary model and store the predictions in the source data frame.

```<code>summary(stepmodel)

validate$pred <- predict(stepmodel, validate, type = "response")

validate$real <- validate$shortness_breath

train$pred <- predict(stepmodel, train, type = "response")
train$real <- train$shortness_breath
</code>```

Then I plot my ROC curve with no problem:

```<code>plot.roc(validate$real, validate$pred, col = "red", main = "ROC Validation Set", percent = TRUE, print.auc = TRUE)
</code>```

Yet, when I am trying to get my confusion matrix, this is where I get my error. But this is my code:

```<code>cm_stepmodel <- confusionMatrix(stepmodel, validate)
</code>```

And then, the error comes in:

```<code>Error: `data` and `reference` should be factors with the same levels.
</code>```

With Show Traceback:

```<code>3.
stop("`data` and `reference` should be factors with the same levels.", call. = FALSE)
2.
confusionMatrix.default(stepmodel, validate)
1.
confusionMatrix(stepmodel, validate)
</code>```

I simply do not see the problem. And tried several other options but did not work. I have reproduced, step by step the exact approach I am undertaking. And I do not get my answer. Also, I have tag this issue with RMarkdown as well, alongside caret and R, just in case.

Also, libraries used are:

```<code>library(tidyverse)
library(conflicted)
library(tidymodels)
library(ggrepel)
library(corrplot)
library(dplyr)
library(corrr)
library(themis)
library(rsample)
library(caret)
library(forcats)
library(rcompanion)
library(MASS)
library(pROC)
library(ROCR)
library(data.table)
</code>```

答:
Try to convert your predicted probabilities to labels, and then run your confusionMatrix on this:

```<code>validate$pred <- predict(stepmodel, validate, type = "response")
validate$pred_label <- as.factor(ifelse(validate$pred >= 0.5, "Yes", "No"))
confusionMatrix(validate$real, validate$pred) # Error
confusionMatrix(validate$real, validate$pred_label) # This will work
</code>```

Check that you are correctly assigning labels as in your original dataset in the validate$pred_label statement.

I'm not particularly familiar with confusionMatrix, but the general idea is that you make predictions of labels and compare to the actual labels of your data. It threw an error because you were comparing labels with probabilities -- you needed to assign the labels. Please correct me if I made a conceptual error or coding mistake above.

Body:
I have seen lots of answers with regards to this particular error. I haven't found any answer to it with specifics to my particular issue. Therefore, my problem

This is what I do:

    shortness_breath_data <- data_categ_nosev %>%
dplyr::select(shortness_breath, obesity, asthma, diabetes_type_one, diabetes_type_two, obesity, hypertension, heart_disease, lung_condition, liver_disease, kidney_disease, Covid_tested, Gender)

And this is put(head(shortness_breath_data)):

structure(list(shortness_breath = structure(c(1L, 2L, 1L, 1L,
1L, 2L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(1L,
1L, 2L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    asthma = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    diabetes_type_two = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), hypertension = structure(c(1L,
    1L, 1L, 2L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), lung_condition = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), kidney_disease = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative",
    "positive"), class = "factor"), Gender = structure(c(2L,
    1L, 2L, 1L, 1L, 2L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), problems = structure(list(row = c(2910L,
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double",
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))

And I divide this into training and testing dataset.

shortness_breath_data$shortness_breath <- as.factor(shortness_breath_data$shortness_breath)

n <- nrow(shortness_breath_data)
set.seed(22)
trainingdx <- sample(1:n, 0.7 * n)

train <- shortness_breath_data[trainingdx,]
validate <- shortness_breath_data[-trainingdx,]

train %>% distinct(shortness_breath)
validate %>% distinct(shortness_breath)

And just to do the same in case it will ease you job in finding the issue, I provided dput(head(train)) and dput(head(validate))

train dataset:

structure(list(shortness_breath = structure(c(1L, 1L, 1L, 1L,
1L, 1L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(2L,
1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    asthma = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    diabetes_type_two = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), hypertension = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), lung_condition = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), kidney_disease = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative",
    "positive"), class = "factor"), Gender = structure(c(1L,
    1L, 1L, 2L, 1L, 2L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), problems = structure(list(row = c(2910L,
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double",
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))

validate dataset:

structure(list(shortness_breath = structure(c(1L, 2L, 2L, 1L,
1L, 1L), .Label = c("No", "Yes"), class = "factor"), obesity = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    asthma = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), diabetes_type_one = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    diabetes_type_two = structure(c(2L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), hypertension = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    heart_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), lung_condition = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    liver_disease = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("No",
    "Yes"), class = "factor"), kidney_disease = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("No", "Yes"), class = "factor"),
    Covid_tested = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("negative",
    "positive"), class = "factor"), Gender = structure(c(2L,
    1L, 2L, 2L, 1L, 1L), .Label = c("Female", "Male", "Other"
    ), class = "factor")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"), problems = structure(list(row = c(2910L,
35958L), col = c("how_unwell", "how_unwell"), expected = c("a double",
"a double"), actual = c("How Unwell", "How Unwell"), file = c("'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'",
"'/Users/gabrielburcea/Rprojects/data/data_lev_categorical_no_sev.csv'"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
)))

And then, I build my logistic regression model with stepwise, forward method.

null_model <- glm(shortness_breath ~ 1, data = train, family = "binomial")

fm_shortness_breath <- glm(shortness_breath ~., data = train, family = "binomial")

stepmodel <- step(null_model, scope = list(lower = null_model, upper = fm_shortness_breath), direction = "forward")

Then I get my summary model and store the predictions in the source data frame.

summary(stepmodel)

validate$pred <- predict(stepmodel, validate, type = "response")

validate$real <- validate$shortness_breath

train$pred <- predict(stepmodel, train, type = "response")
train$real <- train$shortness_breath

Then I plot my ROC curve with no problem:

plot.roc(validate$real, validate$pred, col = "red", main = "ROC Validation Set", percent = TRUE, print.auc = TRUE)

Yet, when I am trying to get my confusion matrix, this is where I get my error. But this is my code:

cm_stepmodel <- confusionMatrix(stepmodel, validate)

And then, the error comes in:

Error: `data` and `reference` should be factors with the same levels.

With Show Traceback:

3.
stop("`data` and `reference` should be factors with the same levels.", call. = FALSE)
2.
confusionMatrix.default(stepmodel, validate)
1.
confusionMatrix(stepmodel, validate)

I simply do not see the problem. And tried several other options but did not work. I have reproduced, step by step the exact approach I am undertaking. And I do not get my answer. Also, I have tag this issue with RMarkdown as well, alongside caret and R, just in case.

Also, libraries used are:

library(tidyverse)
library(conflicted)
library(tidymodels)
library(ggrepel)
library(corrplot)
library(dplyr)
library(corrr)
library(themis)
library(rsample)
library(caret)
library(forcats)
library(rcompanion)
library(MASS)
library(pROC)
library(ROCR)
library(data.table)

Body:
Try to convert your predicted probabilities to labels, and then run your confusionMatrix on this:

validate$pred <- predict(stepmodel, validate, type = "response")
validate$pred_label <- as.factor(ifelse(validate$pred >= 0.5, "Yes", "No"))
confusionMatrix(validate$real, validate$pred) # Error
confusionMatrix(validate$real, validate$pred_label) # This will work

Check that you are correctly assigning labels as in your original dataset in the validate$pred_label statement.

I'm not particularly familiar with confusionMatrix, but the general idea is that you make predictions of labels and compare to the actual labels of your data. It threw an error because you were comparing labels with probabilities -- you needed to assign the labels. Please correct me if I made a conceptual error or coding mistake above.


问:
Comparison of mongodb with table-based db
I try to understand which problems are better to solve with mongodb. Maybe someone can provide link to some article about where it's better to use mongodb and where it's better to use table-based DBs.

thank you in advance!

答:
MongoDB has a short document here.

There is also a list of production deployments. That should provide some ideas of who is using MongODB.


问:
Multiple keys with WPF KeyDown event
I'm working with WPF KeyDown event (KeyEventArgs from Windows.Input). I need to recognize when user pressed F1 alone and Ctrl+F1.

```<code>   private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key==Key.F1 && Keyboard.IsKeyDown(Key.LeftCtrl))
        {
            MessageBox.Show("ctrlF1");
        }
        if (e.Key == Key.F1 && !Keyboard.IsKeyDown(Key.LeftCtrl))
        {
            MessageBox.Show("F1");
        }
    }
</code>```

My problem is that when I press Ctrl+F1  plain F1 messagebox would fire too. I tried to add e.Handled to Ctrl+F1 case, but it doesn't help.

答:
check Key.F1 first, and if it pressed, then Key.LeftCtrl:</p>

```<code>private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.F1)
    {
        MessageBox.Show(Keyboard.IsKeyDown(Key.LeftCtrl) ? "Ctrl-F1" : "F1");
    }
}
</code>```

Title: Multiple keys with WPF KeyDown event

Body:
I'm working with WPF KeyDown event (KeyEventArgs from Windows.Input). I need to recognize when user pressed F1 alone and Ctrl+F1.

   private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key==Key.F1 && Keyboard.IsKeyDown(Key.LeftCtrl))
        {
            MessageBox.Show("ctrlF1");
        }
        if (e.Key == Key.F1 && !Keyboard.IsKeyDown(Key.LeftCtrl))
        {
            MessageBox.Show("F1");
        }
    }

My problem is that when I press Ctrl+F1  plain F1 messagebox would fire too. I tried to add e.Handled to Ctrl+F1 case, but it doesn't help.

Body:
check Key.F1 first, and if it pressed, then Key.LeftCtrl:

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.F1)
    {
        MessageBox.Show(Keyboard.IsKeyDown(Key.LeftCtrl) ? "Ctrl-F1" : "F1");
    }
}


问:
Uploading a file using the Google Drive API v3 and php via html form
I'm working on a program that would allow users to select a file using a HTML form, and then the  program would upload said file to Google Drive and share it with a certain other user. I've been able to create a file in Google Drive and then share it; but once I tried uploading a file it all went downhill.

It's odd, because I think the code to upload the file is correct, so the issue must lie in how i get the file from the HTML form to the PHP file. My suspicion has sort of been confirmed by the fact that I attempt to echo $_FILES['myfile']['name'] nothing happens.

I'll upload two code snippets below, but I'll omit all the Google Drive api authentication for brevity's sake because that works.

index.php

```<code>      <form action="../Next.php" method="POST" enctype="multipart/form-data">
    <section class="file">
      <span>Please select the file to be uploaded </span>
      <br>
      <label for="myfile">Select a file:</label>
      <input type="file"  name="myfile" required  >
     </section>
    <section class="submission">
      <input type="submit" value="Submit">
    </section>
  </form>
</code>```

Next.php

```<code>    $myfile=$_FILES['myfile']['tmp_name'];
    $type=mime_content_type($myfile);
    $drive = new Google_Service_Drive($client);
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle('Test');
    $file->setDescription('Test');
    $file->setMimeType($type);
    $data = file_get_contents($myfile);
    $uploadedFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => $type,
     ));
</code>```

Please remember I have omitted the authentication code because I know that works.

I can't understand why this does nothing, from what I've been able to gather from looking around the internet the code is correct. I think the issue might have to do with the $_FILES['myfile'] array, and yet from all the documentation online it seems to be correct as well.

答:
if still not resolved then...
As you mentioned $_FILES is empty then i suggest to look at the file location in your project.
suppose your index.php is in PROJECT->HOME->index.php directory then your Next.php should be in PROJECT->Next.php directory.

Also you have to give submit a name=submit.

in Next.php test either form is set or not

if(isset($_POST['submit'])){
 print_r($_FILES['myfile']);
}

And if file is not being uploaded let me know the issue.

Body:
I'm working on a program that would allow users to select a file using a HTML form, and then the  program would upload said file to Google Drive and share it with a certain other user. I've been able to create a file in Google Drive and then share it; but once I tried uploading a file it all went downhill.

It's odd, because I think the code to upload the file is correct, so the issue must lie in how i get the file from the HTML form to the PHP file. My suspicion has sort of been confirmed by the fact that I attempt to echo $_FILES['myfile']['name'] nothing happens.

I'll upload two code snippets below, but I'll omit all the Google Drive api authentication for brevity's sake because that works.

index.php

      <form action="../Next.php" method="POST" enctype="multipart/form-data">

      Please select the file to be uploaded

      Select a file:
      <input type="file"  name="myfile" required  >

      <input type="submit" value="Submit">

  </form>

Next.php

    $myfile=$_FILES['myfile']['tmp_name'];
    $type=mime_content_type($myfile);
    $drive = new Google_Service_Drive($client);
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle('Test');
    $file->setDescription('Test');
    $file->setMimeType($type);
    $data = file_get_contents($myfile);
    $uploadedFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => $type,
     ));

Please remember I have omitted the authentication code because I know that works.

I can't understand why this does nothing, from what I've been able to gather from looking around the internet the code is correct. I think the issue might have to do with the $_FILES['myfile'] array, and yet from all the documentation online it seems to be correct as well.


问:
Java Script Date Function
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.</p>

```<code>function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}
</code>```

答: Everything was ok. You were missing parentheses in the function declaration. Instead of function abc{...} you should use function abc(){...}. And to display it you can call the function in the console.log(abc())

Title: Java Script Date Function

Body:
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.

function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}


问:
Removing brackets in filenames using Python across different file extensions
I have a few text, pdf, and doc files that have brackets and I wish to remove them in the file names.

For eg. [Alpha].txt --> Alpha.txt

The below code works, but it only works on specifically one file extension. Is there a way to include .pdf and .doc files within the same code?

```<code>import os, fnmatch

#Set directory of locataion; include double slash for each subfolder.
file_path = "C:\\Users\\Mr.Slowbro\\Desktop\\Source Files\\"

#Set file extension accordingly
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.txt')

for file_name in files_to_rename:
    file_name_new = file_name.replace('[', '')
    os.rename(file_path + file_name, file_path + file_name_new)
    os.rename(file_path + file_name_new, file_path + file_name_new.replace(']', ''))
</code>```

答:
Use . instead of *.txt

```<code>files_to_rename = fnmatch.filter(os.listdir(file_path), '*.*')
</code>```

Body:
I have a few text, pdf, and doc files that have brackets and I wish to remove them in the file names.

For eg. [Alpha].txt --> Alpha.txt

The below code works, but it only works on specifically one file extension. Is there a way to include .pdf and .doc files within the same code?

import os, fnmatch

#Set directory of locataion; include double slash for each subfolder.
file_path = "C:\\Users\\Mr.Slowbro\\Desktop\\Source Files\\"

#Set file extension accordingly
files_to_rename = fnmatch.filter(os.listdir(file_path), '*.txt')

for file_name in files_to_rename:
    file_name_new = file_name.replace('[', '')
    os.rename(file_path + file_name, file_path + file_name_new)
    os.rename(file_path + file_name_new, file_path + file_name_new.replace(']', ''))

Body:
Use . instead of *.txt

files_to_rename = fnmatch.filter(os.listdir(file_path), '*.*')


问:
ES6: self-import vs ordering exports for referencing
I have a single file that has utils methods. Each is exported individually. I am in a situation where one util requires another. I currently define the functions used before they're used. But I came across ES6's cyclic dependency and using that removes the need to meticulously organize the util functions. Is there any reason I should not use that?

Simplified eg:
Currently:

```<code>  export const safeParsing = (str) =>  {
    try { return JSON.parse(str); }
    catch (e) { return {}; }
  };

  export const parseToken = (t) => safeParsing(t);
</code>```

Using cyclic dep:

```<code>import * as self from 'src/jsUtils';

export const parseToken = (t) => self.safeParsing(t);
export const safeParsing = (str) => {...}

</code>```

Edit: Using cyclic imports also enables me to spyOn (Jest) inner functions.
Eg:

```<code> test('parseToken uses safe parsing', () => { ... spyOn safeParsing ... });
</code>```

Relevant refs:

ES6 modules: Export single class of static methods OR multiple individual methods

https://stackoverflow.com/a/40242291/958598

https://stackoverflow.com/a/35225936/958598

https://stackoverflow.com/a/55193363/958598

答:
If you define them as ordinary functions with function safeParsing() { ... } rather than assigning them to a const variable, then ordering no longer matters because all function definitions are hoisted to the top of the scope. So, you can use all functions in any order. If you do const safeParsing = ... then you have to very carefully order the declarations because they can't be used until after they are assigned. This is one of the reasons I use the regular named function declarations rather than function expressions (like you show).

And, you can still do export function safeParsing() {...}. Just make your definitions be function declarations, not function expressions.

Body:
I have a single file that has utils methods. Each is exported individually. I am in a situation where one util requires another. I currently define the functions used before they're used. But I came across ES6's cyclic dependency and using that removes the need to meticulously organize the util functions. Is there any reason I should not use that?

Simplified eg:
Currently:

  export const safeParsing = (str) =>  {
    try { return JSON.parse(str); }
    catch (e) { return {}; }
  };

  export const parseToken = (t) => safeParsing(t);

Using cyclic dep:

import * as self from 'src/jsUtils';

export const parseToken = (t) => self.safeParsing(t);
export const safeParsing = (str) => {...}

Edit: Using cyclic imports also enables me to spyOn (Jest) inner functions.
Eg:

 test('parseToken uses safe parsing', () => { ... spyOn safeParsing ... });

Relevant refs:

ES6 modules: Export single class of static methods OR multiple individual methods

https://stackoverflow.com/a/40242291/958598

https://stackoverflow.com/a/35225936/958598

https://stackoverflow.com/a/55193363/958598


问:
ffmpeg duplicates image overlay (place it twice to the output)
I need gif overlay (equaliser line) on png background and mix it with audio to video output.

Last problem is, that gif overlay is placed twice to the output video. One on 0:0 coordinates and second on 50:262 which is specified in the 1 overlay.
Similary as attached

ffmpeg -i "audio.mp3" -ignore_loop 0 -i "anim-eq.gif" -loop 1 -i "bg.png" -filter_complex "[2]scale=w=1080:h=608,overlay=0:0[vt]; [1]scale=w=350:h=84,[vt]overlay=50:262" -c:a aac -ab 64k -ac 2 -ar 44100 -c:v libx264 -shortest "output.mp4"

Thank you for help.

答:
You have set two overlay filters. There should be only one.</p>

```<code>-filter_complex "[2]scale=w=1080:h=608[vt];[1]scale=w=350:h=84[eq];[vt][eq]overlay=50:262"
</code>```

Body:
You have set two overlay filters. There should be only one.

-filter_complex "[2]scale=w=1080:h=608[vt];[1]scale=w=350:h=84[eq];[vt][eq]overlay=50:262"


问:
Ionic5 provider with local storage and remote sync
I am thinking to implement a data provider that would store a copy of backend data locally for it to be available readily. Guess this would be called mirroring or so.

However, it needs to be synced / updated to remain consistent with the backend.

I'm thinking of a provider with a data model copy such as either local storage for persistence or a singleton object if it's only for mirroring during runtime.

What are exiting solutions in the ionic / angular library for this?
Please note, we have a custom backend, no firebase or similar solutions.

答:
Ionic and Angular do not provide standard functionality for this. It is outside the scope of these frameworks.

You could create a service that caches the data and periodically goes to the server to refresh the data. You can also do it more generally with an interceptor. The Angular guide has an example.

You could also use a service worker to achieve this. Angular has some support for this.

If you do not change the data locally (in the app) and data is only changed remotely (on the server) this is relatively straightforward. If you change data on both sides, this can be difficult to implement, because you can get synchronization conflicts.

If you have a lot of data, and it needs to be persistent, it is probably better to use IndexedDB for storage.


问:
How to call a function from another file in Flutter?
I am new to dart and am trying to call a function from my auth.dart file in my sign in page I tried many solutions but it did'nt work out, so any NEW Ideas?
This is my auth file:</p>

```<code>abstract class BaseAuth{
  Future<FirebaseUser> currentUser();
  Future<String> signIn(String email, String password);
  Future<String> createUser(String email, String password);
  Future<void> signOut();
  Future<String> getEmail();
  Future<bool> isEmailVerified();
  Future<void> resetPassword(String email);
  Future<void> sendEmailVerification();
}
class Auth implements BaseAuth{
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  Future<String> signIn(String email, String password) async {
    FirebaseUser user = (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)) as FirebaseUser;
    return user.uid;
  }
  Future<String> createUser(String email, String password) async {
    FirebaseUser user = (await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password)) as FirebaseUser;
    return user.uid;
  }
  Future<FirebaseUser> currentUser() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    print("uid ${user.uid}");
    return user;
  }
  Future<String> getEmail() async{
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.email;
  }
  Future<void> signOut() async {
    return _firebaseAuth.signOut();
  }
  Future<bool> isEmailVerified() async{
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.isEmailVerified;
  }
  Future<void> resetPassword(String email) async{
    return _firebaseAuth.sendPasswordResetEmail(email: email);
  }
  Future<void> sendEmailVerification() async{
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.sendEmailVerification();
  }
}
</code>```

答:
first you need to import the file. Do this at the very top of your file. You need to provide the path to the file from the current file location. So if current file is in /lib and the new file is in /lib/widgets your path is "widgets/new.dart". You can go up a folder like this "../new.dart"

```<code>import 'new.dart';
</code>```

Then instantiate an object of your class and use that object to call functions.

```<code>New x = New();
x.getFromOtherFile();
</code>```

"New" is my class name in this example.

Body:
I am new to dart and am trying to call a function from my auth.dart file in my sign in page I tried many solutions but it did'nt work out, so any NEW Ideas?
This is my auth file:

abstract class BaseAuth{
  Future<FirebaseUser> currentUser();
  Future<String> signIn(String email, String password);
  Future<String> createUser(String email, String password);
  Future<void> signOut();
  Future<String> getEmail();
  Future<bool> isEmailVerified();
  Future<void> resetPassword(String email);
  Future<void> sendEmailVerification();
}
class Auth implements BaseAuth{
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  Future<String> signIn(String email, String password) async {
    FirebaseUser user = (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)) as FirebaseUser;
    return user.uid;
  }
  Future<String> createUser(String email, String password) async {
    FirebaseUser user = (await _firebaseAuth.createUserWithEmailAndPassword(email: email, password: password)) as FirebaseUser;
    return user.uid;
  }
  Future<FirebaseUser> currentUser() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    print("uid ${user.uid}");
    return user;
  }
  Future<String> getEmail() async{
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.email;
  }
  Future<void> signOut() async {
    return _firebaseAuth.signOut();
  }
  Future<bool> isEmailVerified() async{
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.isEmailVerified;
  }
  Future<void> resetPassword(String email) async{
    return _firebaseAuth.sendPasswordResetEmail(email: email);
  }
  Future<void> sendEmailVerification() async{
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.sendEmailVerification();
  }
}

Body:
first you need to import the file. Do this at the very top of your file. You need to provide the path to the file from the current file location. So if current file is in /lib and the new file is in /lib/widgets your path is "widgets/new.dart". You can go up a folder like this "../new.dart"

import 'new.dart';

Then instantiate an object of your class and use that object to call functions.

New x = New();
x.getFromOtherFile();

"New" is my class name in this example.


问:
Angular - Property ' ' does not exist on type ' '
I'm a beginner to angular and am taking an online course on edx. In one of the tutorial labs, I am learning how to use the HttpClient.

ngOnInit() {
   this.GitSearchService.gitSearch('angular').then( (response) => {
    alert("Total Libraries Found:" + response.total_count);
   }, (error) => {
    alert("Error: " + error.statusText)
   })
 }
 title = 'app is functional!';
}
```

It says total_count does not exist on type unknown, but in one of the imports, I have "total_count": number

答:
Problem is that the response variable doesn't have a type.

You can fix that in different ways, some cleaner, some less.

An unclean way, for example, would be to workaround the typing

```<code>alert("Total Libraries Found:" + response['total_count']);
</code>```

A more clean way would be to provide a type to the response

```<code>this.GitSearchService.gitSearch('angular')
  .then( (response : MyAwesomeType) => { your code } )
</code>```

in this case, MyAwesomeType is expected to be a type that has the property total_count

Body:
I'm a beginner to angular and am taking an online course on edx. In one of the tutorial labs, I am learning how to use the HttpClient.

ngOnInit() {
   this.GitSearchService.gitSearch('angular').then( (response) => {
    alert("Total Libraries Found:" + response.total_count);
   }, (error) => {
    alert("Error: " + error.statusText)
   })
 }
 title = 'app is functional!';
}

It says total_count does not exist on type unknown, but in one of the imports, I have "total_count": number

Body:
Problem is that the response variable doesn't have a type.

You can fix that in different ways, some cleaner, some less.

An unclean way, for example, would be to workaround the typing

alert("Total Libraries Found:" + response['total_count']);

A more clean way would be to provide a type to the response

this.GitSearchService.gitSearch('angular')
  .then( (response : MyAwesomeType) => { your code } )

in this case, MyAwesomeType is expected to be a type that has the property total_count


问:
How to draw vertical connector lines between icons in Flutter?
I have 3 ListTile widgets as shown below and I want to add vertical connection lines between icons but not sure how to do that. Can anyone help please? Thanks.

```<code>[Icon]   Order received
  |      2020-05-28 10:00 AM
  |
  |
[Icon]   On the way
  |      2020-05-29 10:00 AM
  |
  |
[Icon]   Delivered
         2020--05-29 11:00 AM
</code>```

Edit: source code is provided below. As described above I need to draw a line between icons of the ListTile widgets. Tried VerticalDivider but there is still a big gap between ListTile widgets.

```<code>
    import 'package:flutter/material.dart';
    import 'package:font_awesome_flutter/font_awesome_flutter.dart';
    import 'package:home_chefs/common_widgets/text_widget.dart';
    import 'package:home_chefs/constants/color_palette.dart';
    import 'package:home_chefs/constants/font_enum.dart';
    import 'package:home_chefs/constants/form_styleguides.dart';

    class OrderStatusWidget extends StatefulWidget {
      @override
      _OrderStatusWidgetState createState() => _OrderStatusWidgetState();
    }

    class _OrderStatusWidgetState extends State<OrderStatusWidget> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: ColorPalette.white,
          body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(top: 30.0, bottom: 30.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    TextWidget(
                      text: 'Order status',
                      fontFamily: FontFamily.BalooRegular.toShortString(),
                      fontSize: FormStyleGuides.textSizeMedium,
                    ),
                    TextWidget(
                      text: 'Invoice: 12828',
                      fontFamily: FontFamily.BalooRegular.toShortString(),
                      fontSize: FormStyleGuides.textSizeMedium,
                    ),
                    Container(
                        height: 100.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(8.0)),
                            image: DecorationImage(
                                fit: BoxFit.contain,
                                image: AssetImage(
                                  'assets/images/trending/pho_ha_noi.jpg',
                                ))))
                  ],
                ),
              ),
              Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    ListTile(
                      leading: FaIcon(
                        FontAwesomeIcons.book,
                        color: ColorPalette.persimmon,
                      ),
                      title: Text('Order received'),
                      subtitle: Text('30/05/2020 10.00 AM'),
                      //contentPadding: EdgeInsets.only(left: 20.0, bottom: 30.0),
                    ),
                    ListTile(
                      leading: FaIcon(
                        FontAwesomeIcons.truck,
                        color: ColorPalette.persimmon,
                      ),
                      title: Text('On the way'),
                      subtitle: Text('30/05/2020 10.00 AM'),
                      //contentPadding: EdgeInsets.only(left: 20.0, bottom: 30.0),
                    ),
                    ListTile(
                      leading: FaIcon(
                        FontAwesomeIcons.solidFlag,
                        color: ColorPalette.persimmon,
                      ),
                      title: Text('Delivered'),
                      subtitle: Text('30/05/2020 11.00 AM'),
                      //contentPadding: EdgeInsets.only(left: 20.0, bottom: 30.0),
                    ),
                  ],
                ),
              ),
              Container(
                width: 100.0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    RaisedButton(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(
                              FormStyleGuides.buttonBorderRadius),
                          side: BorderSide(color: ColorPalette.persimmon)),
                      color: ColorPalette.persimmon,
                      highlightColor: ColorPalette.persimmon,
                      onPressed: () {},
                      padding: EdgeInsets.fromLTRB(
                          FormStyleGuides.buttonPaddingLeft,
                          FormStyleGuides.buttonPaddingTop,
                          FormStyleGuides.buttonPaddingRight,
                          FormStyleGuides.buttonPaddingBottom),
                      child: TextWidget(
                        text: 'Confirm delivery',
                        color: ColorPalette.white,
                        fontSize: FormStyleGuides.textFormFieldLabelSize,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        );
      }
    }
</code>```

答:
If I understood your question correctly, you are looking for something like this:</p>

```<code>class IconLines62088774 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ItemContainer(),
        ItemContainer(),
        ItemContainer(),
      ],
    );
  }
}

class ItemContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                color: Colors.blue,
                height: 20,
                width: 1,
              ),
              Icon(Icons.message, color: Colors.grey,),
              Container(
                color: Colors.blue,
                height: 20,
                width: 1,
              ),
            ],
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(8),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('On the way'),
                  Text('01-07-2020'),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
I have 3 ListTile widgets as shown below and I want to add vertical connection lines between icons but not sure how to do that. Can anyone help please? Thanks.

[Icon]   Order received
  |      2020-05-28 10:00 AM
  |
  |
[Icon]   On the way
  |      2020-05-29 10:00 AM
  |
  |
[Icon]   Delivered
         2020--05-29 11:00 AM

Edit: source code is provided below. As described above I need to draw a line between icons of the ListTile widgets. Tried VerticalDivider but there is still a big gap between ListTile widgets.

    import 'package:flutter/material.dart';
    import 'package:font_awesome_flutter/font_awesome_flutter.dart';
    import 'package:home_chefs/common_widgets/text_widget.dart';
    import 'package:home_chefs/constants/color_palette.dart';
    import 'package:home_chefs/constants/font_enum.dart';
    import 'package:home_chefs/constants/form_styleguides.dart';

    class OrderStatusWidget extends StatefulWidget {
      @override
      _OrderStatusWidgetState createState() => _OrderStatusWidgetState();
    }

    class _OrderStatusWidgetState extends State<OrderStatusWidget> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: ColorPalette.white,
          body: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(top: 30.0, bottom: 30.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    TextWidget(
                      text: 'Order status',
                      fontFamily: FontFamily.BalooRegular.toShortString(),
                      fontSize: FormStyleGuides.textSizeMedium,
                    ),
                    TextWidget(
                      text: 'Invoice: 12828',
                      fontFamily: FontFamily.BalooRegular.toShortString(),
                      fontSize: FormStyleGuides.textSizeMedium,
                    ),
                    Container(
                        height: 100.0,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(8.0)),
                            image: DecorationImage(
                                fit: BoxFit.contain,
                                image: AssetImage(
                                  'assets/images/trending/pho_ha_noi.jpg',
                                ))))
                  ],
                ),
              ),
              Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    ListTile(
                      leading: FaIcon(
                        FontAwesomeIcons.book,
                        color: ColorPalette.persimmon,
                      ),
                      title: Text('Order received'),
                      subtitle: Text('30/05/2020 10.00 AM'),
                      //contentPadding: EdgeInsets.only(left: 20.0, bottom: 30.0),
                    ),
                    ListTile(
                      leading: FaIcon(
                        FontAwesomeIcons.truck,
                        color: ColorPalette.persimmon,
                      ),
                      title: Text('On the way'),
                      subtitle: Text('30/05/2020 10.00 AM'),
                      //contentPadding: EdgeInsets.only(left: 20.0, bottom: 30.0),
                    ),
                    ListTile(
                      leading: FaIcon(
                        FontAwesomeIcons.solidFlag,
                        color: ColorPalette.persimmon,
                      ),
                      title: Text('Delivered'),
                      subtitle: Text('30/05/2020 11.00 AM'),
                      //contentPadding: EdgeInsets.only(left: 20.0, bottom: 30.0),
                    ),
                  ],
                ),
              ),
              Container(
                width: 100.0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    RaisedButton(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(
                              FormStyleGuides.buttonBorderRadius),
                          side: BorderSide(color: ColorPalette.persimmon)),
                      color: ColorPalette.persimmon,
                      highlightColor: ColorPalette.persimmon,
                      onPressed: () {},
                      padding: EdgeInsets.fromLTRB(
                          FormStyleGuides.buttonPaddingLeft,
                          FormStyleGuides.buttonPaddingTop,
                          FormStyleGuides.buttonPaddingRight,
                          FormStyleGuides.buttonPaddingBottom),
                      child: TextWidget(
                        text: 'Confirm delivery',
                        color: ColorPalette.white,
                        fontSize: FormStyleGuides.textFormFieldLabelSize,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        );
      }
    }

Body:
If I understood your question correctly, you are looking for something like this:

class IconLines62088774 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ItemContainer(),
        ItemContainer(),
        ItemContainer(),
      ],
    );
  }
}

class ItemContainer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                color: Colors.blue,
                height: 20,
                width: 1,
              ),
              Icon(Icons.message, color: Colors.grey,),
              Container(
                color: Colors.blue,
                height: 20,
                width: 1,
              ),
            ],
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.all(8),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('On the way'),
                  Text('01-07-2020'),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}


问:
What is the difference between callable HTTPS functions and HTTPS functions with param?
In HTTPS Callable function if the statement checks whether context.auth exist,
does it guarantee that the calling user is authenticated and is same as the context.auth.uid?

after reading this code  and this page i am getting mixed thoughts on how these functions work

In the code it uses a pram to get and check if the pram has the auth token.
In the second doc it uses just the context to get the auth token.

i am thinking the first code is old then the code in doc, can someone clear this?

答:
The first example is not a Callable Cloud Function, but rather a regular HTTP(S) Cloud Function/web hook. In the implementation of that example, it decodes the req.headers.authorization header and verifies its correctness with admin.auth().verifyIdToken(idToken). The client that calls this Cloud Function will need to ensure it passes a valid ID token in the authorization header.

The second example is a Callable Cloud Function. Here the Functions SDK on the client automatically passes the ID token, and the Functions SDK on the server automatically decodes and verified that token. So it's pretty much the same process that happened before, you just don't have to write the code for it yourself.


问:
Automatically tick checkbox when clicking on another form input field
I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

```<code><input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>
</code>```

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

答:
Simply add a listener to the text input that checks the box.

const checkbox = document.querySelector('#box');
const input = document.querySelector('input[type="text"]');

input.addEventListener('click', () => {
  checkbox.checked = true;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label></code>```

Body:
I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

<input type="checkbox" id="box">

  <input type="text">

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

Body:
Simply add a listener to the text input that checks the box.

const checkbox = document.querySelector('#box');
const input = document.querySelector('input[type="text"]');

input.addEventListener('click', () => {
  checkbox.checked = true;
});

<input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>


问:
How pass arguments via require to material avatar
```<code>import Avatar from '@material-ui/core/Avatar';
</code>```

This code works:

```<code><Avatar alt="user 4" src={require('Assets/img/user-1.jpg')} className="size-80 rounded-circle border-info rct-notify" />
</code>```

But I need to pass variable, this code doesn't work :

```<code>{line.icon != null && <Avatar alt="user 3" src={require(line.icon)} className="size-80 rounded-circle border-warning rct-notify" />}
</code>```

Error:

```<code>Uncaught Error: Cannot find module 'Assets/img/user-3.jpg'
</code>```

答:
I find some case how it works, but still not enough.

This code works only if in require we start from some text and after this, we can use a variable.

```<code>{line.icon != null && <Avatar alt="user 3" src={require(`Assets/img/${line.icon}`)} className="size-80 rounded-circle border-warning rct-notify" />}
</code>```

Body:
import Avatar from '@material-ui/core/Avatar';

This code works:

<Avatar alt="user 4" src={require('Assets/img/user-1.jpg')} className="size-80 rounded-circle border-info rct-notify" />

But I need to pass variable, this code doesn't work :

{line.icon != null && <Avatar alt="user 3" src={require(line.icon)} className="size-80 rounded-circle border-warning rct-notify" />}

Error:

Uncaught Error: Cannot find module 'Assets/img/user-3.jpg'

Body:
I find some case how it works, but still not enough.

This code works only if in require we start from some text and after this, we can use a variable.

{line.icon != null && <Avatar alt="user 3" src={require(`Assets/img/${line.icon}`)} className="size-80 rounded-circle border-warning rct-notify" />}