问:
WebSocket connection from node module to chrome extension closing automatically in Windows 10
I use https://www.npmjs.com/package/ws npm package to communicate between my npm module and my chrome extension.

Connection is getting opened, but closes in few seconds.

I researched the topic and I found that I should send messages back and forth between webSocket server and Client to keep it alive.

I am sanding this messages every 2 sec but my connection is still closing.

Interesting stuff is that close event fires on node module side only, while chrome plugin does not fire the event. Here is a code from my chrome extension:

function myPlugin() {
    myPlugin.prototype.socket = false;
    myPlugin.prototype.isConnected = false;
    myPlugin.prototype.port = false;
    myPlugin.prototype.pluginName = "Tab Reloader";

    myPlugin.prototype.init();
};

myPlugin.prototype = {
    initListeners: function () {
        chrome.browserAction.onClicked.addListener(function(tab) {
            if (!this.isConnected) {
                this.connectToServer();
            } else {
                this.disconnectFromServer();
            }
        }.bind(this));
    },

    setPort: function () {
        chrome.storage.sync.get(['port'], function(items) {
            this.port = items.port || '8001';
        }.bind(this));
    },

    getTabsToReload: function (callback) {
        var tabsToReload = [];

        chrome.storage.sync.get(['hostName'], function(items) {
            if (!items.hostName) {
                chrome.tabs.query({active: true}, function(tabs) {
                    tabs.forEach(function (tab) {
                        tabsToReload.push(tab);
                    });

                    callback(tabsToReload);
                });
            } else {
                chrome.tabs.query({}, function(tabs) {
                    tabs.forEach(function (tab) {
                        if (tab.url.indexOf(items.hostName) != -1) {
                            tabsToReload.push(tab);
                        }
                    });

                    callback(tabsToReload);
                });
            }
        }.bind(this));
    },

    initSocketListeners: function () {
        var fileExtIndex,
            fileExt,
            file;

        this.socket.onmessage = function (ev) {
            file = ev.data.toString();
            fileExtIndex = file.lastIndexOf('.') + 1;
            fileExt = file.slice(fileExtIndex),
            fileNameStandardize = file.replace(/\\/g, '\/'),
            indexOfLastSeparator = fileNameStandardize.lastIndexOf('/') + 1,
            fileName = file.slice(indexOfLastSeparator);

            if (file != 'pong' && file.indexOf('connected to server!!!') == -1) {
                //do stuff
            } else {
                if (file == 'pong') {
                    this.isAlive = true;
                }
            }
        }.bind(this);

        this.socket.addEventListener('close', function (ev) {
            console.log('connection Closed')
            clearInterval(this.aliveInterval);
            chrome.browserAction.setIcon({
                path: {
                    "16": "img/icon_disabled_16.png",
                    "24": "img/icon_disabled_24.png",
                    "32": "img/icon_disabled_32.png"
                }
            });
            this.isConnected = false;
        }.bind(this));
    },

    connectToServer: function () {
        this.socket = new WebSocket("ws://localhost:" + this.port);

        this.socket.addEventListener('error', function (ev) {
            this.isConnected = false;
            alert('Error connecting to websocket server, make sure it\'s running and port ' + this.port + ' is not occupied by other process');
        }.bind(this));

        this.socket.addEventListener('open', function (ev) {
            this.isConnected = true;
            this.socket.send(this.pluginName + ' connected to server!!!');
            this.initSocketListeners();
            this.stayConnected();
            this.isAlive = true;
            this.aliveInterval = setInterval(function () {
                this.checkIfAlive();
            }.bind(this), 2500);

            this.getTabsToReload(function (tabsToReload) {
                tabsToReload.forEach(function (tab) {
                    chrome.tabs.update(tab.id, {url: tab.url});
                });
            });

            chrome.browserAction.setIcon({
                path: {
                    "16": "img/icon_active_16.png",
                    "24": "img/icon_active_24.png",
                    "32": "img/icon_active_32.png"
                }
            });
        }.bind(this));
    },

    disconnectFromServer: function () {
        this.socket.close();
    },

    stayConnected: function () {
        setTimeout(function () {
            this.socket.send('ping');

            if (this.isConnected) {
                this.stayConnected();
            }
        }.bind(this), 1000);
    },

    checkIfAlive: function () {
        this.isAlive = false;

        setTimeout(function () {
            console.log(this.isAlive)
            if (!this.isAlive) {
                console.log(this.isAlive)
                this.disconnectFromServer();
            }
        }.bind(this), 2000);
    },

    init: function () {
        this.setPort();
        this.initListeners();
    }
}

window.onload = new myPlugin();
```

<p>And here is my node module code:</p>

<pre class="lang-javascript prettyprint-override"><code>    "use strict";

//var WebSocketServer = require('websocketserver');
//var WebSocketServer = require("nodejs-websocket")
var WebSocket = require('ws');

class MyModule {
    constructor(options) {
        this.options = options;
        this.server = false;
        this.pluginName = 'Some';
        this.isConnected = false;
        this.connection = false;

        this.init();

        return this.refreshTab.bind(this);
    }

    init() {
        var port = this.options ? this.options.port : false;
        this.server = new WebSocket.Server({port: port || 8001});

        this.server.on('connection', (websocket) => {
            console.log('Connection open');
            this.websocket = websocket;
            this.isConnected= true;

            this.initListeners();
        });
    }

    refreshTab(uploadedFiles) {
        if (this.isConnected) {
            if (Array.isArray(uploadedFiles)) {
                uploadedFiles.forEach(function (el) {
                    this.websocket.send(el.toString());
                }.bind(this));
            } else {
                this.websocket.send(uploadedFiles ? uploadedFiles.toString() : 'reload');
            }
        } else {
            console.log('You are not connected to server yet.');
        }
    }

    initListeners() {
        this.websocket.on('message', (message) => {
            if (message == 'ping') {
                this.websocket.send('pong');
            }
        });

        this.websocket.on('close', () => {
            this.isConnected = false;
            console.log(this.pluginName + ' connection is closed');
        });
    }
};

module.exports = MyModule;
</code>```

Appreciate any help,
Thanks in advance.

答:
So my problem was actually in manifest.json

```<code>"background": {
    "scripts": ["js/tab_reloader.js"],
    "persistent": false
}
</code>```

"persistent" was set to false, it transformed my Background page into Event Page. And event page is unloaded from memory after a period of time, which was killing the connection. After I set "persistent" to true the problem got fixed.

Body:
I use https://www.npmjs.com/package/ws npm package to communicate between my npm module and my chrome extension.

Connection is getting opened, but closes in few seconds.

I researched the topic and I found that I should send messages back and forth between webSocket server and Client to keep it alive.

I am sanding this messages every 2 sec but my connection is still closing.

Interesting stuff is that close event fires on node module side only, while chrome plugin does not fire the event. Here is a code from my chrome extension:

function myPlugin() {
    myPlugin.prototype.socket = false;
    myPlugin.prototype.isConnected = false;
    myPlugin.prototype.port = false;
    myPlugin.prototype.pluginName = "Tab Reloader";

    myPlugin.prototype.init();
};

myPlugin.prototype = {
    initListeners: function () {
        chrome.browserAction.onClicked.addListener(function(tab) {
            if (!this.isConnected) {
                this.connectToServer();
            } else {
                this.disconnectFromServer();
            }
        }.bind(this));
    },

    setPort: function () {
        chrome.storage.sync.get(['port'], function(items) {
            this.port = items.port || '8001';
        }.bind(this));
    },

    getTabsToReload: function (callback) {
        var tabsToReload = [];

        chrome.storage.sync.get(['hostName'], function(items) {
            if (!items.hostName) {
                chrome.tabs.query({active: true}, function(tabs) {
                    tabs.forEach(function (tab) {
                        tabsToReload.push(tab);
                    });

                    callback(tabsToReload);
                });
            } else {
                chrome.tabs.query({}, function(tabs) {
                    tabs.forEach(function (tab) {
                        if (tab.url.indexOf(items.hostName) != -1) {
                            tabsToReload.push(tab);
                        }
                    });

                    callback(tabsToReload);
                });
            }
        }.bind(this));
    },

    initSocketListeners: function () {
        var fileExtIndex,
            fileExt,
            file;

        this.socket.onmessage = function (ev) {
            file = ev.data.toString();
            fileExtIndex = file.lastIndexOf('.') + 1;
            fileExt = file.slice(fileExtIndex),
            fileNameStandardize = file.replace(/\\/g, '\/'),
            indexOfLastSeparator = fileNameStandardize.lastIndexOf('/') + 1,
            fileName = file.slice(indexOfLastSeparator);

            if (file != 'pong' && file.indexOf('connected to server!!!') == -1) {
                //do stuff
            } else {
                if (file == 'pong') {
                    this.isAlive = true;
                }
            }
        }.bind(this);

        this.socket.addEventListener('close', function (ev) {
            console.log('connection Closed')
            clearInterval(this.aliveInterval);
            chrome.browserAction.setIcon({
                path: {
                    "16": "img/icon_disabled_16.png",
                    "24": "img/icon_disabled_24.png",
                    "32": "img/icon_disabled_32.png"
                }
            });
            this.isConnected = false;
        }.bind(this));
    },

    connectToServer: function () {
        this.socket = new WebSocket("ws://localhost:" + this.port);

        this.socket.addEventListener('error', function (ev) {
            this.isConnected = false;
            alert('Error connecting to websocket server, make sure it\'s running and port ' + this.port + ' is not occupied by other process');
        }.bind(this));

        this.socket.addEventListener('open', function (ev) {
            this.isConnected = true;
            this.socket.send(this.pluginName + ' connected to server!!!');
            this.initSocketListeners();
            this.stayConnected();
            this.isAlive = true;
            this.aliveInterval = setInterval(function () {
                this.checkIfAlive();
            }.bind(this), 2500);

            this.getTabsToReload(function (tabsToReload) {
                tabsToReload.forEach(function (tab) {
                    chrome.tabs.update(tab.id, {url: tab.url});
                });
            });

            chrome.browserAction.setIcon({
                path: {
                    "16": "img/icon_active_16.png",
                    "24": "img/icon_active_24.png",
                    "32": "img/icon_active_32.png"
                }
            });
        }.bind(this));
    },

    disconnectFromServer: function () {
        this.socket.close();
    },

    stayConnected: function () {
        setTimeout(function () {
            this.socket.send('ping');

            if (this.isConnected) {
                this.stayConnected();
            }
        }.bind(this), 1000);
    },

    checkIfAlive: function () {
        this.isAlive = false;

        setTimeout(function () {
            console.log(this.isAlive)
            if (!this.isAlive) {
                console.log(this.isAlive)
                this.disconnectFromServer();
            }
        }.bind(this), 2000);
    },

    init: function () {
        this.setPort();
        this.initListeners();
    }
}

