问:
WinMerge: How to compare files with the same content but different encodings?
Motivation:  I am rewriting a doc -- text files to be processed later. The new sources now use UTF-8. Large portions of the sources are the same. I need to find differences.

Details: The old doc sources use the cp1250 encoding, the new sources use the UTF-8. Both new and old sources use the same line endings (CR+LF). I am using the Unicode version of the WinMerge application (WinMergeU.exe), version 2.12.4.0.

It almost works, but... When the lines differ, they are initially marked as block by the dark yellow, and the different portions are marked using the lighter colour. When moving the red block cursor there, the panes below show the different part.

However, the block of text is marked by the dark yellow also in cases when (the Unicode representation of) the text is the same. The red block moves also to those portions of the files. In such case, the two panes below (that show the differences) containt the same text and nothing is marked as different. See the picture below:

The very first line differs -- this is OK. But the second line has visually the same content. The only character outside of the ASCII range is Ú there. It has a different representation in the encoded sources. This causes the line marked as different, but the panes below does not mark anyting at the line as different.

See also the following paragraphs that are exactly the same (only the encoding in the sources differ, the same line ending is used).

It looks as if the initial comparison were based on binary representation of the lines. Is there any setting to tell WinMerge that the comparison (I mean the block marking) should be based on Unicode content?

I tried hard, but no luck, yet.

Update: The above question was for the latest stable 2.12.4. The beta version 2.13.22 works just perfectly for me. See my answer below.

答:
Edit -> Options

Select 'Compare' from categories pane on left.

Check box 'Ignore carriage return differences' (UNIX, Windows, Mac)


来源: stackexchange

问:
I can't use UPDATE in MS Access but I can add rows to a database
The error I'm getting is that the row wasn't added because of protection violation reasons. The error is in Portuguese so is not exactly what is wrote there. Any help? thanks</p>

答: Try adding a timestamp field to the source database table.  Can't tell you how many times an update issue on a linked table has been fixed that way for me.  Also check that your source table has adequate keys set up to uniquely identify records.</p>

ContentLicense: CC BY-SA 3.0


问:
How many nodejs event loops works on pm2 cluster with few instances?
So, if I run "pm2 start app.js -i 3" how many nodejs event loops do I get?

I think about it because I heart that event loop eats a lot of resources from nodejs app.

答:
3 event loops for three separate nodejs instance.

If you think about browser, in general every tab has their own event-loop. But, it varies on the implementation of the browser. For example: chrome uses Process-per-site-instance which means, same site opened in multiple tab will be rendered by the same process.

ContentLicense: CC BY-SA 4.0


问:
No foreign_key related in validated_data in Django
Hi I want to POST into my Album using my AlbumSerializer. The problem is I don't receive the Artist name in the validated data inside the function create.

```<code>#models.py
class Artist(models.Model):
    name = models.CharField()
    ...

class Album(models.Model):
    name = models.CharField()
    artist = models.ForeignKey(Artist)

class Track(models.Model):
    album = models.ForeignKey(Album)
    title = models.CharField()

#serializers.py
class AlbumSerializer(serializers.ModelSerializer):
    artist = serializers.StringRelatedField()
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = '__all__'

    def create(self, validated_data):
        print(validated_data)
        ...
</code>```

I am passing in this data:

```<code>{
    "name": "Test",
    "artist": "Enimem",
    ...
}
</code>```

When I print the validated_data, the artist is not included. Is it because it is a foreign key? Then how will I add it to the validated_data?

```<code>{'name': 'Test', ...}
</code>```

I have tried adding the function to_interval_value, which resolved my problem, but I really don't want it added because it messes up the default ValidationErrors.

```<code>def to_interval_value(self, data):
    return data
</code>```

答:
The thing is that StringRelatedField uses the __str__ method as specified here and most importantly it's read only, so that's why.