window.onload = new myPlugin();

And here is my node module code:

    "use strict";

//var WebSocketServer = require('websocketserver');
//var WebSocketServer = require("nodejs-websocket")
var WebSocket = require('ws');

class MyModule {
    constructor(options) {
        this.options = options;
        this.server = false;
        this.pluginName = 'Some';
        this.isConnected = false;
        this.connection = false;

        this.init();

        return this.refreshTab.bind(this);
    }

    init() {
        var port = this.options ? this.options.port : false;
        this.server = new WebSocket.Server({port: port || 8001});

        this.server.on('connection', (websocket) => {
            console.log('Connection open');
            this.websocket = websocket;
            this.isConnected= true;

            this.initListeners();
        });
    }

    refreshTab(uploadedFiles) {
        if (this.isConnected) {
            if (Array.isArray(uploadedFiles)) {
                uploadedFiles.forEach(function (el) {
                    this.websocket.send(el.toString());
                }.bind(this));
            } else {
                this.websocket.send(uploadedFiles ? uploadedFiles.toString() : 'reload');
            }
        } else {
            console.log('You are not connected to server yet.');
        }
    }

    initListeners() {
        this.websocket.on('message', (message) => {
            if (message == 'ping') {
                this.websocket.send('pong');
            }
        });

        this.websocket.on('close', () => {
            this.isConnected = false;
            console.log(this.pluginName + ' connection is closed');
        });
    }
};

module.exports = MyModule;

Appreciate any help,
Thanks in advance.

Body:
So my problem was actually in manifest.json

"background": {
    "scripts": ["js/tab_reloader.js"],
    "persistent": false
}

"persistent" was set to false, it transformed my Background page into Event Page. And event page is unloaded from memory after a period of time, which was killing the connection. After I set "persistent" to true the problem got fixed.


来源: stackexchange

问:
Create COM-Object from own C# Dll in Progress 4GL
I'm wondering how I can create a Com-Object from my own C# DLL.

I made the following Class in C#:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ProgressNet
{
    [Guid("a9b1e34d-3ea3-4e91-a77a-5bcb25875485")]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    [ProgId("ProgressNet.Server")]
    public class NetServer
    {
        public NetServer() {}

        [DispId(1)]
        public string GetString()
        {
            return "Some String";
        }
    }
}
</code>```

In Properties I checked Register for COM Interop.

Then I registered the DLL with regasm.

```<code>regasm G:\ProgressTestApp\ProgressNet.dll /tlb:G:\ProgressTestApp\ProgressNet.tlb /codebase
</code>```

Then I tried in Progress 4GL this Code:

```<code>DEFINE VARIABLE NetServer AS COM-HANDLE.
CREATE "ProgressNet.NetServer" NetServer.
MESSAGE NetServer:GetString().
</code>```

But then I get "The automation server for ProgressNet.NetServer is not registered properly"..

Any Suggestions? :)

答:
The error is in the create com-handle statement. It should be create "ProgressNet.Server" NetServer. and not "ProgressNet.NetServer" as specified by the ProgId call.

I registered the DLL with regasm as you mentioned and used the code below to test and it worked fine.

```<code>def var ch as com-handle no-undo.

create "ProgressNet.Server" ch.

MESSAGE ch:GetString()
    VIEW-AS ALERT-BOX INFO BUTTONS OK.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering how I can create a Com-Object from my own C# DLL.

I made the following Class in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ProgressNet
{
    [Guid("a9b1e34d-3ea3-4e91-a77a-5bcb25875485")]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ComVisible(true)]
    [ProgId("ProgressNet.Server")]
    public class NetServer
    {
        public NetServer() {}

        [DispId(1)]
        public string GetString()
        {
            return "Some String";
        }
    }
}

In Properties I checked Register for COM Interop.

Then I registered the DLL with regasm.

regasm G:\ProgressTestApp\ProgressNet.dll /tlb:G:\ProgressTestApp\ProgressNet.tlb /codebase

Then I tried in Progress 4GL this Code:

DEFINE VARIABLE NetServer AS COM-HANDLE.
CREATE "ProgressNet.NetServer" NetServer.
MESSAGE NetServer:GetString().

But then I get "The automation server for ProgressNet.NetServer is not registered properly"..

Any Suggestions? :)

Body:
The error is in the create com-handle statement. It should be create "ProgressNet.Server" NetServer. and not "ProgressNet.NetServer" as specified by the ProgId call.

I registered the DLL with regasm as you mentioned and used the code below to test and it worked fine.

def var ch as com-handle no-undo.

create "ProgressNet.Server" ch.

MESSAGE ch:GetString()
    VIEW-AS ALERT-BOX INFO BUTTONS OK.


问:
Flex: Restore Spark VideoDisplay stream
EDIT
If someone can at least tell me how to receive an event when the streams disconnects that would be great.

The documentation for this control is simply horrible. I have an application that will have a live video stream and I'm looking for a way to make the VideoDisplay control restore its connection in case of the occurrence of any of these specific scenarios:

The application starts and the stream is not online yet.

The application is streaming and the user is disconnected from the internet.

The application is streaming and the video server crashes and reboots.

I'm using Wowza Media Server and Wirecast to test this. 1 and 3 don't work, I'm not sure number 2 does. I made number 1 work by adding this very questionable piece of code:

```<code>    protected function onMediaPlayerStateChange(event:MediaPlayerStateChangeEvent):void
    {
        if (event.state == MediaPlayerState.PLAYBACK_ERROR)
        {
            var videoSource:DynamicStreamingVideoSource = this.videoDisplay.source as DynamicStreamingVideoSource;

            try
            {
                this.videoDisplay.source = null;
                this.videoDisplay.source = videoSource;
            }
            catch (any:*) {}
        }
    }
</code>```

As you can see I need a try/catch block since both calls to source cause exceptions, yet whatever happens before those exceptions seems to fix problem #1. This doesn't fix problem #3 because a media state change event apparently doesn't occur when you stop the video server.

This is my control declaration:

```<code><s:VideoDisplay id="videoDisplay" click="onVideoStreamClick(event)" mediaPlayerStateChange="onMediaPlayerStateChange(event)" muted="{this.videoMuted}" top="10" width="280" height="220" autoPlay="true" horizontalCenter="0">
    <s:source>
        <s:DynamicStreamingVideoSource id="videoSource" streamType="live" host="{FlexGlobals.topLevelApplication.parameters.videoStreamURL}">
            <s:DynamicStreamingVideoItem id="videoItemLow" streamName="{FlexGlobals.topLevelApplication.parameters.videoLow}" bitrate="{FlexGlobals.topLevelApplication.parameters.videoLowBitrate}" />
            <s:DynamicStreamingVideoItem id="videoItemMedium" streamName="{FlexGlobals.topLevelApplication.parameters.videoMedium}" bitrate="{FlexGlobals.topLevelApplication.parameters.videoMediumBitrate}" />
            <s:DynamicStreamingVideoItem id="videoItemHigh" streamName="{FlexGlobals.topLevelApplication.parameters.videoHigh}" bitrate="{FlexGlobals.topLevelApplication.parameters.videoHighBitrate}" />
        </s:DynamicStreamingVideoSource>
    </s:source>
</s:VideoDisplay>
</code>```

Does anyone know how to make the VideoDisplay recover from these issues? Any help is appreciated, thanks.

答:
I know this question was asked many years ago, but it still helped me solving my problem encouraging me diving into the sources of VideoDisplay (since there obviously is no "clean" solution ;-(

And for those who have the same problem my "solution" ,ight be helpful too:

I had to restart the same video after the user clicked abort but then decided to play it again. Without "resetting"  VideoDisplay this resulted in a black screen.

Here's how I solved the issue after I found out that in VideoDisplay an internal function "setupSource()" was called when in the commitProperties() function no thumnailSource was defined.

Since the setupSource() function was not publicly accessible I used this:

```<code>        myVideoDisplaySpark.enabled = false; // changes properties
        myVideoDisplaySpark.source = "";    // does not harm ;-)
        myVideoDisplaySpark.mx_internal::thumbnailSource = null; // forces a setupSource in commitProperties
        myVideoDisplaySpark.enabled = true;  // finally results in the call if setupSource
</code>```

That's at least what I understood; and at the end it worked for me ;-)

Title: Flex: Restore Spark VideoDisplay stream

Body:
EDIT
If someone can at least tell me how to receive an event when the streams disconnects that would be great.

The documentation for this control is simply horrible. I have an application that will have a live video stream and I'm looking for a way to make the VideoDisplay control restore its connection in case of the occurrence of any of these specific scenarios:

The application starts and the stream is not online yet.

The application is streaming and the user is disconnected from the internet.

The application is streaming and the video server crashes and reboots.

I'm using Wowza Media Server and Wirecast to test this. 1 and 3 don't work, I'm not sure number 2 does. I made number 1 work by adding this very questionable piece of code:

    protected function onMediaPlayerStateChange(event:MediaPlayerStateChangeEvent):void
    {
        if (event.state == MediaPlayerState.PLAYBACK_ERROR)
        {
            var videoSource:DynamicStreamingVideoSource = this.videoDisplay.source as DynamicStreamingVideoSource;

            try
            {
                this.videoDisplay.source = null;
                this.videoDisplay.source = videoSource;
            }
            catch (any:*) {}
        }
    }

As you can see I need a try/catch block since both calls to source cause exceptions, yet whatever happens before those exceptions seems to fix problem #1. This doesn't fix problem #3 because a media state change event apparently doesn't occur when you stop the video server.

This is my control declaration:

<s:VideoDisplay id="videoDisplay" click="onVideoStreamClick(event)" mediaPlayerStateChange="onMediaPlayerStateChange(event)" muted="{this.videoMuted}" top="10" width="280" height="220" autoPlay="true" horizontalCenter="0">
    <s:source>
        <s:DynamicStreamingVideoSource id="videoSource" streamType="live" host="{FlexGlobals.topLevelApplication.parameters.videoStreamURL}">
            <s:DynamicStreamingVideoItem id="videoItemLow" streamName="{FlexGlobals.topLevelApplication.parameters.videoLow}" bitrate="{FlexGlobals.topLevelApplication.parameters.videoLowBitrate}" />
            <s:DynamicStreamingVideoItem id="videoItemMedium" streamName="{FlexGlobals.topLevelApplication.parameters.videoMedium}" bitrate="{FlexGlobals.topLevelApplication.parameters.videoMediumBitrate}" />
            <s:DynamicStreamingVideoItem id="videoItemHigh" streamName="{FlexGlobals.topLevelApplication.parameters.videoHigh}" bitrate="{FlexGlobals.topLevelApplication.parameters.videoHighBitrate}" />
        </s:DynamicStreamingVideoSource>
    </s:source>
</s:VideoDisplay>

Does anyone know how to make the VideoDisplay recover from these issues? Any help is appreciated, thanks.

Body:
I know this question was asked many years ago, but it still helped me solving my problem encouraging me diving into the sources of VideoDisplay (since there obviously is no "clean" solution ;-(

And for those who have the same problem my "solution" ,ight be helpful too:

I had to restart the same video after the user clicked abort but then decided to play it again. Without "resetting"  VideoDisplay this resulted in a black screen.

Here's how I solved the issue after I found out that in VideoDisplay an internal function "setupSource()" was called when in the commitProperties() function no thumnailSource was defined.

Since the setupSource() function was not publicly accessible I used this:

        myVideoDisplaySpark.enabled = false; // changes properties
        myVideoDisplaySpark.source = "";    // does not harm ;-)
        myVideoDisplaySpark.mx_internal::thumbnailSource = null; // forces a setupSource in commitProperties
        myVideoDisplaySpark.enabled = true;  // finally results in the call if setupSource

That's at least what I understood; and at the end it worked for me ;-)


问:
How to suppress eXist-db betterForms CSS?
I wonder if it is possible to suppress eXist-db betterForms CSS.

I have googled for it, and the solution I have found here was to add the CSS class no-bf-css to the body element the HTML page, but it doesn't seem to work.

答:
To disable betterFORM in eXist:

Comment out or delete all betterFORM's servlets, filters and mapping in

```<code>    $EXIST_HOME/webapp/WEB_INF/web.xml
</code>```

Comment out or delete betterFORM's resource-servlet in

```<code>    $EXIST_HOME/webapp/WEB_INF/controller-config.xml
</code>```

(Adapted from Evgeny Gazdovsky's post to exist-open on May 4, 2013, archived at http://markmail.org/message/2mbnfzzmhqepc5zz.)

Body:
To disable betterFORM in eXist:

Comment out or delete all betterFORM's servlets, filters and mapping in

    $EXIST_HOME/webapp/WEB_INF/web.xml

Comment out or delete betterFORM's resource-servlet in

    $EXIST_HOME/webapp/WEB_INF/controller-config.xml

(Adapted from Evgeny Gazdovsky's post to exist-open on May 4, 2013, archived at http://markmail.org/message/2mbnfzzmhqepc5zz.)


问:
What is the best tool to draw out large inheritance pieces of code?
I have started doing a code review for someone, and there is a large inheritance model (many layers deep).  After filling up my white board, I realized that I need a tool to draw this out.

What is the best tool (preferably free) to draw this out, so I can visualize what's happening in the code base.  The code is in Python, but I think my question or the solution should be generic.  I don't mind drawing it out by hand as the value for me is the scalability around the visualization.

答:
StarUML is free.

Works great.  It's my go-to UML program when I need to visualize something.  You can do both class and sequence diagrams with it.  It even includes a nice reverse-engineer feature - but upon further review, it looks like python reverse engineering is not supported.

Even so, it's a good alternative to some of the heavier (non-free) proprietary solutions like Rational Rose.

ContentLicense: CC BY-SA 2.5


问:
Amateur Coder File Testing
I am working on a project and have a great idea.
This is a very simple question and I've done this before, but it doesn't seem to be working.
In my idle, when I type:

```<code>f = open('a.txt', 'w')
f.write('hi')
</code>```

I get an output of 2.
It doesn't make sense to me beyond the fact that hi has a length of two... I want to add 'hi' to my file!!

答:
Consider using the context handler when dealing with fileIO. By using the with statement as shown below, the file will automatically close when the codeblock is finished executing.

```<code>with open('a.txt', 'w') as f:
    f.write('hi')
</code>```

This saves you from having to remember to close the file when you're done with it.

Title: Amateur Coder File Testing

Body:
I am working on a project and have a great idea.
This is a very simple question and I've done this before, but it doesn't seem to be working.
In my idle, when I type:

f = open('a.txt', 'w')
f.write('hi')

I get an output of 2.
It doesn't make sense to me beyond the fact that hi has a length of two... I want to add 'hi' to my file!!

Body:
Consider using the context handler when dealing with fileIO. By using the with statement as shown below, the file will automatically close when the codeblock is finished executing.

with open('a.txt', 'w') as f:
    f.write('hi')

This saves you from having to remember to close the file when you're done with it.


问:
Node JS - Elastic Beanstalk AWS - allow write access
I have a NodeJS application i am deploying to AWS Elastic Beanstalk, which needs to be able to write to some JSON files which is in the applications directories.

This is currently working locally but not when i deploy to AWS because clearly write permissions are not there.

Can you please let me know what i need to add to EBEXTENSIONS and how, to allow write access with a NodeJS Elastic Beanstalk app

Thanks

答:
First of all, you shouldn't store anything important on AWS Elastic Beanstalk servers as they can get terminated/rolled-over depending on the requirement and you will lose the files.

AWS EB should always be stateless.

But if you want to write some temporary files, you already have permissions in the app directory.

But if you want to change permissions of some other directory, say /var/log

you can do this in container_commands

```<code>container_commands:
    change_permissions:
        command: chmod 750 /var/log
</code>```

Body:
First of all, you shouldn't store anything important on AWS Elastic Beanstalk servers as they can get terminated/rolled-over depending on the requirement and you will lose the files.

AWS EB should always be stateless.

But if you want to write some temporary files, you already have permissions in the app directory.

But if you want to change permissions of some other directory, say /var/log

you can do this in container_commands

container_commands:
    change_permissions:
        command: chmod 750 /var/log


问:
URL just isn't displaying what I want

Possible Duplicate:

  How can I accomplish this type of URL in ASP.Net MVC2?

I want to create HTML links like:

```<code>/Auctions/Clothes
/Auctions/Electronics
/Auctions/Real Estate
</code>```

Here's how I'm constructing the links:

```<code><li>@Html.ActionLink("Ropa", "Index", "Anuncios", new { category = "Ropa" }, new { })</li>
<li>@Html.ActionLink("Libros", "Index", "Anuncios", new { category = "Libros" }, new { })</li>
</code>```

The problems is the links are being used like this:

```<code>http://localhost:8589/Anuncios?category=Libros
</code>```

I want my URLS to be nice looking, as such I'd like the above to be like:

```<code>/Anuncios/Libros
</code>```

Any suggestions on how to fix this? Here's the ActionResult method, and to clarify, this is doing exactly what I want it to do. It works, except the URL is horrible.

```<code>public ActionResult Index(string category)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions().Where(a => a.Subcategory.Category.Name == category);
    return View(auctions);
}
</code>```

答:
You need to add some routes so MVC knows how you would prefer the links to look like. Its not like it can read your thoughts, or make coffee.</p>

```<code>public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        "Anuncios",                 // Route name
        "Anuncios/{category}",      // URL with parameters
        new { category = "Index" }  // Parameter defaults
    );
}
</code>```

OwnerDisplayName: delete

Title: URL just isn't displaying what I want

Body:
Possible Duplicate:

  How can I accomplish this type of URL in ASP.Net MVC2?

I want to create HTML links like:

/Auctions/Clothes
/Auctions/Electronics
/Auctions/Real Estate

Here's how I'm constructing the links:

@Html.ActionLink("Ropa", "Index", "Anuncios", new { category = "Ropa" }, new { })

@Html.ActionLink("Libros", "Index", "Anuncios", new { category = "Libros" }, new { })

The problems is the links are being used like this:

http://localhost:8589/Anuncios?category=Libros

I want my URLS to be nice looking, as such I'd like the above to be like:

/Anuncios/Libros

Any suggestions on how to fix this? Here's the ActionResult method, and to clarify, this is doing exactly what I want it to do. It works, except the URL is horrible.

public ActionResult Index(string category)
{
    AuctionRepository auctionRepo = new AuctionRepository();
    var auctions = auctionRepo.FindAllAuctions().Where(a => a.Subcategory.Category.Name == category);
    return View(auctions);
}

Body:
You need to add some routes so MVC knows how you would prefer the links to look like. Its not like it can read your thoughts, or make coffee.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        "Anuncios",                 // Route name
        "Anuncios/{category}",      // URL with parameters
        new { category = "Index" }  // Parameter defaults
    );
}


问:
Need understanding on "Changes in abstract class will not break code for all inheriting classes"

Please provide your insights, or correct me,  on what is being referred in the statement:
"when we change code in abstract class all inheriting classes will have this changes. But on changing code in Interface, it breaks the code for all the implementing classes"

When I tried, as below, both of them, abstract class and interface, breaks the code.

I tried creating an abstract class A with method 1(concrete), method 2 (abstract), and created a class B extending class A .
When I try to add another method 3 (abstract) in class A, I see the code breaks in class B (an error - must implement the inherited abstract method).

What could be the main objective to have "only abstract methods in an abstract class" and "only concrete methods in an abstract class"?

答:
Need understanding on “Changes in abstract class will not break code
  for all inheriting classes”

There's no dichotomy.

With inheritance in Java, a subclass (or implementing class) gets at least two things:

A contract (specified by its API)

Implementation (formerly available only with abstract classes, but now also available as default interface methods in Java 8+)

It is typically true that an API developer is free to change the implementation provided by an abstract class ONLY AS LONG AS such changes do not change the contract specified by its API.  If this happens, then yes, changing the implementation will cause clients to break.

At no point, however, can an API developer change the contract -- whether it has been specified by an abstract class or an interface -- and not expect clients to break.  In Java 7 and earlier, interfaces could only express the contract with abstract method signatures ... so changing any of these would break clients.

Even so, even in Java 7, an abstract class author could evolve method implementations without penalty (even add new methods) but only if the original contract specified by the abstract class was still valid.


问:
controlling order of operations in async redux operations with .then
I'm using react with redux and thunk middleware. I want to do one asynchronous request, and then have a bunch of actions .then'd off of it occur in synchronous order.  I am not managing to achieve it.

Here are two ways I've tried:

```<code>addStudent(name, campusId = undefined, view = 'students') {
        const creatingStudent = axios.post('/api/student', { name: name, campusId: campusId })
            .then(res => {
                return res.data
            })
            .then(student => {
               return store.dispatch(createStudent(student))
            })
            .then(()=> {return store.dispatch(getStudents())})
            .then(()=> {return store.dispatch(changeView(view))})
            .catch(err => console.log(err))

addStudent(name, campusId = undefined, view = 'students') {
         const creatingStudent = axios.post('/api/student', { name: name, campusId: campusId })
             .then(res => {
                 return res.data
             })
             .then(student => {
                store.dispatch(createStudent(student))
               store.dispatch(getStudents())
                store.dispatch(changeView(view))
             })
             .catch(err => console.log(err))
     }
</code>```

I want the order:
1) the axios request
2) dispatch createStudent
3) dispatch getStudents
4) dispatch changeView