You want to make it read-write since read_only means it will be used for display but ignored as an input when POSTing (see here https://www.django-rest-framework.org/api-guide/fields/#read_only).

I think you want to use read-write SlugRelatedField specifying slug_field='name' and queryset=Artist.objects.all():

artist = serializers.SlugRelatedField(slug_field='name', queryset=Artist.objects.all())
```

Look at the docs here for more info about this.

Note that the field should be unique.

Body:
Hi I want to POST into my Album using my AlbumSerializer. The problem is I don't receive the Artist name in the validated data inside the function create.

#models.py
class Artist(models.Model):
    name = models.CharField()
    ...

class Album(models.Model):
    name = models.CharField()
    artist = models.ForeignKey(Artist)

class Track(models.Model):
    album = models.ForeignKey(Album)
    title = models.CharField()

#serializers.py
class AlbumSerializer(serializers.ModelSerializer):
    artist = serializers.StringRelatedField()
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = '__all__'

    def create(self, validated_data):
        print(validated_data)
        ...

I am passing in this data:

{
    "name": "Test",
    "artist": "Enimem",
    ...
}

When I print the validated_data, the artist is not included. Is it because it is a foreign key? Then how will I add it to the validated_data?

{'name': 'Test', ...}

I have tried adding the function to_interval_value, which resolved my problem, but I really don't want it added because it messes up the default ValidationErrors.

def to_interval_value(self, data):
    return data

Body:
The thing is that StringRelatedField uses the __str__ method as specified here and most importantly it's read only, so that's why.

You want to make it read-write since read_only means it will be used for display but ignored as an input when POSTing (see here https://www.django-rest-framework.org/api-guide/fields/#read_only).

I think you want to use read-write SlugRelatedField specifying slug_field='name' and queryset=Artist.objects.all():

artist = serializers.SlugRelatedField(slug_field='name', queryset=Artist.objects.all())

Look at the docs here for more info about this.

Note that the field should be unique.


问:
Angular 6 - How to apply external css stylesheet (leaflet) at component level?
Trying to use Leaflet in an Angular 6 component. Depending on how the css file is linked, the map shows ok or is messed up, there are missing tiles not in the right order, which means the css is not taken into account.

I managed to make it work with 2 solutions linking the css to the application level (global), but never only to the component. Here's what I tried (in addition to reading several posts about css/leaflet/Angular):

Worked - global level:

```<code>// styles.css
@import url("assets/lib/leaflet/leaflet.css");
</code>```

Worked - global level:

```<code>// index.html
<link rel="stylesheet" href="./assets/lib/leaflet/leaflet.css" type="text/css">
</code>```

Did not work - global level:

```<code>// angular.json
"styles": [
    "src/styles.css",
    "src/assets/lib/leaflet/leaflet.css"
],
</code>```

Did not work - component level:

```<code>// ...

import * as L from "../assets/lib/leaflet/leaflet.js";
import "../assets/lib/leaflet/leaflet-bing-layer.js";
import { BingHelper } from "../assets/lib/bing/bing-helper.js";

// -> importing the .css file here does not work

@Component({
    templateUrl: "./map.component.html",
    selector: "app-map",
    styleUrls: ["../assets/lib/leaflet/leaflet.css"] // -> does not work

    // -> also tried to put the content of the .css in style: "", did not work neither

})
export class MapComponent implements AfterViewInit {
    ngAfterViewInit() {
        var map = L.map("map", {
            attributionControl: false,
            zoom: 8,
            minZoom: 3,
            maxZoom: 15,
            center: new L.LatLng(40.737, -73.923)
        });
        // ...
</code>```

Did not work: encapsulation - component level:
Load external CSS into component

Loading from CDN instead of local file does not change the issue.

Note: I am using a Bing layer extension, but this has no impact on this issue. I also had the same issue using Mapbox tiles instead.

Question: is there a way to link Leaflet css in a component and make it only available to the component, but not to the whole Angular application?

答:
Doing this

```<code>@import url("path")
</code>```

ex:

```<code>@import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css")
</code>```

or doig also

```<code>@import "bootstrap/dist/css/bootstrap.min.css"
</code>```

Body:
Trying to use Leaflet in an Angular 6 component. Depending on how the css file is linked, the map shows ok or is messed up, there are missing tiles not in the right order, which means the css is not taken into account.

I managed to make it work with 2 solutions linking the css to the application level (global), but never only to the component. Here's what I tried (in addition to reading several posts about css/leaflet/Angular):

Worked - global level:

// styles.css
@import url("assets/lib/leaflet/leaflet.css");

Worked - global level:

// index.html
<link rel="stylesheet" href="./assets/lib/leaflet/leaflet.css" type="text/css">

Did not work - global level:

// angular.json
"styles": [
    "src/styles.css",
    "src/assets/lib/leaflet/leaflet.css"
],

Did not work - component level:

// ...

import * as L from "../assets/lib/leaflet/leaflet.js";
import "../assets/lib/leaflet/leaflet-bing-layer.js";
import { BingHelper } from "../assets/lib/bing/bing-helper.js";

// -> importing the .css file here does not work

@Component({
    templateUrl: "./map.component.html",
    selector: "app-map",
    styleUrls: ["../assets/lib/leaflet/leaflet.css"] // -> does not work

    // -> also tried to put the content of the .css in style: "", did not work neither

})
export class MapComponent implements AfterViewInit {
    ngAfterViewInit() {
        var map = L.map("map", {
            attributionControl: false,
            zoom: 8,
            minZoom: 3,
            maxZoom: 15,
            center: new L.LatLng(40.737, -73.923)
        });
        // ...

Did not work: encapsulation - component level:
Load external CSS into component

Loading from CDN instead of local file does not change the issue.

Note: I am using a Bing layer extension, but this has no impact on this issue. I also had the same issue using Mapbox tiles instead.

Question: is there a way to link Leaflet css in a component and make it only available to the component, but not to the whole Angular application?

Body:
Doing this

@import url("path")

ex:

@import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css")

or doig also

@import "bootstrap/dist/css/bootstrap.min.css"


问:
Attempt to index field (nil value)
Whenever I try to use Body.pos, it always says that it is a nil value. But it is assigned a value in the new function, so it should not be nil.

My code:

```<code>Vector={
    x=nil,y=nil

    ,new=function (self,x,y)
        o={}
        setmetatable(o,self)
        self.__index=self

        o.x=x or 1
        o.y=y or 1

        return o
    end

    -- utility functions here
}

Body={
    pos=nil
    ,vel=nil
    ,acc=nil
    ,mass=nil

    ,new=function (self,pos,vel,acc,mass)
        o={}
        setmetatable(o,self)
        self.__index=self

        o.pos=pos or Vector:new()
        o.vel=vel or Vector:new()
        o.acc=acc or Vector:new()
        o.mass=mass or 1

        return o
    end

    ,applyForce=function (self,v)
        self.acc:add(v:scale(1/self.mass))
    end

    ,applyGravity=function (self)
        self.acc:add(GRAVITY_VECTOR)
    end

    ,step=function (self)
        self.vel:add(self.acc)
        self.pos:add(self.vel)

        self.acc:scale(0)
    end
}
</code>```

Trial code:

```<code>b=Body:new()
print(b.pos.x) -- shows error that pos is nil

</code>```

Vector:new() does not return nil, but still Body.pos is always nil. I don't know what I am doing wrong here.

EDIT: Added Vector implementation

答:
The issue is your OOP implementation. The metatable o needs to be set as a local variable.

In your code o is a global variable hence why you always reset it when you create a new object.

Vector={
    -- ...
    ,new=function (self,x,y)
        local o={}
        -- ...
    end
    -- ...
}

Body={
    -- ...
    ,new=function (self,pos,vel,acc,mass)
        local o={}
        -- ...
        return o
    end
    -- ...
}

b=Body:new()
print(b.pos.x) -- 1
```

Basically any variable that isn't declared as local is automatically put into the global scope.

Additionally I recommend using a linter (e.g. luacheck) to automatically detect issues like this.

Title: Attempt to index field (nil value)

Body:
Whenever I try to use Body.pos, it always says that it is a nil value. But it is assigned a value in the new function, so it should not be nil.

My code:

Vector={
    x=nil,y=nil

    ,new=function (self,x,y)
        o={}
        setmetatable(o,self)
        self.__index=self

        o.x=x or 1
        o.y=y or 1

        return o
    end

    -- utility functions here
}

Body={
    pos=nil
    ,vel=nil
    ,acc=nil
    ,mass=nil

    ,new=function (self,pos,vel,acc,mass)
        o={}
        setmetatable(o,self)
        self.__index=self

        o.pos=pos or Vector:new()
        o.vel=vel or Vector:new()
        o.acc=acc or Vector:new()
        o.mass=mass or 1

        return o
    end

    ,applyForce=function (self,v)
        self.acc:add(v:scale(1/self.mass))
    end

    ,applyGravity=function (self)
        self.acc:add(GRAVITY_VECTOR)
    end

    ,step=function (self)
        self.vel:add(self.acc)
        self.pos:add(self.vel)

        self.acc:scale(0)
    end
}

Trial code:

b=Body:new()
print(b.pos.x) -- shows error that pos is nil

Vector:new() does not return nil, but still Body.pos is always nil. I don't know what I am doing wrong here.

EDIT: Added Vector implementation

Body:
The issue is your OOP implementation. The metatable o needs to be set as a local variable.

In your code o is a global variable hence why you always reset it when you create a new object.

Vector={
    -- ...
    ,new=function (self,x,y)
        local o={}
        -- ...
    end
    -- ...
}

Body={
    -- ...
    ,new=function (self,pos,vel,acc,mass)
        local o={}
        -- ...
        return o
    end
    -- ...
}

b=Body:new()
print(b.pos.x) -- 1

Basically any variable that isn't declared as local is automatically put into the global scope.

Additionally I recommend using a linter (e.g. luacheck) to automatically detect issues like this.


问:
get selected text in an other application
I want to have a python script, which will "idle" until some text is selected in an other desktop app, and then store it in a var. Eg:

User goes into Safari

User selects a block of text

In the background, the python script will store that block of text in a var

Now that the python script has it's var, it can stop "idling" / "pausing" and continue

Think a clipboard, where you don't need to hit "Cmd+C"; all you do is select the text

Cheers!
This is for Mac OSX by the way

答:
Doing what you want would be hard to do properly, assuming it's possible at all.

For example, without requiring the user to press a key (eg: Cmd+C, Ctrl+C, etc)  how do you expect your application to know when they are done selecting? If I do a click, then shift-click to select a range, am I done? What if I shift-click again? How about if I do a double-click? Triple-click? How does your app know when I'm done making the selection?

Better to make the user explicitly copy the selection to the clipboard. You can fairly easily write an app that uses tkinter or wxpython to poll the clipboard and wait for it to change.


问:
Remove signature from outlook mail template executed from python
I have written a program which opens a .oft file from shared drive and puts desired email id in TO field and can edit the subject field as well.
But at the end when the mail gets Displayed, my default signature always get added. Now I am going to deploy this script to multiple users and the mail does not need to have a user's signature as the template already has a groups signature predefined.

I already search and found that there is no mail.Signature in Outlook by which it can be modified.

```<code>import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItemFromTemplate(r'\\Server\Share\Folder\maial.oft')
mail.To = 'someone@exapmle.com'
mail.Subject = 'Test'
mail.Display(True)
</code>```

Is there any way by which I can restrict outlook to add the default signature in the mail using python ?

答:
As the signature is part of the whole email body (.HTMLbody), I realised I can 'initialize' it with a blank and just 'come back' to it with the desired content. This is especially helpful if you are using .GetInspector which, by default, always includes the designated email signature for the active outlook user account.

So you can do:

```<code>mail.HTMLbody = ''
</code>```

and then

```<code>mail.HTMLbody = '<Insert desired content>' #This overwrites the previous one
</code>```

and/or paste something via .GetInspector like a Word Document content for example:

```<code>msg.GetInspector.WordEditor.Range(Start=0, End=0).Paste() #This seems to append, not overwrite
</code>```

For more about copying Word documents into Outlook, see this post.

-EDIT-

Since OP is using a template, it seems that the email signature is within the template itself (not being called by Outlook via .GetInspector --- which was my actual case), two possible solutions I can think of is to

Get rid of it by creating a copy without the sig, then send that modified copy into Outlook.

Continue using the template but specify the range (excluding the email sig) via .GetInspector

Body:
I have written a program which opens a .oft file from shared drive and puts desired email id in TO field and can edit the subject field as well.
But at the end when the mail gets Displayed, my default signature always get added. Now I am going to deploy this script to multiple users and the mail does not need to have a user's signature as the template already has a groups signature predefined.

I already search and found that there is no mail.Signature in Outlook by which it can be modified.

import win32com.client as win32

outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItemFromTemplate(r'\\Server\Share\Folder\maial.oft')
mail.To = 'someone@exapmle.com'
mail.Subject = 'Test'
mail.Display(True)

Is there any way by which I can restrict outlook to add the default signature in the mail using python ?

Body:
As the signature is part of the whole email body (.HTMLbody), I realised I can 'initialize' it with a blank and just 'come back' to it with the desired content. This is especially helpful if you are using .GetInspector which, by default, always includes the designated email signature for the active outlook user account.

So you can do:

mail.HTMLbody = ''

and then

mail.HTMLbody = '<Insert desired content>' #This overwrites the previous one

and/or paste something via .GetInspector like a Word Document content for example:

msg.GetInspector.WordEditor.Range(Start=0, End=0).Paste() #This seems to append, not overwrite

For more about copying Word documents into Outlook, see this post.

-EDIT-

Since OP is using a template, it seems that the email signature is within the template itself (not being called by Outlook via .GetInspector --- which was my actual case), two possible solutions I can think of is to

Get rid of it by creating a copy without the sig, then send that modified copy into Outlook.

Continue using the template but specify the range (excluding the email sig) via .GetInspector


问:
firefox - customize scroll bar
i have the following code that customizes a webkit scroll bar....

```<code>/*webkit scroll bar*/

::-webkit-scrollbar {
    width: 6px;
}

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    -webkit-border-radius: 10px;
    border-radius: 10px;
    background: rgba(255,0,0);
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
    background: rgba(255,0,0);
}
</code>```

what i would like to do is customize the scrollbar of a page loaded in firefox the same way... for which i tried the following code..

```<code>/*mozilla scroll bar*/

::-moz-scrollbar {
    width: 6px;
}

::-moz-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

::-moz-scrollbar-thumb {
    -webkit-border-radius: 10px;
    border-radius: 10px;
    background: rgba(255,0,0);
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-moz-scrollbar-thumb:window-inactive {
    background: rgba(255,0,0);
}
</code>```

but it does not work..... how can i customize the scrollbar in the same way i did for webkit... any help would be appreciated... thanks in advance... :)

答:
FireFox support these two:

scrollbar-width : auto|thin|none...

scrollbar-color

Title: firefox - customize scroll bar

Body:
i have the following code that customizes a webkit scroll bar....

/*webkit scroll bar*/

::-webkit-scrollbar {
    width: 6px;
}

::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    -webkit-border-radius: 10px;
    border-radius: 10px;
    background: rgba(255,0,0);
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
    background: rgba(255,0,0);
}

what i would like to do is customize the scrollbar of a page loaded in firefox the same way... for which i tried the following code..

/*mozilla scroll bar*/

::-moz-scrollbar {
    width: 6px;
}

::-moz-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

::-moz-scrollbar-thumb {
    -webkit-border-radius: 10px;
    border-radius: 10px;
    background: rgba(255,0,0);
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-moz-scrollbar-thumb:window-inactive {
    background: rgba(255,0,0);
}

but it does not work..... how can i customize the scrollbar in the same way i did for webkit... any help would be appreciated... thanks in advance... :)


问:
Convert object of objects to array
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

```<code>P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}
</code>```

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks

答:
You can use Object.keys() which will give an array with all the keys inside the object. You can get the objects from the main object object using those keys while using a loop

var obj={P3E051V:{
    lot: "P3E051V",
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V",
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V",
    quantite: 10800
}
}
Object.keys(obj).forEach(e=>console.log(obj[e]))```

Title: Convert object of objects to array

Body:
I work on a Angular Project and I have a little issue with an object..

I have an object with objects inside :

P3E051V:{
    lot: "P3E051V"
    quantite: 5400
},
P3E052V:{
    lot: "P3E052V"
    quantite: 5400
},
P3E054V:{
    lot: "P3E054V"
    quantite: 10800
}

What I would like to do is to display a table like this :
image of the table

But I can't loop on an object with *ngFor.
I tried to use Object.entries(myObject) but it doesn't work.

Anyone have an idea to solve this ?

Thanks


问:
Is there a way to create java objects from clojure maps?
is there a way to create java objects from Clojure maps? something where the following would hold - (= my-map (bean (convert-to-object my-map)))

答:
Take a look at https://github.com/uwcpdx/bean-dip

Bidirectional translation between Clojure maps and Java beans that's
  declarative and reflection-free


问:
AutoCompleteTextView force to show all items
There is a moment in my app, that I need to force to show all items in the suggestion list, no matter what the user has typed. How can I do that?

I tried to do something with filtering, but for me as a beginner filtering is just way too complicated, I tried searching beginners tutorial for filtering without any luck. Maybe, there is a simpler way to force to show all the suggestion items?

EDIT:
Basically what was my idea, is that, when user types something whats not in the list, it shows all the available options he can have.

I've found the best way of checking weather the ACTV is beign shown or not, but onTextChangeEvent I compare the user typed text with my list, and then if no elements have been found show full list.

```<code>public void onTextChanged(CharSequence s, int start, int before, int count)
         {
           final EditText editText = (EditText) findViewById(R.id.vardsUserInput);
            String strValue = editText.getText().toString().toUpperCase();
            String temp;
            int Cc=0; //my count variable
            for(int i=0; i<vardi.length; i++)
            {
                temp = vardi[i].toUpperCase();
                if(temp.startsWith(strValue.toUpperCase()))
                {
                    Log.d("testing",vardi[i]);
                    Cc++;
                }
            }
        if(Cc == 0)
        {
        //Show all the available options
    textView.showDropDown();
         }
}
</code>```

答:
To stop adapter from filtering you can set high enough treshold on your textview:

```<code>autoCompleteTextView.setThreshold(100);
</code>```

Hope it helps.

Body:
There is a moment in my app, that I need to force to show all items in the suggestion list, no matter what the user has typed. How can I do that?

I tried to do something with filtering, but for me as a beginner filtering is just way too complicated, I tried searching beginners tutorial for filtering without any luck. Maybe, there is a simpler way to force to show all the suggestion items?

EDIT:
Basically what was my idea, is that, when user types something whats not in the list, it shows all the available options he can have.

I've found the best way of checking weather the ACTV is beign shown or not, but onTextChangeEvent I compare the user typed text with my list, and then if no elements have been found show full list.

public void onTextChanged(CharSequence s, int start, int before, int count)
         {
           final EditText editText = (EditText) findViewById(R.id.vardsUserInput);
            String strValue = editText.getText().toString().toUpperCase();
            String temp;
            int Cc=0; //my count variable
            for(int i=0; i<vardi.length; i++)
            {
                temp = vardi[i].toUpperCase();
                if(temp.startsWith(strValue.toUpperCase()))
                {
                    Log.d("testing",vardi[i]);
                    Cc++;
                }
            }
        if(Cc == 0)
        {
        //Show all the available options
    textView.showDropDown();
         }
}

Body:
To stop adapter from filtering you can set high enough treshold on your textview:

autoCompleteTextView.setThreshold(100);

Hope it helps.


问:
Why the if statement is executed in ` if [ ''=1 ] ; then echo "true"; else echo "false"; fi`?
```<code>if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
fi
</code>```

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed.

Show  status of ''=1 in bash.

```<code>''=1
bash: =1: command not found
echo $?
127
</code>```

The value of status is 127, not zero. A strange statement:

```<code>if [ ''=1 ] ; then echo "true"; else echo "false"; fi
true
</code>```

Why value of status 127, not zero invoke then statement? Why can't get false in bash?

@Дмитрий Шатов

```<code>=1
bash: =1: command not found
echo $?
127
</code>```

答:
You need spaces

''=1 gets interpreted as a string =1 and test finds a non-empty string. If you want to compare '' to 1, write

```<code>[ '' = 1 ]
</code>```

Why status 127?

man bash

... If that function is not defined, the shell prints an error message and returns an exit status of 127.

Body:
if test-commands; then
  consequent-commands;
[elif more-test-commands; then
  more-consequents;]
[else alternate-consequents;]
fi

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed.

Show  status of ''=1 in bash.

''=1
bash: =1: command not found
echo $?
127

The value of status is 127, not zero. A strange statement:

if [ ''=1 ] ; then echo "true"; else echo "false"; fi
true

Why value of status 127, not zero invoke then statement? Why can't get false in bash?

@Дмитрий Шатов

=1
bash: =1: command not found
echo $?
127

Body:
You need spaces

''=1 gets interpreted as a string =1 and test finds a non-empty string. If you want to compare '' to 1, write

[ '' = 1 ]

Why status 127?

man bash

... If that function is not defined, the shell prints an error message and returns an exit status of 127.


问:
How can the neural net classify images with only one dense layer and RELU?
I am reading this Tensorflow tutorial about Fashion MNIST classification with tf.keras. Although it is an image classification problem, they train with only dense layer and softmax:

```<code>model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])
</code>```

I checked myself, it trains very fast and achieves a high accuracy. The question is how they do it without convolution at all, just matrix multiplication and RELU? I thought it could be done with at least one convolutional layer.

答:
Convolution are not mandatory when the task is not too complex (small and simple images).

Images are just a matrix of pixel that you can flatten and classify, but this method has its limits.

By flattening you'll loose all the spacial informations of the image, informations that can be really important.
That's why convolutional networks are better, they keep all those features.

To summarize : Fully connnected networks can achieve high accuracy quickly on simple tasks but will never perform as good as a convolutional network on images.

Body:
I am reading this Tensorflow tutorial about Fashion MNIST classification with tf.keras. Although it is an image classification problem, they train with only dense layer and softmax:

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])

I checked myself, it trains very fast and achieves a high accuracy. The question is how they do it without convolution at all, just matrix multiplication and RELU? I thought it could be done with at least one convolutional layer.


问:
how to read text file from POST with express-uploadfile?
I am trying to make node js server, for uploading text files there.

so I am using POST for get local user's text file, then I want to make server read the file.

I think I can make user upload he's local text file, I can get uploaded file's description.

but It is hard to make server read the file's actual string.
because I always get 'undefined' when I get try to read it by
logFile.data.toString('utf8');

Could you guide me how to read the uploaded text file's string?

Here is my tried code, Thank you.:

html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<h3>ENTER</h3>
<form action="/loadfile" method="post" enctype="multipart/form-data">
    <table>

        <tr>
            <td>file : </td>
            <td><input type="file" name="fileName"></td>
        </tr>
        <tr>
            <td><input type="submit" value="submit"></td>
        </tr>
    </table>
</form>

</body>
</html>

</code>```

logFile is a file from POST.
I think logFile.data returns the byte array of its text file contents,
so I tried to convert to String by toString('utf8') or toString().

This is node js server:

```<code>var fileupload = require("express-fileupload");
  app.use(fileupload());
  app.use(bodyParser.urlencoded({extended: false}));

           (fetching html... )

app.post('/loadfile', (req,res) =>{

      console.log("react to post action - loadFile");
      res.send("submit ok");
        var logFile = req.files;

        console.log(logFile);
        var buffer = logFile.data;
        console.log(buffer.toString('utf8'));

    });

</code>```

when I put "test.txt" files to this html, this is server's console reaction.

```<code>
2020-02-14T08:18:50.909771+00:00 app[web.1]: react to post action - loadFile
2020-02-14T08:18:50.912904+00:00 app[web.1]: {
2020-02-14T08:18:50.912905+00:00 app[web.1]: fileName: {
2020-02-14T08:18:50.912906+00:00 app[web.1]: name: 'test.txt',
2020-02-14T08:18:50.912907+00:00 app[web.1]: data: <Buffer 68 65 6c 6c 6f 20 74
68 69 73 20 69 73 20 74 65 73 74 20 74 65 78 74 20 66 69 6c 65>,
2020-02-14T08:18:50.912907+00:00 app[web.1]: size: 28,
2020-02-14T08:18:50.912908+00:00 app[web.1]: encoding: '7bit',
2020-02-14T08:18:50.912908+00:00 app[web.1]: tempFilePath: '',
2020-02-14T08:18:50.912912+00:00 app[web.1]: truncated: false,
2020-02-14T08:18:50.912912+00:00 app[web.1]: mimetype: 'text/plain',
2020-02-14T08:18:50.912913+00:00 app[web.1]: md5: 'f4e8dbc8c1fa4d01329d4f8260511
1d2',
2020-02-14T08:18:50.912913+00:00 app[web.1]: mv: [Function: mv]
2020-02-14T08:18:50.912914+00:00 app[web.1]: }

** I can see the uploaded file's information properly **

2020-02-14T08:18:50.912914+00:00 app[web.1]: }
2020-02-14T08:18:50.914538+00:00 app[web.1]: TypeError: Cannot read property 'to
String' of undefined
2020-02-14T08:18:50.914539+00:00 app[web.1]: at /app/server.js:111:28
2020-02-14T08:18:50.914540+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914540+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/route.js:137:13)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Route.dispatch (/app/node_module
s/express/lib/router/route.js:112:3)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at /app/node_modules/express/lib/ro
uter/index.js:281:22
2020-02-14T08:18:50.914542+00:00 app[web.1]: at Function.process_params (/app/no
de_modules/express/lib/router/index.js:335:12)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/index.js:275:10)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at urlencodedParser (/app/node_modu
les/body-parser/lib/types/urlencoded.js:100:7)
2020-02-14T08:18:50.914543+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)

**But read the file's actual string by 'toString()' is not possible, why??**

</code>```