But I have logging middleware installed and 3 and 4 are always reversed.  Also, particularly with the second option, I occasionally get a fatal error that I think is caused by some other reversal of order, but I can't tell exactly what order, since the application is crashing before it logs.

I also tried chaining the calls to dispatch off of each other, but that doesn't seem to work, probably because they are not returning promises.

Here's my getStudents action creator:

```<code>export const getStudents = () => {
   return dispatch => {
    axios.get('/api/students')
      .then(response => {
        return dispatch(receiveStudents(response.data));
      });
  }
};
</code>```

It makes sense that it is taking a little bit longer since it's hitting the server, but how can I .then off it if store.dispatch doesn't return a promise? What's the right way to do this?

EDIT: This was originally not clearly stated.  I should have been more explicit that my frustration was that changeViews() was dispatched before receiveStudents(), not, as I implied, that changeViews() was dispatched before getStudents().  I did not know when getStudents() was being dispatched.

答:
I'm answering my own question.  One aspect of the way I asked the question was misleading.  I wanted to change the View after I had my students, and I was frustrated that I saw CHANGE_VIEW and then RECEIVE_STUDENTS in my logging middleware.  But that's not the same as saying 3 and 4 are reversed. In fact, 3 and 4 were dispatched in order. I now understand that because getStudents() is itself an asynchronous operation, dispatching it will resolve before the asynchronous action completes.  Thus, even though getStudents() and changeView() were dispatched in order, receiveStudents() was dispatched after changeView().  In my case, if I wanted changeView() to be dispatched after receiveStudents(), I needed to .then dispatch(changeView()) within getStudents().

Here's refactored code that accomplishes what I wanted:

```<code>addStudent(student, view = 'students') {
    const creatingStudent = axios.post('/api/student', student)
        .then(res => res.data)
        .then(student => store.dispatch(createStudent(student)))
        .then(()=> store.dispatch(getStudents(view)))
        .catch(err => console.log(err))
}

const getStudents = (view) => {
   return dispatch => {
     axios.get('/api/students')
       .then(res => dispatch(receiveStudents(res.data)))
       .then(()=>dispatch(changeView(view)))
     }
   }
</code>```

Body:
I'm using react with redux and thunk middleware. I want to do one asynchronous request, and then have a bunch of actions .then'd off of it occur in synchronous order.  I am not managing to achieve it.

Here are two ways I've tried:

addStudent(name, campusId = undefined, view = 'students') {
        const creatingStudent = axios.post('/api/student', { name: name, campusId: campusId })
            .then(res => {
                return res.data
            })
            .then(student => {
               return store.dispatch(createStudent(student))
            })
            .then(()=> {return store.dispatch(getStudents())})
            .then(()=> {return store.dispatch(changeView(view))})
            .catch(err => console.log(err))

addStudent(name, campusId = undefined, view = 'students') {
         const creatingStudent = axios.post('/api/student', { name: name, campusId: campusId })
             .then(res => {
                 return res.data
             })
             .then(student => {
                store.dispatch(createStudent(student))
               store.dispatch(getStudents())
                store.dispatch(changeView(view))
             })
             .catch(err => console.log(err))
     }

I want the order:
1) the axios request
2) dispatch createStudent
3) dispatch getStudents
4) dispatch changeView

But I have logging middleware installed and 3 and 4 are always reversed.  Also, particularly with the second option, I occasionally get a fatal error that I think is caused by some other reversal of order, but I can't tell exactly what order, since the application is crashing before it logs.

I also tried chaining the calls to dispatch off of each other, but that doesn't seem to work, probably because they are not returning promises.

Here's my getStudents action creator:

export const getStudents = () => {
   return dispatch => {
    axios.get('/api/students')
      .then(response => {
        return dispatch(receiveStudents(response.data));
      });
  }
};

It makes sense that it is taking a little bit longer since it's hitting the server, but how can I .then off it if store.dispatch doesn't return a promise? What's the right way to do this?

EDIT: This was originally not clearly stated.  I should have been more explicit that my frustration was that changeViews() was dispatched before receiveStudents(), not, as I implied, that changeViews() was dispatched before getStudents().  I did not know when getStudents() was being dispatched.

Body:
I'm answering my own question.  One aspect of the way I asked the question was misleading.  I wanted to change the View after I had my students, and I was frustrated that I saw CHANGE_VIEW and then RECEIVE_STUDENTS in my logging middleware.  But that's not the same as saying 3 and 4 are reversed. In fact, 3 and 4 were dispatched in order. I now understand that because getStudents() is itself an asynchronous operation, dispatching it will resolve before the asynchronous action completes.  Thus, even though getStudents() and changeView() were dispatched in order, receiveStudents() was dispatched after changeView().  In my case, if I wanted changeView() to be dispatched after receiveStudents(), I needed to .then dispatch(changeView()) within getStudents().

Here's refactored code that accomplishes what I wanted:

addStudent(student, view = 'students') {
    const creatingStudent = axios.post('/api/student', student)
        .then(res => res.data)
        .then(student => store.dispatch(createStudent(student)))
        .then(()=> store.dispatch(getStudents(view)))
        .catch(err => console.log(err))
}

const getStudents = (view) => {
   return dispatch => {
     axios.get('/api/students')
       .then(res => dispatch(receiveStudents(res.data)))
       .then(()=>dispatch(changeView(view)))
     }
   }


问:
Using forall within recursive Function definition
I'm trying to use Function to define a recursive definition using a measure, and I'm getting the error:

```<code>Error: find_call_occs : Prod
</code>```

I'm posting the whole source code at the bottom, but my function is

```<code>Function kripke_sat (M : kripke) (s : U) (p : formula) {measure size p}: Prop :=
match p with
| Proposition p'  => L M (s)(p')
| Not p' => ~ kripke_sat M s p'
| And p' p''   => kripke_sat M s p' /\ kripke_sat M s p''
| Or p' p''  => kripke_sat M s p' \/ kripke_sat M s p''
| Implies p' p''  => ~kripke_sat M s p' \/  kripke_sat M s p''
| Knows a p' =>  forall t, ~(K M a) s t \/ kripke_sat M t p'
| EvKnows p' => forall i, kripke_sat M s (Knows i p' )
end.
</code>```

I know the problem is due to the foralls: if I replace them with True, it works.  I
also know I get the same error if my right-hand-side uses implications (->).
Fixpoint works with foralls, but doesn't allow me to define a measure.

Any advice?

As promised, my complete code is:

```<code>Module Belief.

Require Import Arith.EqNat.
Require Import Arith.Gt.
Require Import Arith.Plus.
Require Import Arith.Le.
Require Import Arith.Lt.
Require Import Logic.
Require Import Logic.Classical_Prop.
Require Import Init.Datatypes.

Require Import funind.Recdef.

(* Formalization of a variant of a logic of knowledge, as given in Halpern 1995 *)

Section Kripke.

  Variable n : nat.
  (* Universe of "worlds" *)
  Definition U := nat.
  (* Universe of Principals *)
  Definition P := nat.
  (* Universe of Atomic propositions *)
  Definition A := nat.

  Inductive prop : Type :=
  | Atomic : A -> prop.

  Definition beq_prop (p1 p2 :prop) : bool :=
    match (p1,p2) with
      | (Atomic p1', Atomic p2') => beq_nat p1' p2'
    end.

  Inductive actor : Type :=
  | Id : P -> actor.

  Definition beq_actor (a1 a2: actor) : bool :=
    match (a1,a2) with
      | (Id a1', Id a2') => beq_nat a1' a2'
    end.

  Inductive formula : Type :=
  | Proposition : prop -> formula
  | Not : formula -> formula
  | And :  formula  -> formula -> formula
  | Or :  formula -> formula -> formula
  | Implies :  formula -> formula ->formula
  | Knows : actor -> formula -> formula
  | EvKnows :  formula -> formula (*me*)
    .

  Inductive con : Type :=
  | empty : con
  | ext : con -> prop -> con.

  Notation " C # P " := (ext C P) (at level 30).

  Require Import Relations.

  Record kripke : Type := mkKripke {
    K : actor -> relation U;
    K_equiv: forall y, equivalence _ (K y);
    L : U -> (prop -> Prop)
  }.

Fixpoint max (a b: nat) : nat :=
   match a, b with
   | 0, _ => a
   | _, 0 => b
   | S(a'), S(b') => 1 + max a' b'
end.

Fixpoint length (p: formula) : nat :=
  match p with
     | Proposition p' => 1
     | Not p' => 1 + length(p')
     | And p' p'' => 1 + max (length p') (length p'')
     | Or p' p''  => 1 + max (length p') (length p'')
     | Implies p' p'' => 1 + max  (length p') (length p'')
     | Knows a p'  => 1 + length(p')
     | EvKnows p' => 1 + length(p')
end.

Fixpoint numKnows (p: formula): nat :=
  match p with
 | Proposition p' => 0
 | Not p' => 0 + numKnows(p')
 | And p' p'' => 0 + max (numKnows p') (numKnows p'')
 | Or p' p''  => 0 + max (numKnows p') (numKnows p'')
 | Implies p' p'' => 0 + max  (numKnows p') (numKnows p'')
 | Knows a p'  => 0 + numKnows(p')
 | EvKnows p' => 1 + numKnows(p')
end.

Definition size (p: formula): nat :=
(numKnows p) + (length p).

Definition twice (n: nat) : nat :=
n + n.

Theorem duh: forall a: nat, 1 + a > a.
Proof.   induction a. apply gt_Sn_O.
apply gt_n_S in IHa. unfold plus in *. apply IHa. Qed.

Theorem eq_lt_lt: forall (a b c d: nat), a = b -> c<d -> a+ c< b+d.
Proof. intros. apply plus_le_lt_compat.
apply eq_nat_elim with (n:=a) (m := b). apply le_refl.
apply eq_nat_is_eq. apply H.  apply H0. Qed.

Function kripke_sat (M : kripke) (s : U) (p : formula) {measure size p}: Prop :=
  match p with
| Proposition p'  => L M (s)(p')
| Not p' => ~ kripke_sat M s p'
| And p' p''   => kripke_sat M s p' /\ kripke_sat M s p''
| Or p' p''  => kripke_sat M s p' \/ kripke_sat M s p''
| Implies p' p''  => ~kripke_sat M s p' \/  kripke_sat M s p''
| Knows a p' =>   forall t, ~(K M a) s t \/ kripke_sat M t p'
| EvKnows p' =>  forall i, kripke_sat M s (Knows i p' )
 end.
</code>```

答:
The "Function" plugin is still very experimental.
In the documentation you can find

term0 must be build as a pure pattern-matching tree (match...with) with λ-abstractions and applications only at the end of each branch.

But I have to agree that this error message is far from being explicit
(normally such error messages should either end with "Please report" or be more user
friendly, I consider this as a bug). It means foralls are not allowed in the body of a Function (I don't know whether or not there are theoretical reasons for this behavior).

So you need to do your definition "by hand" without the help of
Function. Here is a small example you can adapt for your development.
Good luck !

```<code>
Inductive form : Set :=
  | T : form
  | K : nat -> form -> form
  | eK : form -> form.

Fixpoint size (f : form) : nat := match f with
  | T => 1
  | K _ f => S (size f)
  | eK f => S (S (size f))
end.

Require Import Wf.
Require Import Wf_nat.

Definition R x y := size x < size y.
Lemma R_wf : well_founded R.
  apply well_founded_ltof.
Qed.

Lemma lem1 :
  forall x n, R x (K n x).
unfold R; intuition.
Qed.

Lemma lem2 :
   forall x n, R (K n x) (eK x).
unfold R; intuition.
Qed.

Definition interpret : form -> Prop.
(* we use the well_founded_induction instead of Function *)
refine (well_founded_induction_type R_wf (fun _ => Prop) (fun x f => _)).
destruct x.
exact True.                                     (* ⟦T⟧ ≡ True *)
exact (n = 2 /\ f x (lem1 x n)).                (* ⟦K n F⟧ ≡ (n = 2) ∧ ⟦F⟧ *)
exact (forall n:nat, f (K n x) (lem2 x n)).     (* ⟦eK F⟧ ≡ ∀n:nat,⟦K n F⟧ *)
Defined.
</code>```

PS: I am going to fill a bug report with the following simpler version of your code.

```<code>  Require Import Recdef.

  Inductive I : Set :=
  | C  : I.

  Definition m (_ : I) := 0.

  Function f (x : I)  {measure m x} : Type := match x with
  | C => nat -> nat end.
</code>```

Body:
I'm trying to use Function to define a recursive definition using a measure, and I'm getting the error:

Error: find_call_occs : Prod

I'm posting the whole source code at the bottom, but my function is

Function kripke_sat (M : kripke) (s : U) (p : formula) {measure size p}: Prop :=
match p with
| Proposition p'  => L M (s)(p')
| Not p' => ~ kripke_sat M s p'
| And p' p''   => kripke_sat M s p' /\ kripke_sat M s p''
| Or p' p''  => kripke_sat M s p' \/ kripke_sat M s p''
| Implies p' p''  => ~kripke_sat M s p' \/  kripke_sat M s p''
| Knows a p' =>  forall t, ~(K M a) s t \/ kripke_sat M t p'
| EvKnows p' => forall i, kripke_sat M s (Knows i p' )
end.

I know the problem is due to the foralls: if I replace them with True, it works.  I
also know I get the same error if my right-hand-side uses implications (->).
Fixpoint works with foralls, but doesn't allow me to define a measure.

Any advice?

As promised, my complete code is:

Module Belief.

Require Import Arith.EqNat.
Require Import Arith.Gt.
Require Import Arith.Plus.
Require Import Arith.Le.
Require Import Arith.Lt.
Require Import Logic.
Require Import Logic.Classical_Prop.
Require Import Init.Datatypes.

Require Import funind.Recdef.

(* Formalization of a variant of a logic of knowledge, as given in Halpern 1995 *)

Section Kripke.

  Variable n : nat.
  (* Universe of "worlds" *)
  Definition U := nat.
  (* Universe of Principals *)
  Definition P := nat.
  (* Universe of Atomic propositions *)
  Definition A := nat.

  Inductive prop : Type :=
  | Atomic : A -> prop.

  Definition beq_prop (p1 p2 :prop) : bool :=
    match (p1,p2) with
      | (Atomic p1', Atomic p2') => beq_nat p1' p2'
    end.

  Inductive actor : Type :=
  | Id : P -> actor.

  Definition beq_actor (a1 a2: actor) : bool :=
    match (a1,a2) with
      | (Id a1', Id a2') => beq_nat a1' a2'
    end.

  Inductive formula : Type :=
  | Proposition : prop -> formula
  | Not : formula -> formula
  | And :  formula  -> formula -> formula
  | Or :  formula -> formula -> formula
  | Implies :  formula -> formula ->formula
  | Knows : actor -> formula -> formula
  | EvKnows :  formula -> formula (*me*)
    .

  Inductive con : Type :=
  | empty : con
  | ext : con -> prop -> con.

  Notation " C # P " := (ext C P) (at level 30).

  Require Import Relations.

  Record kripke : Type := mkKripke {
    K : actor -> relation U;
    K_equiv: forall y, equivalence _ (K y);
    L : U -> (prop -> Prop)
  }.

Fixpoint max (a b: nat) : nat :=
   match a, b with
   | 0, _ => a
   | _, 0 => b
   | S(a'), S(b') => 1 + max a' b'
end.

Fixpoint length (p: formula) : nat :=
  match p with
     | Proposition p' => 1
     | Not p' => 1 + length(p')
     | And p' p'' => 1 + max (length p') (length p'')
     | Or p' p''  => 1 + max (length p') (length p'')
     | Implies p' p'' => 1 + max  (length p') (length p'')
     | Knows a p'  => 1 + length(p')
     | EvKnows p' => 1 + length(p')
end.

Fixpoint numKnows (p: formula): nat :=
  match p with
 | Proposition p' => 0
 | Not p' => 0 + numKnows(p')
 | And p' p'' => 0 + max (numKnows p') (numKnows p'')
 | Or p' p''  => 0 + max (numKnows p') (numKnows p'')
 | Implies p' p'' => 0 + max  (numKnows p') (numKnows p'')
 | Knows a p'  => 0 + numKnows(p')
 | EvKnows p' => 1 + numKnows(p')
end.

Definition size (p: formula): nat :=
(numKnows p) + (length p).

Definition twice (n: nat) : nat :=
n + n.

Theorem duh: forall a: nat, 1 + a > a.
Proof.   induction a. apply gt_Sn_O.
apply gt_n_S in IHa. unfold plus in *. apply IHa. Qed.

Theorem eq_lt_lt: forall (a b c d: nat), a = b -> c<d -> a+ c L M (s)(p')
| Not p' => ~ kripke_sat M s p'
| And p' p''   => kripke_sat M s p' /\ kripke_sat M s p''
| Or p' p''  => kripke_sat M s p' \/ kripke_sat M s p''
| Implies p' p''  => ~kripke_sat M s p' \/  kripke_sat M s p''
| Knows a p' =>   forall t, ~(K M a) s t \/ kripke_sat M t p'
| EvKnows p' =>  forall i, kripke_sat M s (Knows i p' )
 end.

Body:
The "Function" plugin is still very experimental.
In the documentation you can find

term0 must be build as a pure pattern-matching tree (match...with) with λ-abstractions and applications only at the end of each branch.

But I have to agree that this error message is far from being explicit
(normally such error messages should either end with "Please report" or be more user
friendly, I consider this as a bug). It means foralls are not allowed in the body of a Function (I don't know whether or not there are theoretical reasons for this behavior).

So you need to do your definition "by hand" without the help of
Function. Here is a small example you can adapt for your development.
Good luck !

Inductive form : Set :=
  | T : form
  | K : nat -> form -> form
  | eK : form -> form.

Fixpoint size (f : form) : nat := match f with
  | T => 1
  | K _ f => S (size f)
  | eK f => S (S (size f))
end.

Require Import Wf.
Require Import Wf_nat.

Definition R x y := size x < size y.
Lemma R_wf : well_founded R.
  apply well_founded_ltof.
Qed.

Lemma lem1 :
  forall x n, R x (K n x).
unfold R; intuition.
Qed.

Lemma lem2 :
   forall x n, R (K n x) (eK x).
unfold R; intuition.
Qed.

Definition interpret : form -> Prop.
(* we use the well_founded_induction instead of Function *)
refine (well_founded_induction_type R_wf (fun _ => Prop) (fun x f => _)).
destruct x.
exact True.                                     (* ⟦T⟧ ≡ True *)
exact (n = 2 /\ f x (lem1 x n)).                (* ⟦K n F⟧ ≡ (n = 2) ∧ ⟦F⟧ *)
exact (forall n:nat, f (K n x) (lem2 x n)).     (* ⟦eK F⟧ ≡ ∀n:nat,⟦K n F⟧ *)
Defined.

PS: I am going to fill a bug report with the following simpler version of your code.

  Require Import Recdef.

  Inductive I : Set :=
  | C  : I.

  Definition m (_ : I) := 0.

  Function f (x : I)  {measure m x} : Type := match x with
  | C => nat -> nat end.


问:
Error while compiling the project
I'm getting this error everytime I try to compile my program.

Some project features, such as full solution analysis for the failed
  project and projects that depend on it, have been disabled.

The "DebugType" parameter is not supported by the "XamlCTask" task.
  Verify the parameter exists on the task, and it is a settable public
  instance property.

The "XamlCTask" task could not be initialized with its input
  parameters.

It's an Android Project on Xamarin.

Thanks to everyone In advance.

答:
This happened to me when I had two instances of VS 2017 running. First instance had Xamarin default project with old Nuget for Xamarin. Ran debug onto Mac build server.

Then started up second instance of VS with Xamarin project on latest Nuget for Xamarin. Both instances were connected to MAC build server. When I tried to build I would get this error.

Stoped both instances of VS and started just one. Loaded my project with the latest Xamarin Nuget - All builds OK now.

Title: Error while compiling the project


问:
ASP.NET - accessing database table in authentication attribute
I am building ASP.NET Web API 2 (MVC 6) application using this tutorial: http://bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/

Everything went fine, but now I want to access the ApplicationsUsers table in HMACAuthenticationAttribute. How can I do that? Is making the allowedApps dictionary public static, and adding every freshly registered user to this dictionary the only possible solution? How can I access dbcontext here?

For people who do not want to read that tutorial: I need to access dbcontext in IAuthenticationFilter. How to do that?

答:
You can create a variable of your DbContext on the HMACAuthenticationAttribute class.

I would not recommend to let the allowedApps as a static variable if your app is going to create a lot of app Ids. It could be public variable. But i would recommend to make addition to the dictionary available through a separate method, with that you could gain more control over what is being inserted into the allowedApps


问:
Caching layer for different microservices
We have different microservices which makes duplicate calls to internal and external services. We need to cache these calls between services to improve latency. We are thinking of introducing an API gateway whose major aim would be caching the data between services.
Some other objectives are -

i) Would be calling different micro-services to aggregate their response.