答:
From the docs, you are supposed to access the upload file via req.files.[HTMLInput-name-attribute], you are missing out the HTMLInput-name-attribute in the route handler. Source. Try this:

```<code>app.post('/loadfile', (req, res) => {

  console.log("react to post action - loadFile");
  res.send("submit ok");
  // Notice the addition of the "fileName" key
  // It is the HTML name attribute value here in the input element:
  // <td><input type="file" name="fileName"></td>
  var logFile = req.files.fileName;

  console.log(logFile);
  var buffer = logFile.data;
  console.log(buffer.toString('utf8'));

});
</code>```

Body:
I am trying to make node js server, for uploading text files there.

so I am using POST for get local user's text file, then I want to make server read the file.

I think I can make user upload he's local text file, I can get uploaded file's description.

but It is hard to make server read the file's actual string.
because I always get 'undefined' when I get try to read it by
logFile.data.toString('utf8');

Could you guide me how to read the uploaded text file's string?

Here is my tried code, Thank you.:

html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

ENTER

<form action="/loadfile" method="post" enctype="multipart/form-data">

            file :
            <input type="file" name="fileName">

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

</form>

logFile is a file from POST.
I think logFile.data returns the byte array of its text file contents,
so I tried to convert to String by toString('utf8') or toString().

This is node js server:

var fileupload = require("express-fileupload");
  app.use(fileupload());
  app.use(bodyParser.urlencoded({extended: false}));

           (fetching html... )

app.post('/loadfile', (req,res) =>{

      console.log("react to post action - loadFile");
      res.send("submit ok");
        var logFile = req.files;

        console.log(logFile);
        var buffer = logFile.data;
        console.log(buffer.toString('utf8'));

    });

when I put "test.txt" files to this html, this is server's console reaction.

2020-02-14T08:18:50.909771+00:00 app[web.1]: react to post action - loadFile
2020-02-14T08:18:50.912904+00:00 app[web.1]: {
2020-02-14T08:18:50.912905+00:00 app[web.1]: fileName: {
2020-02-14T08:18:50.912906+00:00 app[web.1]: name: 'test.txt',
2020-02-14T08:18:50.912907+00:00 app[web.1]: data: <Buffer 68 65 6c 6c 6f 20 74
68 69 73 20 69 73 20 74 65 73 74 20 74 65 78 74 20 66 69 6c 65>,
2020-02-14T08:18:50.912907+00:00 app[web.1]: size: 28,
2020-02-14T08:18:50.912908+00:00 app[web.1]: encoding: '7bit',
2020-02-14T08:18:50.912908+00:00 app[web.1]: tempFilePath: '',
2020-02-14T08:18:50.912912+00:00 app[web.1]: truncated: false,
2020-02-14T08:18:50.912912+00:00 app[web.1]: mimetype: 'text/plain',
2020-02-14T08:18:50.912913+00:00 app[web.1]: md5: 'f4e8dbc8c1fa4d01329d4f8260511
1d2',
2020-02-14T08:18:50.912913+00:00 app[web.1]: mv: [Function: mv]
2020-02-14T08:18:50.912914+00:00 app[web.1]: }

** I can see the uploaded file's information properly **

2020-02-14T08:18:50.912914+00:00 app[web.1]: }
2020-02-14T08:18:50.914538+00:00 app[web.1]: TypeError: Cannot read property 'to
String' of undefined
2020-02-14T08:18:50.914539+00:00 app[web.1]: at /app/server.js:111:28
2020-02-14T08:18:50.914540+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914540+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/route.js:137:13)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Route.dispatch (/app/node_module
s/express/lib/router/route.js:112:3)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at /app/node_modules/express/lib/ro
uter/index.js:281:22
2020-02-14T08:18:50.914542+00:00 app[web.1]: at Function.process_params (/app/no
de_modules/express/lib/router/index.js:335:12)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/index.js:275:10)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at urlencodedParser (/app/node_modu
les/body-parser/lib/types/urlencoded.js:100:7)
2020-02-14T08:18:50.914543+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)

**But read the file's actual string by 'toString()' is not possible, why??**

Body:
From the docs, you are supposed to access the upload file via req.files.[HTMLInput-name-attribute], you are missing out the HTMLInput-name-attribute in the route handler. Source. Try this:

app.post('/loadfile', (req, res) => {

  console.log("react to post action - loadFile");
  res.send("submit ok");
  // Notice the addition of the "fileName" key
  // It is the HTML name attribute value here in the input element:
  // <td><input type="file" name="fileName"></td>
  var logFile = req.files.fileName;

  console.log(logFile);
  var buffer = logFile.data;
  console.log(buffer.toString('utf8'));

});


问:
How to apply unmerged upstream pull requests from other forks into my fork?
A project on GitHub that I have a fork of has a new pull requests that I want to pull into my fork that the author has not pulled in yet.

Is there a simple way to apply pull request from other forks into my fork? Is there something else here that I am missing?

答:
You can do it manually quite easily:

add the other fork as a remote of your repo:

```<code>git remote add otherfork git://github.com/request-author/project.git
</code>```

fetch his repo's commits

```<code>git fetch otherfork
</code>```