ii) Would also be avoiding multiple calls to external services across micro services.

iii) Would be taking care of cache miss & hit for external API calls.

iv) High throughput, performance and low latency.

We have vert.x based tech stack.
What would be the best way to implement such a system. I had following questions -

1) Implement it as a library or a service ?

2) Which data store to be used ( we are considering Redis/Hazelcast) ?

3) Can libraries such as Varnish/Squid/Nginx help here ?

4) How to handle cache invalidation ?

答:
I think you have many options:

Redis

Redis Sentinel (support clustering)

ETCD (from CoreOS) : Support Clustering

Apache Geode

Aerospike : Support clustering even between data centers

and many commercial products like SAP HANA.

note : Aerospike is free but for clustering between data centers I think you should pay.

I myself have used ETCD for same scenarios (thanks to Brandon Philips).


问:
Accessing members of structs in a list in C
I have been working through the exercises in K&R on my quest to learn C, and I've hit a strange problem. I wrote a program to count words, characters, and lines in a file, then draw a histogram displaying the count for each. Everything worked well until I tried to make my code a little more reusable with a struct. My struct is as follows:

```<code>struct category {
    char *name;
    int namelen;
    int count;
};
</code>```

and it's values are assigned by a constructor function:

```<code>struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
return cat;
}
</code>```

and finally I have a list comprised of all the categories, as follows:

```<code>struct category catList[] = {words, lines, characters};
</code>```

when I access the members of these structs by name, I have no issues. But if I try to access them in a loop, via catList[i].member, the member count always returns 0. the other two members, name and namelen, behave correctly withing the loop, and accessing count from outside the loops returns correctly. If anyone would be willing to help me understand what's going on I would greatly appreciate it.

if it is necessary, here is my full program:

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

int get_width(char* word) {
    return 15 - strlen(word);
}

struct category {
    char *name;
    int namelen;
    int count;
};

struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
    return cat;
}

int main () {
    int c;
    int inside_word;
    int i;
    int p;
    struct category words = createCat("words");
    struct category lines = createCat("lines");
    struct category characters = createCat("characters");

    struct category catList[] = {words, lines, characters};

    while ((c = getchar()) != EOF) {
        characters.count++;
        if (c != '\n' && c != ' ' && c != '\t') {
            putchar(c);
            if (!inside_word) {
                inside_word = 1;
                words.count++;
            }
        }

        else {
            if (inside_word)
                printf("\n");
            inside_word = 0;
            if (c == '\n')
                lines.count++;
        }
    }
    printf("\n%d words, %d lines, %d characters\n",
            words.count, lines.count, characters.count);

    for (i = 0; i < 3; i++) {
        printf("%s:%*s", catList[i].name, catList[i].namelen, " ");
        printf("%d", catList[i].count);
        for ( p = 0; p < catList[p].count; p++)
            printf("#");
        printf("\n");

    }
    return 0;
}
</code>```

答:
When you do this:

```<code>struct category catList[] = {words, lines, characters};
</code>```

You are copying the 3 structs' data into the catList. So when you update the 3 structs by their names, the ones in the catList are different copies and would not be updated.

To resolve this, I would recommend using pointer types. There are two ways of doing this.

You can return a pointer in the createCat method.

```<code>struct category* createCat(char *name) {
    struct category* cat = (struct category*) malloc(sizeof(struct category));
    //...
    return cat;
}
</code>```

From this point on, always use pointer for storing. This is quite commonly used.

You can store the pointer in the array catList:

```<code>struct category *catList[] = {&words, &lines, &characters};
</code>```

and when you use them in the loop, use like:

```<code>catList[i]->count++;
</code>```

Body:
I have been working through the exercises in K&R on my quest to learn C, and I've hit a strange problem. I wrote a program to count words, characters, and lines in a file, then draw a histogram displaying the count for each. Everything worked well until I tried to make my code a little more reusable with a struct. My struct is as follows:

struct category {
    char *name;
    int namelen;
    int count;
};

and it's values are assigned by a constructor function:

struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
return cat;
}

and finally I have a list comprised of all the categories, as follows:

struct category catList[] = {words, lines, characters};

when I access the members of these structs by name, I have no issues. But if I try to access them in a loop, via catList[i].member, the member count always returns 0. the other two members, name and namelen, behave correctly withing the loop, and accessing count from outside the loops returns correctly. If anyone would be willing to help me understand what's going on I would greatly appreciate it.

if it is necessary, here is my full program:

#include <stdio.h>
#include <string.h>

int get_width(char* word) {
    return 15 - strlen(word);
}

struct category {
    char *name;
    int namelen;
    int count;
};

struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
    return cat;
}

int main () {
    int c;
    int inside_word;
    int i;
    int p;
    struct category words = createCat("words");
    struct category lines = createCat("lines");
    struct category characters = createCat("characters");

    struct category catList[] = {words, lines, characters};

    while ((c = getchar()) != EOF) {
        characters.count++;
        if (c != '\n' && c != ' ' && c != '\t') {
            putchar(c);
            if (!inside_word) {
                inside_word = 1;
                words.count++;
            }
        }

        else {
            if (inside_word)
                printf("\n");
            inside_word = 0;
            if (c == '\n')
                lines.count++;
        }
    }
    printf("\n%d words, %d lines, %d characters\n",
            words.count, lines.count, characters.count);

    for (i = 0; i < 3; i++) {
        printf("%s:%*s", catList[i].name, catList[i].namelen, " ");
        printf("%d", catList[i].count);
        for ( p = 0; p < catList[p].count; p++)
            printf("#");
        printf("\n");

    }
    return 0;
}

Body:
When you do this:

struct category catList[] = {words, lines, characters};

You are copying the 3 structs' data into the catList. So when you update the 3 structs by their names, the ones in the catList are different copies and would not be updated.

To resolve this, I would recommend using pointer types. There are two ways of doing this.

You can return a pointer in the createCat method.

struct category* createCat(char *name) {
    struct category* cat = (struct category*) malloc(sizeof(struct category));
    //...
    return cat;
}

From this point on, always use pointer for storing. This is quite commonly used.

You can store the pointer in the array catList:

struct category *catList[] = {&words, &lines, &characters};

and when you use them in the loop, use like:

catList[i]->count++;


问:
jQuery-UI - .append from .droppable into p.array (almost there!)
The site is using .draggable and .droppable UI to append the players ID from the span tag. This is appended into the following paragraphs:

```<code>           <p class="array goals"></p>
           <p class="array assist"></p>
           <p class="array yellow"></p>
           <p class="array red"></p>
           <p class="array cap"></p>
</code>```

From these divs

```<code>           <h2>DROP PLAYERS INTO AREAS BELOW</h2>
           <p>Goals</p>
           <div class="droppable goals"><p></p></div>
           <p>Assists</p>
           <div class="droppable assist"><p></p></div>
           <p>Yellow card</p>
           <div class="droppable yellow"><p></p></div>
           <p>Red card</p>
           <div class="droppable red"><p></p></div>
           <p>Captain</p>
           <div class="droppable cap"><p></p></div>
</code>```

By this javascript (cut down to needed code)

```<code>    <script type="text/javascript">
$(function() {
    $(".droppable").droppable({
        activeClass: 'dragactive',
        hoverClass: 'drophover',
        drop: function(event, ui) {
            $(".array").append(ui.draggable.children("span").text() + ', ')
        }
    });

});
</script>
</code>```

I need the dropped items to get into the right p.array based on the second class. Now, the result from .droppable is appended to EVERY array class.

This is an example of the draggable player's mark-up:

```<code><div class="drakt spiller draggable">
   <span style="visibility: hidden;">58</span>
   <div class="draktnummer">17</div><p>Traoré</p>
</div>
</code>```

Hope you can help me with this.

Thanks in advance.

答:
Something like this might work:

```<code>drop: function(event, ui) {
  // clz might need trimming
  var clz = $(this)[0].className.replace("droppable", "");
  $(".array." + clz).append(ui.draggable.children("span").text())
}
</code>```

Another idea is to use data attributes. If you can alter the PHP to produce HTML that looks like this:

```<code><div class="droppable goals" data-droptype="goals"><p></p></div>
</code>```

...this sets a property on the div accessible via jQuery's .data method. So the above function then becomes:

```<code>drop: function(event, ui) {
  $(".array." + $(this).data('droptype')).append(ui.draggable.children("span").text())
}
</code>```

Body:
The site is using .draggable and .droppable UI to append the players ID from the span tag. This is appended into the following paragraphs:

From these divs

DROP PLAYERS INTO AREAS BELOW

Goals

Assists

Yellow card

Red card

Captain

By this javascript (cut down to needed code)

I need the dropped items to get into the right p.array based on the second class. Now, the result from .droppable is appended to EVERY array class.

This is an example of the draggable player's mark-up:

   58

17

Traoré

Hope you can help me with this.

Thanks in advance.

Body:
Something like this might work:

drop: function(event, ui) {
  // clz might need trimming
  var clz = $(this)[0].className.replace("droppable", "");
  $(".array." + clz).append(ui.draggable.children("span").text())
}

Another idea is to use data attributes. If you can alter the PHP to produce HTML that looks like this:

<div class="droppable goals" data-droptype="goals"><p></p></div>

...this sets a property on the div accessible via jQuery's .data method. So the above function then becomes:

drop: function(event, ui) {
  $(".array." + $(this).data('droptype')).append(ui.draggable.children("span").text())
}


问:
Problems accessing Connect function value in another Component in a React-Redux App
I've set up Redux in my React app, however I don't get any data passed when I use this.props to access the data in another component in a separate file. My action is being executed and it passes the data I want.
This is my actions.js:

```<code>export const ADD_CART = 'ADD_CART';

export function addCart(item){
    return {
        type: ADD_CART,
        payload: item
    }
};
</code>```

My reducer.js is:

```<code>import {ADD_CART} from './actions';

export default Reducer;

function Reducer(state, action){
    switch(action.type){
        case ADD_CART:
            return {
                ...state,
                cart: action.payload
            }
    };
}
</code>```

My action creator contains cart, which is what I want to pass to the component:

```<code>...
class WebShop extends Component {
    ...

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
    }

   ...

    render() {
        return (
            ..
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
   return {
      cartItem: state.reducer,
   }
}

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);
</code>```

When I try to access cart in another file and component like so:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';

export default class Cart extends Component {
    render() {
        console.log(this.props.cart);
        return(
            <div className= "Webcart" id="Webcart"></div>
        );
    }
}
</code>```

This is my store.js:

```<code>import { createStore, applyMiddleware } from 'redux';
import  reducer  from './reducers';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';

var initialState = {
  cart:"medium",
  data: [],
  url: "/api/comments",
  pollInterval: 2000
}

const store = createStore(
  reducer,
  applyMiddleware(
    createLogger(),
    thunkMiddleware
  )
);
export default store;
</code>```

My Provider is in my app.js file:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import {Provider} from 'react-redux';
import store from '../store';

import App from 'views/App';
import Home from 'views/Home';
import About from 'views/About';
import Cart from 'views/webcart';

console.log(store);
ReactDOM.render(
    <Provider store={store}>
        <Router history={ hashHistory }>
            <Route path='/' component={ App }>
                <IndexRoute component={ Home } />
                <Route path='about' component={ About } />
                <Route path='Cart' component={ Cart } />
            </Route>
        </Router>
    </Provider>,
    document.getElementById('app') // eslint-disable-line
);
</code>```

After updating my code to use mapStateToProps now I get the error Uncaught TypeError: Cannot read property 'Reducer' of undefined. Why I'm I getting this if Reducer should be accessed by the API?

答:
Move your initial state from the store.js to your reducer.js and pass it to the reducer function to have the state defaulted to, like this

```<code>const initialState = {
  cart: {}, // change this to object to hold that cart your're
           //passing or an array to hold multiple cart, in which
           // case you will need to handle the return of your
           // state differently in your reducer
  data: [],
  url: "/api/comments",
  pollInterval: 2000
};

function Reducer(state = initialState, action){
switch(action.type){
    case ADD_CART:
        return {
            ...state,
            cart: action.payload
        }
    };
    default:
        return state;
}
</code>```

This will make sure you have no undefined states and an action not registered with the reducer returns the state of the store.

Your action dispatches a payload item which gets set as state.cart of the store, not the state.reducer.

so in your WebShop component change your mapStateToProps

```<code>function mapStateToProps(state) {
   return {
      cartItem: state.cart.item // to access your item inside your cart
   }
}
</code>```

And to access this cart in another component you either need to pass it to the props of that component like this for stateless components
    const cartItem = this.state.cartItem // get this from either the state or props or from the mapDispatchToProps in connect like you're doing in the webshop component

```<code><Component cart={cartItem} />
</code>```

as cartItem is now in your state, you should be able to do something like this.

```<code>class OtherComponent extends Component {
  render() {
    return (
     <div>
       {/* render some other components */}
       <Component cartItem={this.props.cartItem}
     </div>
  }
}
function mapStateToProps(state) {
  return { cartItem: state.cart.item };
}
export default connect(mapStateToProps, null)(OtherComponent);
</code>```

Hope this clarifies your issue.

Body:
I've set up Redux in my React app, however I don't get any data passed when I use this.props to access the data in another component in a separate file. My action is being executed and it passes the data I want.
This is my actions.js:

export const ADD_CART = 'ADD_CART';

export function addCart(item){
    return {
        type: ADD_CART,
        payload: item
    }
};

My reducer.js is:

import {ADD_CART} from './actions';

export default Reducer;

function Reducer(state, action){
    switch(action.type){
        case ADD_CART:
            return {
                ...state,
                cart: action.payload
            }
    };
}

My action creator contains cart, which is what I want to pass to the component:

...
class WebShop extends Component {
    ...

    handleClick() {
        let cart = {price:0,item:"userselection",size:this.state.value};
        this.props.onCartAdd(cart);
    }

   ...

    render() {
        return (
            ..
}

const mapDispatchToProps = (dispatch) => {
    return {
        onCartAdd: (cart) => {
            dispatch(addCart(cart));
        },
    }
}

function mapStateToProps(state) {
   return {
      cartItem: state.reducer,
   }
}

export default connect(mapStateToProps,mapDispatchToProps)(WebShop);

When I try to access cart in another file and component like so:

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default class Cart extends Component {
    render() {
        console.log(this.props.cart);
        return(

        );
    }
}

This is my store.js:

import { createStore, applyMiddleware } from 'redux';
import  reducer  from './reducers';
import thunkMiddleware from 'redux-thunk';
import {createLogger} from 'redux-logger';

var initialState = {
  cart:"medium",
  data: [],
  url: "/api/comments",
  pollInterval: 2000
}

const store = createStore(
  reducer,
  applyMiddleware(
    createLogger(),
    thunkMiddleware
  )
);
export default store;

My Provider is in my app.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import {Provider} from 'react-redux';
import store from '../store';

import App from 'views/App';
import Home from 'views/Home';
import About from 'views/About';
import Cart from 'views/webcart';

console.log(store);
ReactDOM.render(
    <Provider store={store}>
        <Router history={ hashHistory }>
            <Route path='/' component={ App }>
                <IndexRoute component={ Home } />
                <Route path='about' component={ About } />
                <Route path='Cart' component={ Cart } />
            </Route>
        </Router>
    </Provider>,
    document.getElementById('app') // eslint-disable-line
);

After updating my code to use mapStateToProps now I get the error Uncaught TypeError: Cannot read property 'Reducer' of undefined. Why I'm I getting this if Reducer should be accessed by the API?

Body:
Move your initial state from the store.js to your reducer.js and pass it to the reducer function to have the state defaulted to, like this

const initialState = {
  cart: {}, // change this to object to hold that cart your're
           //passing or an array to hold multiple cart, in which
           // case you will need to handle the return of your
           // state differently in your reducer
  data: [],
  url: "/api/comments",
  pollInterval: 2000
};

function Reducer(state = initialState, action){
switch(action.type){
    case ADD_CART:
        return {
            ...state,
            cart: action.payload
        }
    };
    default:
        return state;
}

This will make sure you have no undefined states and an action not registered with the reducer returns the state of the store.

Your action dispatches a payload item which gets set as state.cart of the store, not the state.reducer.

so in your WebShop component change your mapStateToProps

function mapStateToProps(state) {
   return {
      cartItem: state.cart.item // to access your item inside your cart
   }
}

And to access this cart in another component you either need to pass it to the props of that component like this for stateless components
    const cartItem = this.state.cartItem // get this from either the state or props or from the mapDispatchToProps in connect like you're doing in the webshop component

<Component cart={cartItem} />

as cartItem is now in your state, you should be able to do something like this.

class OtherComponent extends Component {
  render() {
    return (
     <div>
       {/* render some other components */}
       <Component cartItem={this.props.cartItem}
     </div>
  }
}
function mapStateToProps(state) {
  return { cartItem: state.cart.item };
}
export default connect(mapStateToProps, null)(OtherComponent);

Hope this clarifies your issue.


问:
Polymer- using custom element in other projects like angular and Java jsp
I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java

my-element.js:

```<code>    class MyElement extends HTMLElement {
      // This gets called when the HTML parser sees your tag
      constructor() {
        super(); // always call super() first in the ctor.
        this.msg = 'Hello, World!';
      }
      // Called when your element is inserted in the DOM or
      // immediately after the constructor if it’s already in the DOM
      connectedCallback() {
        this.innerHTML = `<form action="/action_page.php">
      <div class="container">
        <label><b>Name</b></label>
        <input type="text" placeholder="Enter Email" name="email" required>

       <label><b>Age</b></label>
        <input type="text" placeholder="Enter Age" name="age" required>

        <div class="clearfix">
          <button type="button"  class="cancelbtn">Cancel</button>
          <button type="submit" class="signupbtn">Add</button>
        </div>
      </div>
    </form>`;
      }
    }
    // This registers your new tag and associates it with your class
    window.customElements.define('my-element', MyElement);
</code>```

my-element.html:

```<code>    <!doctype html>
<html>
<head>
    <meta charset="utf-8">

    <script src="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/webcomponentsjs/webcomponents-lite.js"></script>
    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">
    <script src="my-element.js"></script>
    <!-- <link rel="import" href="add-form.html"> -->

</head>
<body>
<my-element></my-element>

</body>
</html>
</code>```

Two issues I am struggling with now are below

1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?

```<code><link rel="import" href="my-element.html">
<script src="my-element.js"></script>

 <my-element></my-element>
</code>```

I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements

[
      {
        "name":"Name",
        "type":"text",
        "size":"20",
        "readyOnly": false,
        "validateFunction":"onlyText"
      },
      {
        "name":"Age",
        "type":"number",
        "size":"3",
        "readyOnly": false,
        "validateFunction":"onlyNumber"
      }
    ]

I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors

```<code><my-element form-data="{{data}}"></my-element>
</code>```

答:
it looks like this is using a web component as opposed to a polymer component. The native web component API does not include data binding, although angular and polymer both do (but implemented in different ways).

Native web components and polymer components can be used with Angular as well as other frameworks.

Depending on whether you are using Angular.js(1) or Angular(2+), setting up the data object to be passed into the DOM will vary, but in general the data should be "set up" so to speak in the JS and passed into the DOM. Otherwise as @daKmoR said, the data would need to be declared as he did in his example.

There are packages that assist in implementing data 2-way binding between polymer's data bindings and angulars bindings if that is needed.

Trey

Body:
I am trying to create custom form element which I am trying to reuse in other applications developed in angular and jsp page of Java

my-element.js:

    class MyElement extends HTMLElement {
      // This gets called when the HTML parser sees your tag
      constructor() {
        super(); // always call super() first in the ctor.
        this.msg = 'Hello, World!';
      }
      // Called when your element is inserted in the DOM or
      // immediately after the constructor if it’s already in the DOM
      connectedCallback() {
        this.innerHTML = `<form action="/action_page.php">

        Name
        <input type="text" placeholder="Enter Email" name="email" required>

       Age
        <input type="text" placeholder="Enter Age" name="age" required>

          <button type="button"  class="cancelbtn">Cancel</button>
          <button type="submit" class="signupbtn">Add</button>

    </form>`;
      }
    }
    // This registers your new tag and associates it with your class
    window.customElements.define('my-element', MyElement);

my-element.html:

    <!doctype html>

    <meta charset="utf-8">

    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/polymer/polymer.html">
    <link rel="import" href="https://cdn.rawgit.com/download/polymer-cdn/1.5.0/lib/iron-ajax/iron-ajax.html">

<my-element></my-element>

Two issues I am struggling with now are below

1.Can i incude both the files as below to my angular and java jsp page and use custom tag to work?

<link rel="import" href="my-element.html">

 <my-element></my-element>

I am trying to pass below json object as an attribute to custom form element and trying to render custom form elements

[
      {
        "name":"Name",
        "type":"text",
        "size":"20",
        "readyOnly": false,
        "validateFunction":"onlyText"
      },
      {
        "name":"Age",
        "type":"number",
        "size":"3",
        "readyOnly": false,
        "validateFunction":"onlyNumber"
      }
    ]

I tried using below way to inject json data to custom element to render form elements based on json but no luck and there are no console errors

<my-element form-data="{{data}}"></my-element>


问:
which is faster in spark, collect() or toLocalIterator()
I have a spark application in which I need to get the data from executors to driver and I am using collect(). However, I also came across toLocalIterator(). As far as I have read about toLocalIterator() on Internet, it returns an iterator rather than sending whole RDD instantly, so it has better memory performance, but what about speed? How is the performance between collect() and toLocalIterator() when it comes to execution/computation time?

答:
To quote from the documentation on toLocalIterator():

This results in multiple Spark jobs, and if the input RDD is the result of a wide transformation (e.g. join with different partitioners), to avoid recomputing the input RDD should be cached first.

It means that in the worst case scenario (no caching at all) it can be n-partitions times more expensive than collect. Even if data is cached, the overhead of starting multiple Spark jobs can be significant on large datasets. However lower memory footprint can partially compensate that, depending on a particular configuration.

Overall, both methods are inefficient and should be avoided on large datasets.

ContentLicense: CC BY-SA 4.0


问:
Confusion about Printing string arrays in C
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

```<code>char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);
</code>```

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

答:
The context in which *(not * as in multiplication) matters,
when used in declearation as in char *words[LENGTH] word becomes array of pointers to char.

as far as pointers are concern * is Value at address operator, it gives Value stored at particular address, while & is the address operator, gives address of variable.

```<code>printf("%s\n",*words) // prints value at address to which word points
</code>```

while

```<code>printf("%p\n",words) // prints address to which word points
</code>```

Body:
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

Body:
The context in which *(not * as in multiplication) matters,
when used in declearation as in char *words[LENGTH] word becomes array of pointers to char.

as far as pointers are concern * is Value at address operator, it gives Value stored at particular address, while & is the address operator, gives address of variable.

printf("%s\n",*words) // prints value at address to which word points

while

printf("%p\n",words) // prints address to which word points


问:
Get 2 Divs in one box?
I was wondering how I would get 2 divs in one div

html {
  margin: auto;
  width: 960px;
  height: auto;
}

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: block;
}

.logo {
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
}

.navitems li,
.navitems ul {
  list-style-type: none;
  display: inline-block;
}

.navitems {
  float: right;
}
```