You have then  two options to apply the pull request (if you don't want to choose pick 1.)

If you don't care about applying also the eventual commits that have been added between the origin and the pull request, you can just rebase the branch on which the pull request was formed

```<code>git rebase master otherfork/pullrequest-branch
</code>```

If you only want the commits in the pull request, identify their SHA1 and do

```<code>git cherry-pick <first-SHA1> <second-SHA1> <etc.>
</code>```

Body:
You can do it manually quite easily:

add the other fork as a remote of your repo:

git remote add otherfork git://github.com/request-author/project.git

fetch his repo's commits

git fetch otherfork

You have then  two options to apply the pull request (if you don't want to choose pick 1.)

If you don't care about applying also the eventual commits that have been added between the origin and the pull request, you can just rebase the branch on which the pull request was formed

git rebase master otherfork/pullrequest-branch

If you only want the commits in the pull request, identify their SHA1 and do

git cherry-pick <first-SHA1> <second-SHA1> <etc.>


问:
TestCafe get version
I try to get the current installed version of TestCafe on my Node.js.
I tried:

```<code>    let testcafe = null;

    createTestCafe('localhost', 1337, 1338, void 0, true)
        .then(tc => {
            testcafe     = tc;
    .......
        })
        .then(() => {
            return runner
                .src([__basedir + '/tests/temp.js'])
                .browsers(myBrowser)
                .screenshots(screnshotpath, true)
                .reporter('allure')
                .run()
                .then(failedCount => {
                    console.log( "Testcafe Version" + testcafe.version);
                    testcafe.close();
    .......

</code>```

But this is undefined. Is there any other way possible?

答:
When used programmatically, it doesn't seem like Testcafe has an option to get the version like you might have when using the cli, with the -v option.

The easiest way I can think of is to import package.json:

```<code>const { version } = require('testcafe/package.json');
console.log("Testcafe Version " + version);
</code>```

Title: TestCafe get version

Body:
I try to get the current installed version of TestCafe on my Node.js.
I tried:

    let testcafe = null;

    createTestCafe('localhost', 1337, 1338, void 0, true)
        .then(tc => {
            testcafe     = tc;
    .......
        })
        .then(() => {
            return runner
                .src([__basedir + '/tests/temp.js'])
                .browsers(myBrowser)
                .screenshots(screnshotpath, true)
                .reporter('allure')
                .run()
                .then(failedCount => {
                    console.log( "Testcafe Version" + testcafe.version);
                    testcafe.close();
    .......

But this is undefined. Is there any other way possible?

Body:
When used programmatically, it doesn't seem like Testcafe has an option to get the version like you might have when using the cli, with the -v option.

The easiest way I can think of is to import package.json:

const { version } = require('testcafe/package.json');
console.log("Testcafe Version " + version);


问:
Jquery Client-Side Form Validation
I just found out that using Jquery for form submission also means I need to use Jquery for client-side validation as well. I have done some research and found the reportValidity() function which does everything I need it to do, but I am not clear on what the code does.

My question is on the [0] in $("#loginemail")[0]

$("#loginbutton").click(function() {
  if ($("#loginemail")[0].reportValidity()) {
    alert("login email is valid");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="email" placeholder="Email Address" id="loginemail" autofocus required><br>
<input type="email" placeholder="Email Address" id="loginemail" required><br>
<input type="button" value="Log In" id="loginbutton"></br></code>```

I read that when Jquery is told to use the selector, say for an id, it will find all instances of that id and make an array. The [#] is to clarify to Jquery which id to act upon. You can see that I have two email fields, each with the same id of 'loginemail'.

When the index is set to [0], filling in the first email box and clicking Log In results in a successful alert.

However, when the index is set to [1], this means Jquery should be acting on the 2nd email box. When I fill in the 2nd email box correctly, the alert does not show. Why is this?

答:
An ID must be unique in a document. Use a markup valitor to fix errors in your HTML.

The selectors API optimises searching for ID selectors by assuming your document is not invalid (and stopping after it finds a single match).

(It doesn't perform that optimisation for an ID attribute selector, but you should fix the HTML instead of hacking around the problem. Use a class instead.)

Title: Jquery Client-Side Form Validation

Body:
I just found out that using Jquery for form submission also means I need to use Jquery for client-side validation as well. I have done some research and found the reportValidity() function which does everything I need it to do, but I am not clear on what the code does.

My question is on the [0] in $("#loginemail")[0]

$("#loginbutton").click(function() {
  if ($("#loginemail")[0].reportValidity()) {
    alert("login email is valid");
  }
});

<input type="email" placeholder="Email Address" id="loginemail" autofocus required>

<input type="email" placeholder="Email Address" id="loginemail" required>

<input type="button" value="Log In" id="loginbutton">

I read that when Jquery is told to use the selector, say for an id, it will find all instances of that id and make an array. The [#] is to clarify to Jquery which id to act upon. You can see that I have two email fields, each with the same id of 'loginemail'.

When the index is set to [0], filling in the first email box and clicking Log In results in a successful alert.

However, when the index is set to [1], this means Jquery should be acting on the 2nd email box. When I fill in the 2nd email box correctly, the alert does not show. Why is this?


问:
How to filter multidimensional array based on another multidimensional array of exclusions?
I'm attempting to filter a multidimensional array containing (>40,000) products.  Each product entry/subarray contains the product id and some product attributes.

I have an associative exclusion array which has 1 or more blacklisted values pertaining to specific attributes.

If a product has any key-value pairs that are specified in my exclusion array, then that product/subarray should be filtered out.

Exclusions array:

```<code>$exclusions = [
    'Discontinue Status' => [
        'Discontinued',
        'Run Down Stock',
    ],
    'Hazardous' => [
        'No',
    ],
];
</code>```

Sample products array:

```<code>$products = [
    [
        'Product ID' => '452',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '463',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '477',
        'Discontinue Status' => 'Run Down Stock',
        'Hazardous' => 'Yes',
    ],
    [
        'Product ID' => '502',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
];
</code>```

Expected output:

```<code>[
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
]
</code>```

I was only able to get as far as returning the correct number of products/items but only the exclusion associated with that item and not the item itself with the following code.

```<code>    $exclusions = $this->exclusions;

    $products = [];

    foreach ($array as $product) {

        $filtered = array_filter($product, function ($val, $key) use ($exclusions) {
                return isset($exclusions[$key]) && !in_array($val, $exclusions[$key]);
            },
            ARRAY_FILTER_USE_BOTH
        );

        $products[] = $filtered;

    }

    $result = array_filter(array_map('array_filter', $products));

    echo '```' . var_export($result, true) . '```';
    echo count($result);
</code>```

答:
First we're setting up $data, $discontinued and $hazardous as blank arrays, we will populate these arrays with data as we loop through the $exclusions and $products arrays.

```<code>$data = $discontinued = $hazardous = [];

foreach($exclusions as $exclusion) {

    if(isset($exclusion['Discontinue Status'])) $discontinued = $exclusion['Discontinue Status'];

    if(isset($exclusion['Hazardous'])) $hazardous = $exclusion['Hazardous'];

}
</code>```

Now we we want to loop through the products and check if the values of each products matches anything in the exclusion arrays.

```<code>foreach($products as $product) {

    if(in_array($product['Discountinue Status'], $discontinued)) continue;
    if(in_array($product['Hazardous'], $hazardous)) continue;

    $data[] = $product;

}
</code>```

Body:
I'm attempting to filter a multidimensional array containing (>40,000) products.  Each product entry/subarray contains the product id and some product attributes.

I have an associative exclusion array which has 1 or more blacklisted values pertaining to specific attributes.

If a product has any key-value pairs that are specified in my exclusion array, then that product/subarray should be filtered out.

Exclusions array:

$exclusions = [
    'Discontinue Status' => [
        'Discontinued',
        'Run Down Stock',
    ],
    'Hazardous' => [
        'No',
    ],
];

Sample products array:

$products = [
    [
        'Product ID' => '452',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '463',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '477',
        'Discontinue Status' => 'Run Down Stock',
        'Hazardous' => 'Yes',
    ],
    [
        'Product ID' => '502',
        'Discontinue Status' => 'Discontinued',
        'Hazardous' => 'No',
    ],
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
];

Expected output:

[
    [
        'Product ID' => '520',
        'Discontinue Status' => 'Normal',
        'Hazardous' => 'Yes',
    ],
]

I was only able to get as far as returning the correct number of products/items but only the exclusion associated with that item and not the item itself with the following code.

    $exclusions = $this->exclusions;

    $products = [];

    foreach ($array as $product) {

        $filtered = array_filter($product, function ($val, $key) use ($exclusions) {
                return isset($exclusions[$key]) && !in_array($val, $exclusions[$key]);
            },
            ARRAY_FILTER_USE_BOTH
        );

        $products[] = $filtered;

    }

    $result = array_filter(array_map('array_filter', $products));

    echo '
' . var_export($result, true) . '
';
    echo count($result);

Body:
First we're setting up $data, $discontinued and $hazardous as blank arrays, we will populate these arrays with data as we loop through the $exclusions and $products arrays.

$data = $discontinued = $hazardous = [];

foreach($exclusions as $exclusion) {

    if(isset($exclusion['Discontinue Status'])) $discontinued = $exclusion['Discontinue Status'];

    if(isset($exclusion['Hazardous'])) $hazardous = $exclusion['Hazardous'];

}

Now we we want to loop through the products and check if the values of each products matches anything in the exclusion arrays.

foreach($products as $product) {

    if(in_array($product['Discountinue Status'], $discontinued)) continue;
    if(in_array($product['Hazardous'], $hazardous)) continue;

    $data[] = $product;

}


问:
Use comma instead of semicolon for expression splitting in C
Give me an idea please, when one can use comma as a delimiter and when only semicolon:</p>

```<code>typedef struct k{int a,b;}*K;
main() {
  K z=(K)malloc(2*sizeof(int));
  z->a=1, // <- may be ; or , at the eol
  // This seems not like a multi-variables definition of same type vars, so why ',' is good?
  z->b=2;
  free(z);
  return 0;
}
</code>```

答:
First of all, you must realize that you are using the comma operator here. See What does the comma operator , do?

There is no practical difference between the comma operator and semicolons. The key here is to understand sequence points, an abstract C term for points in the source where all previous evaluations must be done. A semicolon always introduces a sequence point, but so does the comma operator. That's why your code works and why z->a=1 is guaranteed to be executed ("sequenced") before z->b=2.

However, using the comma operator leads to strange, hard-to-read code. It is often confused with commas in initializer lists or function call parameter lists. In your comment, you confuse this for a multiple variable initialization.

As a rule of thumb, the comma operator should not be used at all, except for very specialized cases.

The main use of the comma operator and the reason why it is still in the language, is that it allows for function-like macros that do multiple things but still return a value like a function. Example:

```<code>#include <stdio.h>

int foo (void)
{
  puts("hello world");
  return 1;
}

#define foo() (puts("mocking function foo"), 2)

int main()
{
  printf("%d", foo());
  return 0;
}
</code>```

Here a macro is completely replacing the function with the same name (known as "function mocking"), but keeps the calling API intact, which might be useful for debug and test purposes. There's a place for the comma operator in special-purpose macros like these.

Body:
Give me an idea please, when one can use comma as a delimiter and when only semicolon:

typedef struct k{int a,b;}*K;
main() {
  K z=(K)malloc(2*sizeof(int));
  z->a=1, // <- may be ; or , at the eol
  // This seems not like a multi-variables definition of same type vars, so why ',' is good?
  z->b=2;
  free(z);
  return 0;
}

Body:
First of all, you must realize that you are using the comma operator here. See What does the comma operator , do?

There is no practical difference between the comma operator and semicolons. The key here is to understand sequence points, an abstract C term for points in the source where all previous evaluations must be done. A semicolon always introduces a sequence point, but so does the comma operator. That's why your code works and why z->a=1 is guaranteed to be executed ("sequenced") before z->b=2.

However, using the comma operator leads to strange, hard-to-read code. It is often confused with commas in initializer lists or function call parameter lists. In your comment, you confuse this for a multiple variable initialization.

As a rule of thumb, the comma operator should not be used at all, except for very specialized cases.

The main use of the comma operator and the reason why it is still in the language, is that it allows for function-like macros that do multiple things but still return a value like a function. Example:

#include <stdio.h>

int foo (void)
{
  puts("hello world");
  return 1;
}

#define foo() (puts("mocking function foo"), 2)

int main()
{
  printf("%d", foo());
  return 0;
}

Here a macro is completely replacing the function with the same name (known as "function mocking"), but keeps the calling API intact, which might be useful for debug and test purposes. There's a place for the comma operator in special-purpose macros like these.


问:
How to properly use ControlFlowGraph from roslyn code analysis in C#
I cannot understand why I am getting an error (using VS2017) for the code in below related to not finding the class ControlFlowGraph which is supposed to be part of the package Microsoft.CodeAnalysis.FlowAnalysis:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FlowAnalysis;

namespace CodeAnalysisApp3
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Attempt to set the version of MSBuild.
            var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
            var instance = visualStudioInstances[0];

            Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");

            // NOTE: Be sure to register an instance with the MSBuildLocator
            //       before calling MSBuildWorkspace.Create()
            //       otherwise, MSBuildWorkspace won't MEF compose.
            MSBuildLocator.RegisterInstance(instance);

            using (var workspace = MSBuildWorkspace.Create())
            {
                // Print message for WorkspaceFailed event to help diagnosing project load failures.
                workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);

                var solutionPath = args[0];
                Console.WriteLine($"Loading solution '{solutionPath}'");

                // Attach progress reporter so we print projects as they are loaded.
                var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
                Console.WriteLine($"Finished loading solution '{solutionPath}'");

                // TODO: Do analysis on the projects in the loaded solution
                CSharpParseOptions options = CSharpParseOptions.Default
                .WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "") });

                var projIds = solution.ProjectIds;

                var project = solution.GetProject(projIds[0]);

                Compilation compilation = await project.GetCompilationAsync();

                if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName))
                {
                    var mySyntaxTree = compilation.SyntaxTrees.First();

                    // get syntax nodes for methods
                    var methodNodes = from methodDeclaration in mySyntaxTree.GetRoot().DescendantNodes()
                               .Where(x => x is MethodDeclarationSyntax)
                                      select methodDeclaration;

                    foreach (MethodDeclarationSyntax node in methodNodes)
                    {
                        var model = compilation.GetSemanticModel(node.SyntaxTree);
                        node.Identifier.ToString();
                        if (node.SyntaxTree.Options.Features.Any())
                        {
                            var graph = ControlFlowGraph.Create(node, model); // CFG is here
                        }
                    }
                }
            }
        }

        private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
        {
            public void Report(ProjectLoadProgress loadProgress)
            {
                var projectDisplay = Path.GetFileName(loadProgress.FilePath);
                if (loadProgress.TargetFramework != null)
                {
                    projectDisplay += $" ({loadProgress.TargetFramework})";
                }

                Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
            }
        }
    }
}
</code>```

However, when I compile the above code I am getting the following error message with VS2017:

```<code>1>Program.cs(67,41,67,57): error CS0103: The name 'ControlFlowGraph' does not exist in the current context
1>Done building project "CodeAnalysisApp3.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
</code>```

Version used:

```<code>Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5
</code>```

答:
Based on my test, I find I can use  class ControlFlowGraph.

I installed the following nugetpackage.

Microsoft.CodeAnalysis

Microsoft.Build.Locator

Then, you will see the following result.

Besides, I used .net framwork 4.6.1.

Body:
I cannot understand why I am getting an error (using VS2017) for the code in below related to not finding the class ControlFlowGraph which is supposed to be part of the package Microsoft.CodeAnalysis.FlowAnalysis:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FlowAnalysis;

namespace CodeAnalysisApp3
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Attempt to set the version of MSBuild.
            var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
            var instance = visualStudioInstances[0];

            Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");

            // NOTE: Be sure to register an instance with the MSBuildLocator
            //       before calling MSBuildWorkspace.Create()
            //       otherwise, MSBuildWorkspace won't MEF compose.
            MSBuildLocator.RegisterInstance(instance);

            using (var workspace = MSBuildWorkspace.Create())
            {
                // Print message for WorkspaceFailed event to help diagnosing project load failures.
                workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);

                var solutionPath = args[0];
                Console.WriteLine($"Loading solution '{solutionPath}'");

                // Attach progress reporter so we print projects as they are loaded.
                var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
                Console.WriteLine($"Finished loading solution '{solutionPath}'");

                // TODO: Do analysis on the projects in the loaded solution
                CSharpParseOptions options = CSharpParseOptions.Default
                .WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "") });

                var projIds = solution.ProjectIds;

                var project = solution.GetProject(projIds[0]);

                Compilation compilation = await project.GetCompilationAsync();

                if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName))
                {
                    var mySyntaxTree = compilation.SyntaxTrees.First();

                    // get syntax nodes for methods
                    var methodNodes = from methodDeclaration in mySyntaxTree.GetRoot().DescendantNodes()
                               .Where(x => x is MethodDeclarationSyntax)
                                      select methodDeclaration;

                    foreach (MethodDeclarationSyntax node in methodNodes)
                    {
                        var model = compilation.GetSemanticModel(node.SyntaxTree);
                        node.Identifier.ToString();
                        if (node.SyntaxTree.Options.Features.Any())
                        {
                            var graph = ControlFlowGraph.Create(node, model); // CFG is here
                        }
                    }
                }
            }
        }

        private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
        {
            public void Report(ProjectLoadProgress loadProgress)
            {
                var projectDisplay = Path.GetFileName(loadProgress.FilePath);
                if (loadProgress.TargetFramework != null)
                {
                    projectDisplay += $" ({loadProgress.TargetFramework})";
                }

                Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
            }
        }
    }
}

However, when I compile the above code I am getting the following error message with VS2017:

1>Program.cs(67,41,67,57): error CS0103: The name 'ControlFlowGraph' does not exist in the current context
1>Done building project "CodeAnalysisApp3.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Version used:

Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5


问:
Dynamic Feature with appbundle and PROGUARD not working
OVERVIEW:

I am facing an issue while accessing the activity of the on-demand dynamic feature module from the base module due to proguard. (most probably I guess)

DESCRIPTION:

I have implemented an ON-DEMAND dynamic feature module with app bundle and uploaded on play store.

Implemented proguard with custom rules with it.

After downloading the application from the play store and while accessing that module at runtime, the module gets downloaded. Just after downloading it, I have a call for accessing an activity from my base module to that dynamic module.

I am getting error as like below

```<code>...
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{xxx.yyyyyy.zzzzzz.stage/xxx.yyyyyy.zzzzzz.apphub.appview.view.AppHubActivity}:
java.lang.ClassNotFoundException: Didn't find class "xxx.yyyyyy.zzzzzz.apphub.appview.view.AppHubActivity"
on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file
...
...
</code>```

FYI:

xxx.yyyyyy.zzzzzz is my changed package name for privacy.

IRONY:

This entire code is working perfectly in debugging while accessing it from the app bundle locally without proguard.

I have tried all the links below to overcome this but could not.

1) https://issuetracker.google.com/issues/120517460