<pre class="lang-html prettyprint-override"><code><div id="navbar">
  <div class="logo">
    <img src="images/logo.png" alt="" width="90px" height="90px">
  </div>
  <div class="navitems">
    <li>
      <ul>Home</ul>
      <ul>Contact Us</ul>
      <ul>About</ul>
    </li>
  </div>
</div>
</code>```

答: The 2 divs are in 1 div only but the fact is float property does not changes the flow .Floated elements remain a part of the flow of the web page unlike absolute and fixed positioning so place the div class="navitems" above the div class="logo".Moreover interchange the ul and li you have used them incorrectly conceptually although it doesnt make any difference visually</p>

Title: Get 2 Divs in one box?

Body:
I was wondering how I would get 2 divs in one div

html {
  margin: auto;
  width: 960px;
  height: auto;
}

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: block;
}

.logo {
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
}

.navitems li,
.navitems ul {
  list-style-type: none;
  display: inline-block;
}

.navitems {
  float: right;
}

Home

Contact Us

About


答:
First, use display: inline-block; on those two DIVs. Also, use vertical-align: middle; on both to align them vertically centered to their container.

But there a mistake in your code: ul and li should be used the other way round, the lis are inside  the ul . And also note that list-style-type: none; is only assigned to the ul, and display: inline-block;  only to the li elements.

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: block;
}

.logo {
  display: inline-block;
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
  vertical-align: middle;
}
.navitems {
  display: inline-block;
  vertical-align: middle;
}
.navitems ul {
  list-style-type: none;
}
.navitems li {
  display: inline-block;
  margin-right: 4em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar">
  <div class="logo">
    <img src="http://placehold.it/90x90/fb4" alt="" width="90px" height="90px">
  </div>
  <div class="navitems">
    <ul>
      <li>Home</li>
      <li>Contact Us</li>
      <li>About</li>
    </ul>
  </div>
</div></code>```

Title: Get 2 Divs in one box?

Body:
First, use display: inline-block; on those two DIVs. Also, use vertical-align: middle; on both to align them vertically centered to their container.

But there a mistake in your code: ul and li should be used the other way round, the lis are inside  the ul . And also note that list-style-type: none; is only assigned to the ul, and display: inline-block;  only to the li elements.

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: block;
}

.logo {
  display: inline-block;
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
  vertical-align: middle;
}
.navitems {
  display: inline-block;
  vertical-align: middle;
}
.navitems ul {
  list-style-type: none;
}
.navitems li {
  display: inline-block;
  margin-right: 4em;
}

<div id="navbar">
  <div class="logo">
    <img src="http://placehold.it/90x90/fb4" alt="" width="90px" height="90px">
  </div>
  <div class="navitems">
    <ul>
      <li><a href="#">Home</a></li>
      <li><a href="#team">Contact Us</a></li>
      <li><a href="#about">About</a></li>
    </ul>
  </div>
</div>


答:
It's probably better to use flex.

Set "display: flex" and "justify-content: space-between" on the parent element (navigator).  I also changed the image to just have a background color that stands out.

html {
  margin: auto;
  width: 960px;
  height: auto;
}

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: flex;
  justify-content: space-between;
}

img {
  background-color: #0ff;
}

.logo {
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
}

.navitems li,
.navitems ul {
  list-style-type: none;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="navbar">
  <div class="logo">
    <img width="90px" height="90px">
  </div>
  <div class="navitems">
    <li>
      <ul>Home</ul>
      <ul>Contact Us</ul>
      <ul>About</ul>
    </li>
  </div>
</div></code>```

More on flex properties:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Title: Get 2 Divs in one box?

Body:
It's probably better to use flex.

Set "display: flex" and "justify-content: space-between" on the parent element (navigator).  I also changed the image to just have a background color that stands out.

html {
  margin: auto;
  width: 960px;
  height: auto;
}

#navbar {
  height: 90px;
  background-color: #080808 !important;
  display: flex;
  justify-content: space-between;
}

img {
  background-color: #0ff;
}

.logo {
  padding-left: 31px;
  height: 90px !important;
  width: 90px !important;
}

.navitems li,
.navitems ul {
  list-style-type: none;
  display: inline-block;
}

<div id="navbar">
  <div class="logo">
    <img width="90px" height="90px">
  </div>
  <div class="navitems">
    <li>
      <ul><a href="#">Home</a></ul>
      <ul><a href="#team">Contact Us</a></ul>
      <ul><a href="#about">About</a></ul>
    </li>
  </div>
</div>

More on flex properties:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/


问:
charAt(0) Not returning first number but second
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first. </p>

```<code>import java.util.Scanner;
import javax.swing.JOptionPane;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";
            String firstVowel = "test";

            String word = userWord.next();
            String vowels = "aeiou";
            if (word.equals("Q")) {
                System.exit(0);
            }

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                for (int index = 0; index < word.length(); index++) {
                    if (vowels.contains(String.valueOf(word.charAt(index)))) {
                        System.out.print(index);
                        String firstNumber = Integer.toString(index);
                        firstVowel = Character.toString(firstNumber.charAt(0));

                    }
                }

            }
            System.out.println(firstVowel);
</code>```

答:
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:

```<code>String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
    if(vowels.contains(String.valueOf(word.charAt(i)))){
        System.out.println(word.charAt(i));
        break;
    }
}
</code>```

Please note that you need to do toLowerCase on the actual word in order for contains to work.

Body:
Piglatin translator. at the end I am trying to get the location of the first vowel. Index is set to be the location of every vowel, but with pig latin you only need the location of the first vowel. When I run the program I don't always get the location of the first vowel. it seems to give me the second number and not the first.

import java.util.Scanner;
import javax.swing.JOptionPane;

public class Assignment_4_Piglatin {

    public static void main(String[] args) {

        Scanner userWord = new Scanner(System.in);

        System.out.println("K. Caleb Swallow");
        System.out.println("Welcome to the Pig Latin Translator!");

        boolean run = true;
        while (run) {

            System.out.println("Please enter a word(or press Q to quit):");

            String firstLetter = "something";
            String firstVowel = "test";

            String word = userWord.next();
            String vowels = "aeiou";
            if (word.equals("Q")) {
                System.exit(0);
            }

            firstLetter = Character.toString(word.charAt(0));

            if (firstLetter.equals("a") || firstLetter.equals("e") || firstLetter.equals("i") || firstLetter.equals("o") || firstLetter.equals("u")) {
                System.out.println(word + "way");
            } else {
                for (int index = 0; index < word.length(); index++) {
                    if (vowels.contains(String.valueOf(word.charAt(index)))) {
                        System.out.print(index);
                        String firstNumber = Integer.toString(index);
                        firstVowel = Character.toString(firstNumber.charAt(0));

                    }
                }

            }
            System.out.println(firstVowel);

Body:
The example seems to have some redundant code in if..else condition. If you want to print the first vowels then you can do it with a simple for loop, e.g.:

String word = userWord.next().toLowerCase();
String vowels = "aeiou";
for(int i=0 ; i<word.length() ; i++){
    if(vowels.contains(String.valueOf(word.charAt(i)))){
        System.out.println(word.charAt(i));
        break;
    }
}

Please note that you need to do toLowerCase on the actual word in order for contains to work.