2) https://github.com/android/plaid/issues/764

3) java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

4) https://issuetracker.google.com/issues/79478779

5) https://github.com/android/app-bundle-samples/issues/17

I have also tried all types of proguard files which we can use, but still helpless.

Also kept that both classes in proguard: base and dynamic module activity class but got no success.

Hopefully looking for the solution here.

UPDATE:

not working in android OS 8,9 but working file in android 10.

答:
Make sure you use SplitCompat in the activities of your on-demand module AND in your Application.

See https://developer.android.com/guide/playcore#access_downloaded_modules which explains in more details how to do so.

Body:
OVERVIEW:

I am facing an issue while accessing the activity of the on-demand dynamic feature module from the base module due to proguard. (most probably I guess)

DESCRIPTION:

I have implemented an ON-DEMAND dynamic feature module with app bundle and uploaded on play store.

Implemented proguard with custom rules with it.

After downloading the application from the play store and while accessing that module at runtime, the module gets downloaded. Just after downloading it, I have a call for accessing an activity from my base module to that dynamic module.

I am getting error as like below

...
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{xxx.yyyyyy.zzzzzz.stage/xxx.yyyyyy.zzzzzz.apphub.appview.view.AppHubActivity}:
java.lang.ClassNotFoundException: Didn't find class "xxx.yyyyyy.zzzzzz.apphub.appview.view.AppHubActivity"
on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file
...
...

FYI:

xxx.yyyyyy.zzzzzz is my changed package name for privacy.

IRONY:

This entire code is working perfectly in debugging while accessing it from the app bundle locally without proguard.

I have tried all the links below to overcome this but could not.

1) https://issuetracker.google.com/issues/120517460

2) https://github.com/android/plaid/issues/764

3) java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

4) https://issuetracker.google.com/issues/79478779

5) https://github.com/android/app-bundle-samples/issues/17

I have also tried all types of proguard files which we can use, but still helpless.

Also kept that both classes in proguard: base and dynamic module activity class but got no success.

Hopefully looking for the solution here.

UPDATE:

not working in android OS 8,9 but working file in android 10.


问:
load() inside modal-body firing multiple times
I am working on a script that opens a bootstrap modal, then you confirm your selection with an "im sure" button, then that post()'s and if it submits successfully it load's a comment form into the modal-body. The comment form is stored in a partial, and the comment for uses wysihtml5. Here is my current code:

```<code>    modal_div.find('.confirm-o-c').click(function(ee){
            $.post(
                lnk.attr('href'),
                function(data, textStatus, jqxhr){
                    console.log(data);

                    var lbl = lnk.parent().prev().children('.label').first();
                    lbl.fadeOut('fast');
                    lbl.attr('class','label label-'+data.status)
                       .text(data.text)
                       .fadeIn('fast');
                    var newlnk = $('<a href="#">newlink</a>');
                    newlnk.attr('href',lnk.attr('href').replace('complete','revert'));
                    lnk.parent().append(newlnk);
                    lnk.remove();
                    var status = data.status;
                    var id = data.object.id;
                    var objective_id = data.object.objective_id;

                    if(status === 'submitted'){
                        modal.fadeOut('fast', function(){
                            modal.load('<?=URL::to_action('objectives/completion_comment/')?>/'+id, function(){
                                modal.fadeIn('fast');
                                $('#message-'+objective_id).wysihtml5();

                            });

                            $('#confirm-objective-complete').addClass('modal-large');
                            $('#submit-comment').css("display", "inline-block");
                            oldfooterbtn.css("display", "none");
                            footerbtncancel.css("display", "none");
                            footerbtnclose.css("display", "none");
                            confirmtext.css("display", "none");
                        });
                    };

                });
            // objectives.init();
            ee.preventDefault();
</code>```

The problem
After confirming, the post works great, and it returns submitted, but then when the comment form is leaded it my console shows it happening like 8 times and I get this error
TypeError: f.contentWindow is null

I have seen some like:

```<code>    $(this).one('load', function () {
        console.log("load complete");
    });'
</code>```

but I couldn't figure our how to implement using a URL like I am. Any help would be greatly appreciated.

Thank you for looking over my code.

答:
Make sure you are not binding multiple events to the modal.
You can clear it with the unbind function, specially if are binding events to it multiple times:</p>

```<code>$('#myModal').unbind();
</code>```

Body:
I am working on a script that opens a bootstrap modal, then you confirm your selection with an "im sure" button, then that post()'s and if it submits successfully it load's a comment form into the modal-body. The comment form is stored in a partial, and the comment for uses wysihtml5. Here is my current code:

    modal_div.find('.confirm-o-c').click(function(ee){
            $.post(
                lnk.attr('href'),
                function(data, textStatus, jqxhr){
                    console.log(data);

                    var lbl = lnk.parent().prev().children('.label').first();
                    lbl.fadeOut('fast');
                    lbl.attr('class','label label-'+data.status)
                       .text(data.text)
                       .fadeIn('fast');
                    var newlnk = $('newlink');
                    newlnk.attr('href',lnk.attr('href').replace('complete','revert'));
                    lnk.parent().append(newlnk);
                    lnk.remove();
                    var status = data.status;
                    var id = data.object.id;
                    var objective_id = data.object.objective_id;

                    if(status === 'submitted'){
                        modal.fadeOut('fast', function(){
                            modal.load('<?=URL::to_action('objectives/completion_comment/')?>/'+id, function(){
                                modal.fadeIn('fast');
                                $('#message-'+objective_id).wysihtml5();

                            });

                            $('#confirm-objective-complete').addClass('modal-large');
                            $('#submit-comment').css("display", "inline-block");
                            oldfooterbtn.css("display", "none");
                            footerbtncancel.css("display", "none");
                            footerbtnclose.css("display", "none");
                            confirmtext.css("display", "none");
                        });
                    };

                });
            // objectives.init();
            ee.preventDefault();

The problem
After confirming, the post works great, and it returns submitted, but then when the comment form is leaded it my console shows it happening like 8 times and I get this error
TypeError: f.contentWindow is null

I have seen some like:

    $(this).one('load', function () {
        console.log("load complete");
    });'

but I couldn't figure our how to implement using a URL like I am. Any help would be greatly appreciated.

Thank you for looking over my code.

Body:
Make sure you are not binding multiple events to the modal.
You can clear it with the unbind function, specially if are binding events to it multiple times:

$('#myModal').unbind();


问:
The first speed calculated ball does not go to the target it should go

In the function below, The distance between ball and target is
  known(R). Also, the angle between the resultant vector and the x-axis is
  known(LaunchAngle). Thanks to these parameters(R, LaunchAngle), I
  calculate the initial velocity of a ball. I checked all the values.
  According to physics, they are all correct. Although all calculations
  are correct, the ball does not hit the target.

```<code>void LaunchFromTargetPositionWithoutFrictionForce()
        {
            Vector3 projectileXZPos = new Vector3(transform.position.x, 0.0f, transform.position.z);
            Vector3 targetXZPos = new Vector3(TargetObjectTF.position.x, 0.0f, TargetObjectTF.position.z);
            transform.LookAt(targetXZPos);

            float R = Vector3.Distance(projectileXZPos, targetXZPos);
            float G = -Physics.gravity.y;

            float Vz = Mathf.Sqrt(G * R / Mathf.Sin((2.0f * LaunchAngle) * Mathf.Deg2Rad));
            float Vy = Vz * Mathf.Sin(LaunchAngle * Mathf.Deg2Rad);
            float Vx = Vz * Mathf.Cos(LaunchAngle * Mathf.Deg2Rad);
            text2.text = "vz: " + Vz.ToString() + " vy: " + Vy.ToString() + " vx: " + Vx.ToString();

            Vector3 localVelocity = new Vector3(0f, Vy, Vx);
            Vector3 globalVelocity = transform.TransformDirection(localVelocity);

            rigid.velocity = globalVelocity;
            bTargetReady = true;

            if (isSlowMotion) timeManager.slowMotion();
        }
</code>```

First location of the ball

And after 2-dimensional motion it is hit before target

答:
I changed first 3 line  with below codes. And problem solved.   </p>

```<code>    Vector3 projectileXZPos = transform.position;
    Vector3 targetXZPos = TargetObjectTF.position;
    float dist = Vector3.Distance(projectileXZPos, targetXZPos);
    transform.LookAt(targetXZPos);
</code>```

Body:
In the function below, The distance between ball and target is
  known(R). Also, the angle between the resultant vector and the x-axis is
  known(LaunchAngle). Thanks to these parameters(R, LaunchAngle), I
  calculate the initial velocity of a ball. I checked all the values.
  According to physics, they are all correct. Although all calculations
  are correct, the ball does not hit the target.

void LaunchFromTargetPositionWithoutFrictionForce()
        {
            Vector3 projectileXZPos = new Vector3(transform.position.x, 0.0f, transform.position.z);
            Vector3 targetXZPos = new Vector3(TargetObjectTF.position.x, 0.0f, TargetObjectTF.position.z);
            transform.LookAt(targetXZPos);

            float R = Vector3.Distance(projectileXZPos, targetXZPos);
            float G = -Physics.gravity.y;

            float Vz = Mathf.Sqrt(G * R / Mathf.Sin((2.0f * LaunchAngle) * Mathf.Deg2Rad));
            float Vy = Vz * Mathf.Sin(LaunchAngle * Mathf.Deg2Rad);
            float Vx = Vz * Mathf.Cos(LaunchAngle * Mathf.Deg2Rad);
            text2.text = "vz: " + Vz.ToString() + " vy: " + Vy.ToString() + " vx: " + Vx.ToString();

            Vector3 localVelocity = new Vector3(0f, Vy, Vx);
            Vector3 globalVelocity = transform.TransformDirection(localVelocity);

            rigid.velocity = globalVelocity;
            bTargetReady = true;

            if (isSlowMotion) timeManager.slowMotion();
        }

First location of the ball

And after 2-dimensional motion it is hit before target

Body:
I changed first 3 line  with below codes. And problem solved.

    Vector3 projectileXZPos = transform.position;
    Vector3 targetXZPos = TargetObjectTF.position;
    float dist = Vector3.Distance(projectileXZPos, targetXZPos);
    transform.LookAt(targetXZPos);


问:
Is it possible to connect vscode (on a local machine) with Google Colab (the free service) runtime?
I know on GCP, we can set up a vscode server and connect to that. But what I'm after here, is to know whether it is possible to connect to the runtime instance on Google Colab (the free one ie: https://colab.research.google.com) from a locally run vscode. If I'm not mistaken, we can connect to any remote Jupyter kernel in vscode instead of creating a new instance locally and connecting to it.

So I want to know if it is possible to first create a Python 3 notebook and then from your local machine, fire up vscode, connect to the Colab runtime and code inside vscode ?

There is nothing local here, all files, notebooks, everything resides on Google Colab, it's just the coding and executing the code (debugging, etc) using vscode instead of Google's own editor.

Update

Thanks to the answer, I could successfully connect to Google Colab. However, when I exited the ssh and tried to log in again I faced this:

```<code>Creating config file /etc/ssh/sshd_config with new version
Creating SSH2 RSA key; this may take some time ...
2048 SHA256:yxFwLslfRq7YZFWNIhAD8TfJdp6sTfFbR2CXOWcysOA root@7561da0610da (RSA)
Creating SSH2 ECDSA key; this may take some time ...
256 SHA256:6Yo/7I9JPyYfKJYvtiVelNFHrIL7R1xaB09fDWbVYf4 root@7561da0610da (ECDSA)
Creating SSH2 ED25519 key; this may take some time ...
256 SHA256:r1HvJi/Y9twPkXoayNA4cSF55eH4MdOETHhXNSiC4ok root@7561da0610da (ED25519)
Created symlink /etc/systemd/system/sshd.service → /lib/systemd/system/ssh.service.
Created symlink /etc/systemd/system/multi-user.target.wants/ssh.service → /lib/systemd/system/ssh.service.
invoke-rc.d: could not determine current runlevel
invoke-rc.d: policy-rc.d denied execution of start.
Copy authtoken from https://dashboard.ngrok.com/auth
··········
Root password: aCsRocquey6953P9tHhF
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

I restarted the Google Colab runtime, I even changed the ngrok token and tried again, no luck!

答:
If you exit a session, you can not reconnect, because I believe it changes the port. I tried it too, then it throws an error, saying it's not possible.

But, if you run through the setup again and go the the https://dashboard.ngrok.com/status, you will see, that the port changed. Then you will be able to use it as a new remote connection. This way, I managed it to connect again.

As far as I understand, once a session is terminated, Google will not keep your files.

Body:
I know on GCP, we can set up a vscode server and connect to that. But what I'm after here, is to know whether it is possible to connect to the runtime instance on Google Colab (the free one ie: https://colab.research.google.com) from a locally run vscode. If I'm not mistaken, we can connect to any remote Jupyter kernel in vscode instead of creating a new instance locally and connecting to it.

So I want to know if it is possible to first create a Python 3 notebook and then from your local machine, fire up vscode, connect to the Colab runtime and code inside vscode ?

There is nothing local here, all files, notebooks, everything resides on Google Colab, it's just the coding and executing the code (debugging, etc) using vscode instead of Google's own editor.

Update

Thanks to the answer, I could successfully connect to Google Colab. However, when I exited the ssh and tried to log in again I faced this:

Creating config file /etc/ssh/sshd_config with new version
Creating SSH2 RSA key; this may take some time ...
2048 SHA256:yxFwLslfRq7YZFWNIhAD8TfJdp6sTfFbR2CXOWcysOA root@7561da0610da (RSA)
Creating SSH2 ECDSA key; this may take some time ...
256 SHA256:6Yo/7I9JPyYfKJYvtiVelNFHrIL7R1xaB09fDWbVYf4 root@7561da0610da (ECDSA)
Creating SSH2 ED25519 key; this may take some time ...
256 SHA256:r1HvJi/Y9twPkXoayNA4cSF55eH4MdOETHhXNSiC4ok root@7561da0610da (ED25519)
Created symlink /etc/systemd/system/sshd.service → /lib/systemd/system/ssh.service.
Created symlink /etc/systemd/system/multi-user.target.wants/ssh.service → /lib/systemd/system/ssh.service.
invoke-rc.d: could not determine current runlevel
invoke-rc.d: policy-rc.d denied execution of start.
Copy authtoken from https://dashboard.ngrok.com/auth
··········
Root password: aCsRocquey6953P9tHhF
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I restarted the Google Colab runtime, I even changed the ngrok token and tried again, no luck!


问:
Event subscription by ARM template for topic with EndpointType as AzureFunction
I am trying to create an event grid topic subscription with "endpointType": "AzureFunction". It is giving following error: -

"error": {
      "code": "InvalidRequest",
      "message": "Invalid event subscription request: Supplied URL is invalid. It cannot be null or empty and should be a proper HTTPS URL
  like https://www.example.com."   }

My ARM template is given below: -

```<code>{
      "name": "[concat(variables('eventGridTopicName'), '/Microsoft.EventGrid/', variables('myFuncName'))]",
      "type": "Microsoft.EventGrid/topics/providers/eventSubscriptions",
      "apiVersion": "2019-01-01",
      "location": "[parameters('location')]",
      "properties": {
        "topic": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('resourceGroupName'), '/providers/Microsoft.EventGrid/topics/', variables('eventGridTopicName'))]",
        "destination": {
          "endpointType": "AzureFunction",
          "properties": {
            "resourceId": "[resourceId('Microsoft.Web/sites/functions/', variables('funcAppName'), variables('myFuncName'))]",
            "maxEventsPerBatch": 1,
            "preferredBatchSizeInKilobytes": 64
          }
        },
        "filter": {
          "advancedFilters": [
            {
              "operatorType": "StringIn",
              "key": "eventType",
              "values": [
                "xyzEvent"
              ]
            },
            {
              "operatorType": "StringIn",
              "key": "subject",
              "values": [
                "xyzEventReceived"
              ]
            }
          ]
        },
        "labels": [],
        "eventDeliverySchema": "EventGridSchema"
      },
      "dependsOn": [
        "[variables('eventGridTopicName')]"
      ]
    }
</code>```

Earlier, I was using EndpointType as a webhook since new event handlers like Azure Function, storage Queues, etc. were not available (https://learn.microsoft.com/en-us/azure/event-grid/event-handlers). I used the generated arm template from Azure portal as shown below: -

Has anyone faced this issue?

答:
Jakob's suggestion for changing api version worked for me with change in resourceId. Here is my modified working template: -</p>

```<code>{
      "name": "[concat(variables('eventGridTopicName'), '/Microsoft.EventGrid/', variables('myFuncName'))]",
      "type": "Microsoft.EventGrid/topics/providers/eventSubscriptions",
      "apiVersion": "2020-01-01-preview",
      "location": "[parameters('location')]",
      "properties": {
        "topic": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('resourceGroupName'), '/providers/Microsoft.EventGrid/topics/', variables('eventGridTopicName'))]",
        "destination": {
          "endpointType": "AzureFunction",
          "properties": {
            "resourceId": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/sites/', variables('funcAppName'), '/functions/' , variables('myFuncName'))]",
            "maxEventsPerBatch": 1,
            "preferredBatchSizeInKilobytes": 64
          }
        },
        "filter": {
          "advancedFilters": [
            {
              "operatorType": "StringIn",
              "key": "eventType",
              "values": [
                "xyzEvent"
              ]
            },
            {
              "operatorType": "StringIn",
              "key": "subject",
              "values": [
                "xyzEventReceived"
              ]
            }
          ]
        },
        "labels": [],
        "eventDeliverySchema": "EventGridSchema"
      },
      "dependsOn": [
        "[variables('eventGridTopicName')]"
      ]
    }
</code>```

Body:
I am trying to create an event grid topic subscription with "endpointType": "AzureFunction". It is giving following error: -

"error": {
      "code": "InvalidRequest",
      "message": "Invalid event subscription request: Supplied URL is invalid. It cannot be null or empty and should be a proper HTTPS URL
  like https://www.example.com."   }

My ARM template is given below: -

{
      "name": "[concat(variables('eventGridTopicName'), '/Microsoft.EventGrid/', variables('myFuncName'))]",
      "type": "Microsoft.EventGrid/topics/providers/eventSubscriptions",
      "apiVersion": "2019-01-01",
      "location": "[parameters('location')]",
      "properties": {
        "topic": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('resourceGroupName'), '/providers/Microsoft.EventGrid/topics/', variables('eventGridTopicName'))]",
        "destination": {
          "endpointType": "AzureFunction",
          "properties": {
            "resourceId": "[resourceId('Microsoft.Web/sites/functions/', variables('funcAppName'), variables('myFuncName'))]",
            "maxEventsPerBatch": 1,
            "preferredBatchSizeInKilobytes": 64
          }
        },
        "filter": {
          "advancedFilters": [
            {
              "operatorType": "StringIn",
              "key": "eventType",
              "values": [
                "xyzEvent"
              ]
            },
            {
              "operatorType": "StringIn",
              "key": "subject",
              "values": [
                "xyzEventReceived"
              ]
            }
          ]
        },
        "labels": [],
        "eventDeliverySchema": "EventGridSchema"
      },
      "dependsOn": [
        "[variables('eventGridTopicName')]"
      ]
    }

Earlier, I was using EndpointType as a webhook since new event handlers like Azure Function, storage Queues, etc. were not available (https://learn.microsoft.com/en-us/azure/event-grid/event-handlers). I used the generated arm template from Azure portal as shown below: -

Has anyone faced this issue?

Body:
Jakob's suggestion for changing api version worked for me with change in resourceId. Here is my modified working template: -

{
      "name": "[concat(variables('eventGridTopicName'), '/Microsoft.EventGrid/', variables('myFuncName'))]",
      "type": "Microsoft.EventGrid/topics/providers/eventSubscriptions",
      "apiVersion": "2020-01-01-preview",
      "location": "[parameters('location')]",
      "properties": {
        "topic": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('resourceGroupName'), '/providers/Microsoft.EventGrid/topics/', variables('eventGridTopicName'))]",
        "destination": {
          "endpointType": "AzureFunction",
          "properties": {
            "resourceId": "[concat('/subscriptions/', parameters('subscriptionId'),'/resourcegroups/', parameters('resourceGroupName'), '/providers/Microsoft.Web/sites/', variables('funcAppName'), '/functions/' , variables('myFuncName'))]",
            "maxEventsPerBatch": 1,
            "preferredBatchSizeInKilobytes": 64
          }
        },
        "filter": {
          "advancedFilters": [
            {
              "operatorType": "StringIn",
              "key": "eventType",
              "values": [
                "xyzEvent"
              ]
            },
            {
              "operatorType": "StringIn",
              "key": "subject",
              "values": [
                "xyzEventReceived"
              ]
            }
          ]
        },
        "labels": [],
        "eventDeliverySchema": "EventGridSchema"
      },
      "dependsOn": [
        "[variables('eventGridTopicName')]"
      ]
    }