问:
element.set_value not working in python appium for fill the application form
I am trying to fill the data like name, email, and other details on android app using python appium client getting below error.
Appium server version -1.4.16.1
python appium client = 0.22 and 0.24
getting below error not getting ant resolution.

```<code>    element.set_value('Test_Uder')
  File "build\bdist.win-amd64\egg\appium\webdriver\webelement.py", line 123, in set_value
    self._execute(Command.SET_IMMEDIATE_VALUE, data)
  File "D:\vikas_python_venv\my_appium\lib\site-packages\selenium-3.7.0-py2.7.egg\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "D:\vikas_python_venv\my_appium\lib\site-packages\selenium-3.7.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "build\bdist.win-amd64\egg\appium\webdriver\errorhandler.py", line 29, in check_response
    raise wde
</code>```

WebDriverException: Message: Not yet implemented. Please help us:
  http://appium.io/get-involved.html

答:
did you try using "send_keys" instead?

Something like this:

```<code>self.driver = webdriver.Remote('http://localhost:4723/wd/hub',
desired_caps)

self.driver.find_element_by_id(
'com.matchbook.client:id/editTextUsername').send_keys("username_here")
</code>```

where "com.matchbook.client" is your package name, you can find element ID  (com.matchbook.client:id/editTextUsername) using Appium Inspector which is included in Appium desktop app.

Body:
I am trying to fill the data like name, email, and other details on android app using python appium client getting below error.
Appium server version -1.4.16.1
python appium client = 0.22 and 0.24
getting below error not getting ant resolution.

    element.set_value('Test_Uder')
  File "build\bdist.win-amd64\egg\appium\webdriver\webelement.py", line 123, in set_value
    self._execute(Command.SET_IMMEDIATE_VALUE, data)
  File "D:\vikas_python_venv\my_appium\lib\site-packages\selenium-3.7.0-py2.7.egg\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "D:\vikas_python_venv\my_appium\lib\site-packages\selenium-3.7.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "build\bdist.win-amd64\egg\appium\webdriver\errorhandler.py", line 29, in check_response
    raise wde

WebDriverException: Message: Not yet implemented. Please help us:
  http://appium.io/get-involved.html

Body:
did you try using "send_keys" instead?

Something like this:

self.driver = webdriver.Remote('http://localhost:4723/wd/hub',
desired_caps)

self.driver.find_element_by_id(
'com.matchbook.client:id/editTextUsername').send_keys("username_here")

where "com.matchbook.client" is your package name, you can find element ID  (com.matchbook.client:id/editTextUsername) using Appium Inspector which is included in Appium desktop app.


来源: stackexchange

问:
Gitlab snippets file access
How can we access a snippet file from a Gitlab (private) repository?

I can access and clone my (private) projects (using SSH) but the problem with the snippets is that the raw URL doesn’t return the filename, let me give you an example:

```<code>I create a new snippet:
Title: My new patch
Access: Public (let’s say public to be clearer)
File: my_patch.patch (filename)
<code>….</code>
</code>```

When I see the raw of the file it returns a URL like https://gitlab.com/snippets/id/raw but I need something like https://gitlab.com/snippets/id/my_patch.patch

Is it possible?

答:
I do not think that sharing a private snippet is supported at this moment.

Check and push these feature proposals for having this enhancement:

https://gitlab.com/gitlab-org/gitlab-ce/issues/22337

https://gitlab.com/gitlab-org/gitlab-ce/issues/24318

ContentLicense: CC BY-SA 3.0

Title: Gitlab snippets file access

Body:
How can we access a snippet file from a Gitlab (private) repository?

I can access and clone my (private) projects (using SSH) but the problem with the snippets is that the raw URL doesn’t return the filename, let me give you an example:

I create a new snippet:
Title: My new patch
Access: Public (let’s say public to be clearer)
File: my_patch.patch (filename)
….

When I see the raw of the file it returns a URL like https://gitlab.com/snippets/id/raw but I need something like https://gitlab.com/snippets/id/my_patch.patch

Is it possible?


问:
A zk-textbox which doesn't contain pasted value
How can I create a textbox that prevent copy and paste in ZK? Cut/copy/paste are not allowed in zk-textbox.

Ctrl+V and mouse right click are handled, but what about drag and drop?

答:
You can use javascript to disable dragging of text for certain components. There are several ways to apply such code to components, he following uses an sclass as a marker, which is quite convenient if you only need it for a small number of textboxes:

<textbox value="Drag Me!" />
<textbox value="Can't drag me!" sclass="nodrag" />
<textbox placeholder="Can drop here..." />
<textbox placeholder="...but not here" sclass="nodrop" />

```

<p>You can also do it via zk.afterLoad:</p>

<pre class="lang-js prettyprint-override"><code>zk.afterLoad('zul.inp', function() {
    var xTextbox = {};
    zk.override(zul.inp.Textbox.prototype, xTextbox , {
        bind_  : function() {
            this.$supers('bind_', arguments);
            if (this.$n().className.indexOf("nodrag") > -1) {
                this.domListen_(this.$n(), "onDragstart", function(event) {
                    event.stop();
                    return false;
                });
            }
            if (this.$n().className.indexOf("nodrop") > -1) {
                this.domListen_(this.$n(), "onDragover", function(event) {
                    event.stop();
                });
            }
        }
    });
});
</code>```

This focusses on how to apply this using zk, but in fact it's just plain javascript. You can read here for more info: disable text drag and drop

Body:
You can use javascript to disable dragging of text for certain components. There are several ways to apply such code to components, he following uses an sclass as a marker, which is quite convenient if you only need it for a small number of textboxes:

<textbox value="Drag Me!" />
<textbox value="Can't drag me!" sclass="nodrag" />
<textbox placeholder="Can drop here..." />
<textbox placeholder="...but not here" sclass="nodrop" />

<script type="text/javascript">
    document.body.addEventListener("dragstart", function(e) {
        if (e.target.className.indexOf("nodrag") > -1) {
            e.preventDefault();
            return false;
        }
    }, false);
    document.body.addEventListener("dragover", function(e) {
        if (e.target.className.indexOf("nodrop") > -1) {
            e.preventDefault();
            e.dataTransfer.effectAllowed = "none";
            e.dataTransfer.dropEffect = "none";
            return false;
        }
    }, false);
</script>

You can also do it via zk.afterLoad:

zk.afterLoad('zul.inp', function() {
    var xTextbox = {};
    zk.override(zul.inp.Textbox.prototype, xTextbox , {
        bind_  : function() {
            this.$supers('bind_', arguments);
            if (this.$n().className.indexOf("nodrag") > -1) {
                this.domListen_(this.$n(), "onDragstart", function(event) {
                    event.stop();
                    return false;
                });
            }
            if (this.$n().className.indexOf("nodrop") > -1) {
                this.domListen_(this.$n(), "onDragover", function(event) {
                    event.stop();
                });
            }
        }
    });
});

This focusses on how to apply this using zk, but in fact it's just plain javascript. You can read here for more info: disable text drag and drop


问:
angular watch not fired
There is 1 angular app, with 1 parent controller, and a child controller.
In the child, there is 1 $watch WATCH-CHILD for OBJ-CHILD, which triggers an $emit.
In the parent, there is a listener for the $emit, we'll call it ON-LISTENER, and a $watch WATCH-PARENT for OBJ-PARENT (which uses true as the 3rd argument).

When the child's OBJ-CHILD is changed, it triggers WATCH-CHILD, which triggers the $emit.
The parent listener ON-LISTENER is fired, and changes OBJ-PARENT. It also sets some $location properties.
The $watch WATCH-PARENT for OBJ-PARENT is never fired (even though the value has changed), as well as the properties set on $location not changed in the browser URL (I know they are indeed changed inside the JavaScript, cause I print them).

In order to make sure that ON-LISTENER is called within a $digest, I tried to call $digest at the end of ON-LISTENER, and got the expected exception.

Any idea if I'm doing something wrong? I expect the changes that occur in ON-LISTENER to trigger WATCH-PARENT and browser URL change.

I will try to reproduce on jsfiddle and edit this post if successful.

The code looks like:

CHILD:

```<code>$scope.$watch('vars.model', function(newValue, oldValue) {
  console.log('model changed');
  $scope.$emit('highlightChange', newValue);
}, true);
</code>```

PARENT:

```<code>$scope.$watch('vars.model.highlight', function(newValue, oldValue) {
  console.log('highlight changed');
}, true);

$scope.$on('highlightChange', function(event, value) {
  console.log('listener', $scope.vars.model.highlight.categoryId, value.categoryId);
  $location.search('category-id', value.categoryId);
  $scope.vars.model.highlight.categoryId = value.categoryId;
}
</code>```

答:
Next time please provide more code which works, that way you can get better answers.

Here is a Demo plunker which I created to test the code which you provided. It works just fine. If you could provide more code then we could find the real reason why it did not work.

I created two controllers parentCtrl and childCtrl which uses your code and object of provided structure.

```<code>$scope.vars = {
   model:{
      highlight:{
        categoryId : 5 //This value is set for testing purposes
      }
   }
};
</code>```

Also, I changed watch target (vars.model -> vars.model.highlight) to be the same as in parent controller

```<code>$scope.$watch('vars.model.highlight', function(newValue, oldValue) {
  console.log('child model changed (new/old)', newValue, oldValue);
  $scope.$emit('highlightChange', newValue);
  console.log('Emited change event');
}, true);
</code>```

Title: angular watch not fired

Body:
There is 1 angular app, with 1 parent controller, and a child controller.
In the child, there is 1 $watch WATCH-CHILD for OBJ-CHILD, which triggers an $emit.
In the parent, there is a listener for the $emit, we'll call it ON-LISTENER, and a $watch WATCH-PARENT for OBJ-PARENT (which uses true as the 3rd argument).

When the child's OBJ-CHILD is changed, it triggers WATCH-CHILD, which triggers the $emit.
The parent listener ON-LISTENER is fired, and changes OBJ-PARENT. It also sets some $location properties.
The $watch WATCH-PARENT for OBJ-PARENT is never fired (even though the value has changed), as well as the properties set on $location not changed in the browser URL (I know they are indeed changed inside the JavaScript, cause I print them).

In order to make sure that ON-LISTENER is called within a $digest, I tried to call $digest at the end of ON-LISTENER, and got the expected exception.

Any idea if I'm doing something wrong? I expect the changes that occur in ON-LISTENER to trigger WATCH-PARENT and browser URL change.

I will try to reproduce on jsfiddle and edit this post if successful.

The code looks like:

CHILD:

$scope.$watch('vars.model', function(newValue, oldValue) {
  console.log('model changed');
  $scope.$emit('highlightChange', newValue);
}, true);

PARENT:

$scope.$watch('vars.model.highlight', function(newValue, oldValue) {
  console.log('highlight changed');
}, true);

$scope.$on('highlightChange', function(event, value) {
  console.log('listener', $scope.vars.model.highlight.categoryId, value.categoryId);
  $location.search('category-id', value.categoryId);
  $scope.vars.model.highlight.categoryId = value.categoryId;
}

Body:
Next time please provide more code which works, that way you can get better answers.

Here is a Demo plunker which I created to test the code which you provided. It works just fine. If you could provide more code then we could find the real reason why it did not work.

I created two controllers parentCtrl and childCtrl which uses your code and object of provided structure.

$scope.vars = {
   model:{
      highlight:{
        categoryId : 5 //This value is set for testing purposes
      }
   }
};

Also, I changed watch target (vars.model -> vars.model.highlight) to be the same as in parent controller

$scope.$watch('vars.model.highlight', function(newValue, oldValue) {
  console.log('child model changed (new/old)', newValue, oldValue);
  $scope.$emit('highlightChange', newValue);
  console.log('Emited change event');
}, true);


问:
Attempting to Pre-load Data into Core Data Store
Sup fellas, I am using the script that a fellow stack overflow user posted here(the post by kalperin) to pre-load data to an SQL Lite store. So I have a command-line utility project that I am using and I have an iPhone application in which I successfully parsed my .plist file and stored it in Core Data, and I am trying to copy over code from my iPhone application to this command-line utility(the plist parsing parts at least). The data model I have made looks like so:

Those two classes inherit from ParkingRegionOverlay which requires the MapKit framework which is not addable to a project of this type(as far as I know). So my questions:

How would I bypass this problem(i.e. How do I get the Mapkit framework as part of my command-line utility project?)?

Do I need to include my .xcdatamodel file in the command-line utility project and reference it in any way? If someone wouldn't mind shedding some light in this area it would be greatly appreciated, as I think I do need my project to know about the data model, but am not quite sure.

Thanks in advance for any help!

答:
you absolutely need the xdatamodel file in your project. It will be "compiled" into a momd file and included in your application bundle. Core Data needs this to know what your data model looks like (that's the whole point of the data model file).

This might help you, too: Can't find momd file: Core Data problems

Also, why do you mix Model and View by having your data model classes inherit from an Overlay class. It seems that you can solve your problem simply by adhering to MVC practices.

Cheers,

Johannes

ContentLicense: CC BY-SA 2.5


问:
WPF application in Kiosk mode
I have a WPF application that uses a TabControl to display lets say Tab1, Tab2 and Tab3.

1) How can I enable this application to run in Kiosk mode on Surface tablet as well as Windows touch PC devices?
2) My second question : Is it possible to disable Tab1 and Tab2 in Kiosk mode? The user will have access to only Tab3 in Kiosk mode.

Any help will be appreciated. Thanks.

答:
The Windows 10 Kiosk mode is for Universal Windows Platform (UWP) apps only. WPF apps don’t qualify.

Microsoft provides instructions for configuring Windows for kiosk usage, but most options require Windows 10 Enterprise or Education editions.

Title: WPF application in Kiosk mode


问:
How big is the args array in public static void main(String[] args) in java?
When using command line arguments in java I am curious to how big is the args array parameter in main. And if it is varied length how does main know the length?</p>

答:
It will be as big as needed to hold the arguments passed in. So if you do

java -jar myjar.jar 1 2 34

Args will contain

["1", "2", "34"]

Note the array is typed as string so if you pass in numbers you need to convert the string containing the number to actual number.


问:
Adding animation to my images with JQuery
Here is my home page:

```<code><%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">
<table id="home" style="margin-left: auto; margin-right:auto;">
    <td id="homeLinks">
        <div style="padding-left:35px;" id="homeListing" class="containerMid">
            <div id="homeView">
                <table style="margin-left: auto; margin-right:auto;">
                    <tr>
                        <tr>
                            <td id="btnIcOld" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />
                            </td>
                            <td id="btnIc" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />
                            </td>
                            <td id="btnPricing" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnSheets" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnPort" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />
                            </td>
                            <td id="btnAdmin" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />
                            </td>
                        </tr>
                        <tr>
                            <td id="Td1">
                                <b>Indications Calculator | </b>
                            </td>
                            <td id="lblIc">
                                <b>Indications Calculator - Beta | </b>
                            </td>
                            <td id="lblPricing">
                                <b>Managing Pricing Triggers | </b>
                            </td>
                            <td id="lblSheets">
                                <b>Creating Pricing Sheets | </b>
                            </td>
                            <td id="lblPort">
                                <b>Portfolio Analysis | </b>
                            </td>
                            <td id="lblAdmin">
                                <b>Administration</b>
                            </td>
                        </tr>
                    </tr>
                </table>
            </div>
        </div>
    </td>
</table>

<div id="pageMessage"></div>

<script>
    $(document).ready(function () {

        $('#btnIc').live('click', function () {
            window.location.href = "<%=Url.Action("Indications") %>";
        });

        $('#btnIcOld').live('click', function () {
            window.location.href = 'https://extranetint/swap';
        });

        $('#btnPricing').live('click', function () {
            //window.location.href = "<%=Url.Action("Triggers") %>";
        });

        $('#btnSheets').live('click', function () {
            //window.location.href = "<%=Url.Action("Sheets") %>";
        });

        $('#btnPort').live('click', function () {
            //window.location.href = "<%=Url.Action("Analysis") %>";
        });

        $('#btnAdmin').live('click', function () {
            //window.location.href = "<%=Url.Action("Admin") %>";
        });

    });
</script>
</asp:Content>
</code>```

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

答:
If you don't really care about Internet Explorer, you can just use a bit of CSS3.

```<code>#homeView img {
    -moz-transition: -moz-transform 0.3s;
    -o-transition: -o-transform 0.3s;
    -webkit-transition: -webkit-transform 0.3s;
    -ms-transition: -ms-transform 0.3s;
    transition: transform 0.3s;
}
#homeView img:hover {
    -moz-transform: scale(1.1);
    -o-transform: scale(1.1);
    -webkit-transform: scale(1.1);
    -ms-transform: scale(1.1);
    transform: scale(1.1);
}
</code>```

When the user hovers the image, the image will be zoomed in. Works with the current version of Chrome, Safari, Opera and the upcoming Firefox 4. In Firefox 3.5 and 3.6 you will see the zoom-in effect, just without the transitions.

Demo: http://jsfiddle.net/thai/WNmdh/1/

Body:
Here is my home page:

<%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />

                                Indications Calculator |

                                Indications Calculator - Beta |

                                Managing Pricing Triggers |

                                Creating Pricing Sheets |

                                Portfolio Analysis |

                                Administration

</asp:Content>

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

Body:
If you don't really care about Internet Explorer, you can just use a bit of CSS3.

#homeView img {
    -moz-transition: -moz-transform 0.3s;
    -o-transition: -o-transform 0.3s;
    -webkit-transition: -webkit-transform 0.3s;
    -ms-transition: -ms-transform 0.3s;
    transition: transform 0.3s;
}
#homeView img:hover {
    -moz-transform: scale(1.1);
    -o-transform: scale(1.1);
    -webkit-transform: scale(1.1);
    -ms-transform: scale(1.1);
    transform: scale(1.1);
}

When the user hovers the image, the image will be zoomed in. Works with the current version of Chrome, Safari, Opera and the upcoming Firefox 4. In Firefox 3.5 and 3.6 you will see the zoom-in effect, just without the transitions.

Demo: http://jsfiddle.net/thai/WNmdh/1/


问:
How to create an object from a JSON file in Node.js
I have dowloaded a json file which contains a lot of information that I do not need for my end purpose of rendering a table to a html page containing just some of the items of the data.

the data.json looks like

```<code>{ "events": [
 {
  "id": "181101322507029",
  "name": "Carnival Special",
  "type": "public",
  "coverPicture": "https://scontent.xx.fbcdn.net/v/t1.0.jpg?oh=b9eC",
  "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-jpg?oh=32c4574",
  "description": "Lots and lots of info blah blah",
  "distance": "1546",
  "startTime": "2017-11-18T22:00:00+0000",
  "endTime": "2017-11-19T03:00:00+0000",
  "timeFromNow": 476169,
  "isCancelled": false,
  "isDraft": false,
  "category": null,
  "ticketing": {
    "ticket_uri": "https://nicevenue.co.uk/event/lime-of-your-life/"
  },
  "place": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 66.3445334,
      "longitude": -4.7356667928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  },
  "stats": {
    "attending": 68,
    "declined": 0,
    "maybe": 177,
    "noreply": 336
  },
  "venue": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "about": "Situated in the blah blah aims to provide a friendly atmosphere, gourmet food and fine cocktails.",
    "emails": [
      "nicevenue@googlemail.com"
    ],
    "coverPicture": "https://scontent.xx.fbcdn.net/v/t31.0-8/s78_o.jpg?oh=8f62cb6CB2",
    "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-1/c0.16n.jpg?oh=8ef5df00f31&oe=5AAF3935",
    "category": "Bar",
    "categoryList": [
      "Bar",
      "Restaurant"
    ],
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 65.138604292331,
      "longitude": -9.73566d867928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  }
},
{
  "id": "1896504087342309",
  "name": "Mr Tea  + Dj Dr SJ",
  "type": "public",events
"
"
etc....
</code>```

I need to iterate through this data and create a new object (or array) like

```<code>{"id": 123456 [
 {
  "StartTime": "2017-11-18T22:00:00+0000",
  "description": "Lots and lots of info blah blah",
  "place": {
     "id": "517137361697082",
     "name": "Nice Venue",
     "location": {
     "city": "Nice City",
    "country": "United Kingdom",
    "latitude": 66.3445334,
    "longitude": -4.7356667928,
    "street": "The Blah Blah, Blah, Blah Road",
    "zip": "AB1 2CD"
 }]
 }
</code>```

I would then like to iterate through this object using an express template to render the info to a table tag in the html.

I have looked at For in loops with hasProperty or by using low-dash _.Map  but I don't really understand if I am doing this correctly or even going about what I am trying to do in the best way. Thanks

答:
```<code>var resObj = JSON.parse("your json data");

resObj.forEach(function(event)){
    var id = event.id;
    var place = event.place;
    //so on...and create new objects here.
}
</code>```

You can then load the data in the html or make a html string out of this looped and append it to your main div.

Body:
I have dowloaded a json file which contains a lot of information that I do not need for my end purpose of rendering a table to a html page containing just some of the items of the data.

the data.json looks like

{ "events": [
 {
  "id": "181101322507029",
  "name": "Carnival Special",
  "type": "public",
  "coverPicture": "https://scontent.xx.fbcdn.net/v/t1.0.jpg?oh=b9eC",
  "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-jpg?oh=32c4574",
  "description": "Lots and lots of info blah blah",
  "distance": "1546",
  "startTime": "2017-11-18T22:00:00+0000",
  "endTime": "2017-11-19T03:00:00+0000",
  "timeFromNow": 476169,
  "isCancelled": false,
  "isDraft": false,
  "category": null,
  "ticketing": {
    "ticket_uri": "https://nicevenue.co.uk/event/lime-of-your-life/"
  },
  "place": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 66.3445334,
      "longitude": -4.7356667928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  },
  "stats": {
    "attending": 68,
    "declined": 0,
    "maybe": 177,
    "noreply": 336
  },
  "venue": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "about": "Situated in the blah blah aims to provide a friendly atmosphere, gourmet food and fine cocktails.",
    "emails": [
      "nicevenue@googlemail.com"
    ],
    "coverPicture": "https://scontent.xx.fbcdn.net/v/t31.0-8/s78_o.jpg?oh=8f62cb6CB2",
    "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-1/c0.16n.jpg?oh=8ef5df00f31&oe=5AAF3935",
    "category": "Bar",
    "categoryList": [
      "Bar",
      "Restaurant"
    ],
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 65.138604292331,
      "longitude": -9.73566d867928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  }
},
{
  "id": "1896504087342309",
  "name": "Mr Tea  + Dj Dr SJ",
  "type": "public",events
"
"
etc....

I need to iterate through this data and create a new object (or array) like

{"id": 123456 [
 {
  "StartTime": "2017-11-18T22:00:00+0000",
  "description": "Lots and lots of info blah blah",
  "place": {
     "id": "517137361697082",
     "name": "Nice Venue",
     "location": {
     "city": "Nice City",
    "country": "United Kingdom",
    "latitude": 66.3445334,
    "longitude": -4.7356667928,
    "street": "The Blah Blah, Blah, Blah Road",
    "zip": "AB1 2CD"
 }]
 }

I would then like to iterate through this object using an express template to render the info to a table tag in the html.

I have looked at For in loops with hasProperty or by using low-dash _.Map  but I don't really understand if I am doing this correctly or even going about what I am trying to do in the best way. Thanks

Body:
var resObj = JSON.parse("your json data");

resObj.forEach(function(event)){
    var id = event.id;
    var place = event.place;
    //so on...and create new objects here.
}

You can then load the data in the html or make a html string out of this looped and append it to your main div.


问:
searching a directory for folders
I'm trying to write a program that gets the path of a folder and prints  directories' names inside it.
This is my code:

```<code> if ((dir = opendir (file_path)) != NULL)
 {
    while ((ent = readdir (dir)) != NULL)
    {
       if (stat(ent->d_name, &dir_stat)== 0)
       {
         if( dir_stat.st_mode & S_IFDIR )
         {
            if(strncmp(ent->d_name, "." ,sizeof(ent->d_name)) != 0
                  && strncmp(ent->d_name, "..",sizeof(ent->d_name)) != 0)
                cout<<"dir : "<< ent->d_name<<endl;
         }

       }
   }
 }
</code>```

Now the problem is that when I give it  "." as file_path it works correctly but when I give it, ./folder as file_path, it does not print anything. Any ideas how to fix it? Thanks in advance.

答:
The problem is that readdir() returns the name of the subdirectories, not the path to get to them.

For example if you have a ./folder/sub then when reading the ./folder you will get just sub as the name. Then, doing a stat("sub") will not work, you have to concatenate the directory you are reading:

```<code>while ((ent = readdir (dir)) != NULL)
{
   std::string path = dir;
   path += ent->d_name;
   if (stat(path.c_str(), &dir_stat)== 0)
   {
</code>```

It is usually a good idea to add some perror() calls after your system calls:

```<code>   if (stat(path.c_str(), &dir_stat) < 0)
       perror(path.c_str());
   else
   {
       ...
</code>```

Title: searching a directory for folders

Body:
I'm trying to write a program that gets the path of a folder and prints  directories' names inside it.
This is my code:

 if ((dir = opendir (file_path)) != NULL)
 {
    while ((ent = readdir (dir)) != NULL)
    {
       if (stat(ent->d_name, &dir_stat)== 0)
       {
         if( dir_stat.st_mode & S_IFDIR )
         {
            if(strncmp(ent->d_name, "." ,sizeof(ent->d_name)) != 0
                  && strncmp(ent->d_name, "..",sizeof(ent->d_name)) != 0)
                cout<<"dir : "<< ent->d_name<<endl;
         }

       }
   }
 }

Now the problem is that when I give it  "." as file_path it works correctly but when I give it, ./folder as file_path, it does not print anything. Any ideas how to fix it? Thanks in advance.

Body:
The problem is that readdir() returns the name of the subdirectories, not the path to get to them.

For example if you have a ./folder/sub then when reading the ./folder you will get just sub as the name. Then, doing a stat("sub") will not work, you have to concatenate the directory you are reading:

while ((ent = readdir (dir)) != NULL)
{
   std::string path = dir;
   path += ent->d_name;
   if (stat(path.c_str(), &dir_stat)== 0)
   {

It is usually a good idea to add some perror() calls after your system calls:

   if (stat(path.c_str(), &dir_stat) < 0)
       perror(path.c_str());
   else
   {
       ...


问:
How do I change the width of Jupyter notebook's cell's left part?
I already increase the width of the jupyter notebook's cell on my browser with this

```<code>.container {
    width:100% !important;
}
</code>```

However, I would also like to narrow the left part of the text cell.

enter image description here

For the above picture I would like shrink the part div.prompt.input_prompt.

Is it possible to do it with just css? how?

Also, if this can be done, how to empty left part automatically for all non-code cells?

答:
The prompt width is set in notebook/static/notebook/less/cell.less#L80, so you could do something like:</p>

```<code>/* Narrow the prompts */
.prompt {
    min-width: 10ex;
}

/* Hide prompts altogether for non-conda cells */
.cell:not(.code_cell) .prompt {
    display: none;
}
</code>```

Body:
I already increase the width of the jupyter notebook's cell on my browser with this

.container {
    width:100% !important;
}

However, I would also like to narrow the left part of the text cell.

enter image description here

For the above picture I would like shrink the part div.prompt.input_prompt.

Is it possible to do it with just css? how?

Also, if this can be done, how to empty left part automatically for all non-code cells?

Body:
The prompt width is set in notebook/static/notebook/less/cell.less#L80, so you could do something like:

/* Narrow the prompts */
.prompt {
    min-width: 10ex;
}

/* Hide prompts altogether for non-conda cells */
.cell:not(.code_cell) .prompt {
    display: none;
}


问:
Setting Navigation bar back button Image for entire application in swift
I am setting navigation bar back button in AddDelegate but it is not setting properly.

I have tried below code :

```<code>let backButtonImage = backImage?.withRenderingMode(.alwaysOriginal).resizableImage(withCapInsets: UIEdgeInsetsMake((backImage?.size.height)!, (backImage?.size.width)!, 0, 0))
UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-400, 0), for: .default)
</code>```

from here .

But the UI is not correct:

I have also tried below code :

```<code>UINavigationBar.appearance().backIndicatorImage = backButtonImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backButtonImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)
</code>```

which looks like this:

But it is giving constraint issues in the terminal:

```<code>[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600000098510 UILayoutGuide:0x6040007aca20'BackButtonGuide(0x7f8143611390)'.height == 44   (active)>",
    "<NSLayoutConstraint:0x60000029e320 _UIButtonBarButton:0x7f814349d110.top == UILayoutGuide:0x6040007aca20'BackButtonGuide(0x7f8143611390)'.top   (active)>",
    "<NSLayoutConstraint:0x60000029de20 _UIButtonBarButton:0x7f814349d110.bottom == UILayoutGuide:0x6040007aca20'BackButtonGuide(0x7f8143611390)'.bottom   (active)>",
    "<NSLayoutConstraint:0x60400049d790 _UIModernBarButton:0x7f81434a4800'Back'.lastBaseline == UILayoutGuide:0x6000001b51c0'UIViewLayoutMarginsGuide'.bottom - 80   (active)>",
    "<NSLayoutConstraint:0x60400049d1a0 _UIModernBarButton:0x7f81434a4800'Back'.top >= _UIButtonBarButton:0x7f814349d110.top   (active)>",
    "<NSLayoutConstraint:0x600000481040 UIButtonLabel:0x7f81434a30d0'Back'.centerY == _UIModernBarButton:0x7f81434a4800'Back'.centerY + 1.5   (active)>",
    "<NSLayoutConstraint:0x60000029ea00 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x6000001b51c0'UIViewLayoutMarginsGuide']-(16)-|   (active, names: '|':_UIButtonBarButton:0x7f814349d110 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000481040 UIButtonLabel:0x7f81434a30d0'Back'.centerY == _UIModernBarButton:0x7f81434a4800'Back'.centerY + 1.5   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
    Try this:
    (1) look at each constraint and try to figure out which you don't expect;

(2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x60000029f1d0 _UIModernBarButton:0x7f814360f630.bottom == UILayoutGuide:0x6040007ac940'UIViewLayoutMarginsGuide'.bottom + 84.5   (active)>",
    "<NSLayoutConstraint:0x600000287bc0 V:[_UIModernBarButton:0x7f814360f630]-(>=0)-|   (active, names: '|':_UIButtonBarButton:0x7f814360d8a0 )>",
    "<NSLayoutConstraint:0x604000488930 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x6040007ac940'UIViewLayoutMarginsGuide']-(16)-|   (active, names: '|':_UIButtonBarButton:0x7f814360d8a0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000029f1d0 _UIModernBarButton:0x7f814360f630.bottom == UILayoutGuide:0x6040007ac940'UIViewLayoutMarginsGuide'.bottom + 84.5   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
</code>```

Is there any other way of doing it or I am doing something wrong ?

答:
Someone might post a better answer but my solution was giving up on these nonsense with navigation bar and its appearance so what I did was create a base view controller for all view controllers I use inside the application. (I do that anyway so I am able to control things like status bar style, translation...).

So my base view controller looks somewhat like:

```<code>class BaseViewController: UIViewController {

    @IBInspectable var backButtonImage: UIImage? = /*Use your default here*/

    override func viewDidLoad() {
        super.viewDidLoad()

        if let backButtonImage = backButtonImage {
           navigationItem.leftBarButtonItem = UIBarButtonItem(image: backButtonImage, style: .plain, target: self, action: #selector(onBack))
           navigationController?.interactivePopGestureRecognizer?.delegate = self
        }
    }

    @objc private func onBack() {
        navigationController?.popViewController(animated: true)
    }
}

extension BaseViewController: UIGestureRecognizerDelegate {

    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return (navigationController?.viewControllers.count ?? 0) > 1
    }

}
</code>```

So the back button is completely overridden for all view controllers to show desired image. This then produces an issue that the swipe breaks to go back to previous view controller so the delegate is taken to fix it.

Am I not very pleased with my solution but it seems to be the only one that woks consistently throughout the iOS versions.

Do note that if you use the stupid controllers like UITableViewController or UITabBarViewController you will need to subclass those as well and add the same code in them.

As for the navigation view controller I suggest you subclass it as well and/or even subclass the UINavigationBar. This way you will have a complete control over what is going on and the appearance of it.

Body:
I am setting navigation bar back button in AddDelegate but it is not setting properly.

I have tried below code :

let backButtonImage = backImage?.withRenderingMode(.alwaysOriginal).resizableImage(withCapInsets: UIEdgeInsetsMake((backImage?.size.height)!, (backImage?.size.width)!, 0, 0))
UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-400, 0), for: .default)

from here .

But the UI is not correct:

I have also tried below code :

UINavigationBar.appearance().backIndicatorImage = backButtonImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backButtonImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)

which looks like this:

But it is giving constraint issues in the terminal:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600000098510 UILayoutGuide:0x6040007aca20'BackButtonGuide(0x7f8143611390)'.height == 44   (active)>",
    "<NSLayoutConstraint:0x60000029e320 _UIButtonBarButton:0x7f814349d110.top == UILayoutGuide:0x6040007aca20'BackButtonGuide(0x7f8143611390)'.top   (active)>",
    "<NSLayoutConstraint:0x60000029de20 _UIButtonBarButton:0x7f814349d110.bottom == UILayoutGuide:0x6040007aca20'BackButtonGuide(0x7f8143611390)'.bottom   (active)>",
    "<NSLayoutConstraint:0x60400049d790 _UIModernBarButton:0x7f81434a4800'Back'.lastBaseline == UILayoutGuide:0x6000001b51c0'UIViewLayoutMarginsGuide'.bottom - 80   (active)>",
    "<NSLayoutConstraint:0x60400049d1a0 _UIModernBarButton:0x7f81434a4800'Back'.top >= _UIButtonBarButton:0x7f814349d110.top   (active)>",
    "<NSLayoutConstraint:0x600000481040 UIButtonLabel:0x7f81434a30d0'Back'.centerY == _UIModernBarButton:0x7f81434a4800'Back'.centerY + 1.5   (active)>",
    "<NSLayoutConstraint:0x60000029ea00 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x6000001b51c0'UIViewLayoutMarginsGuide']-(16)-|   (active, names: '|':_UIButtonBarButton:0x7f814349d110 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000481040 UIButtonLabel:0x7f81434a30d0'Back'.centerY == _UIModernBarButton:0x7f81434a4800'Back'.centerY + 1.5   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

[LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
    Try this:
    (1) look at each constraint and try to figure out which you don't expect;

(2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x60000029f1d0 _UIModernBarButton:0x7f814360f630.bottom == UILayoutGuide:0x6040007ac940'UIViewLayoutMarginsGuide'.bottom + 84.5   (active)>",
    "<NSLayoutConstraint:0x600000287bc0 V:[_UIModernBarButton:0x7f814360f630]-(>=0)-|   (active, names: '|':_UIButtonBarButton:0x7f814360d8a0 )>",
    "<NSLayoutConstraint:0x604000488930 'UIView-bottomMargin-guide-constraint' V:[UILayoutGuide:0x6040007ac940'UIViewLayoutMarginsGuide']-(16)-|   (active, names: '|':_UIButtonBarButton:0x7f814360d8a0 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000029f1d0 _UIModernBarButton:0x7f814360f630.bottom == UILayoutGuide:0x6040007ac940'UIViewLayoutMarginsGuide'.bottom + 84.5   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Is there any other way of doing it or I am doing something wrong ?

Body:
Someone might post a better answer but my solution was giving up on these nonsense with navigation bar and its appearance so what I did was create a base view controller for all view controllers I use inside the application. (I do that anyway so I am able to control things like status bar style, translation...).

So my base view controller looks somewhat like:

class BaseViewController: UIViewController {

    @IBInspectable var backButtonImage: UIImage? = /*Use your default here*/

    override func viewDidLoad() {
        super.viewDidLoad()

        if let backButtonImage = backButtonImage {
           navigationItem.leftBarButtonItem = UIBarButtonItem(image: backButtonImage, style: .plain, target: self, action: #selector(onBack))
           navigationController?.interactivePopGestureRecognizer?.delegate = self
        }
    }

    @objc private func onBack() {
        navigationController?.popViewController(animated: true)
    }
}

extension BaseViewController: UIGestureRecognizerDelegate {

    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return (navigationController?.viewControllers.count ?? 0) > 1
    }

}

So the back button is completely overridden for all view controllers to show desired image. This then produces an issue that the swipe breaks to go back to previous view controller so the delegate is taken to fix it.

Am I not very pleased with my solution but it seems to be the only one that woks consistently throughout the iOS versions.

Do note that if you use the stupid controllers like UITableViewController or UITabBarViewController you will need to subclass those as well and add the same code in them.

As for the navigation view controller I suggest you subclass it as well and/or even subclass the UINavigationBar. This way you will have a complete control over what is going on and the appearance of it.


问:
Segment a region in Depth Image of Microsoft Kinect using Open CV Python
I am working on Hand Segmentation using Microsoft Kinect Depth Stream. By doing some thresholding I was able to separate body from background, based on depth information provided by MS Kinect Sensor now I want is to segment hands. Any suggestions how can I segment Hands. Below is a screen shot of my depth Image.
I am using  Open CV in Python. To access Kinect Sensor streams, I am using PyKinect from Microsoft.

答:
What you need is a semantic segmentation algorithm. Random decision forests gave fantastic results. Check the work published by Haggag et al. It is built on top of the work done by Shotton et al and Buys et al. </p>

<p>If you want to use deep learning, check the work done by Abubakr et al. </p>

Body:
What you need is a semantic segmentation algorithm. Random decision forests gave fantastic results. Check the work published by Haggag et al. It is built on top of the work done by Shotton et al and Buys et al.

If you want to use deep learning, check the work done by Abubakr et al.


问:
Insert a snippet from a Visual Studio macro
I have a situation where I want to run a Visual Studio macro that has the user type something in an InputBox, then inserts a snippet and includes that text somewhere in it.  Unfortunately, I can't figure out how to insert the snippet from macro code.  It seems like it'd be something like

```<code>DTE.ExecuteCommand("Edit.InvokeSnippetFromShortcut")
</code>```

or

```<code>DTE.ExecuteCommand("Edit.InvokeSnippetFromShortcut", "theSnippetName")
</code>```

but those don't work.  Any ideas?

答:
You can insert a snippet with the following code.

```<code>DTE.ActiveDocument.Selection.Text = "snippetshortcut"
DTE.ExecuteCommand("Edit.InsertTab")
</code>```

If you are using VS 2010 then you will need to call DTE.ExecuteCommand("Edit.InsertTab") twice.

Body:
I have a situation where I want to run a Visual Studio macro that has the user type something in an InputBox, then inserts a snippet and includes that text somewhere in it.  Unfortunately, I can't figure out how to insert the snippet from macro code.  It seems like it'd be something like

DTE.ExecuteCommand("Edit.InvokeSnippetFromShortcut")

or

DTE.ExecuteCommand("Edit.InvokeSnippetFromShortcut", "theSnippetName")

but those don't work.  Any ideas?

Body:
You can insert a snippet with the following code.

DTE.ActiveDocument.Selection.Text = "snippetshortcut"
DTE.ExecuteCommand("Edit.InsertTab")

If you are using VS 2010 then you will need to call DTE.ExecuteCommand("Edit.InsertTab") twice.


问:
How to run Python test case with Appium?
I've created simple test case using Python (in PyCharm editor) which should click on Join/Login button on iOS app, but it doesn't work. Here is the code:

```<code>from appium import webdriver
import unittest
import os

class LoginTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'iOS'
        desired_caps['platformVersion'] = '11.0'
        desired_caps['deviceName'] = 'iPhone Simulator' # Run on simulator
        desired_caps['bundleId'] = 'com.matchbook.MatchbookApp'
        desired_caps['app'] = os.path.abspath('/Users/majdukovic/Library/Developer/Xcode/DerivedData/MatchBook-bgvchkbwrithuaegnjgpoffewdag/Build/Products/Debug-iphonesimulator/MatchBook.app') # Path to .app
        self.wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
        self.wd.implicitly_wait(60)
        loginButton = self.wd.find_element_by_id("JOIN/LOGIN") # Button ID
        self.assertTrue(loginButton.is_displayed())
        loginButton.click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
    unittest.TextTestRunner(verbosity=2).run(suite)
</code>```

If I run this test case it returns:
"Ran 0 tests in 0.000s

OK"

Appium server is already running and app is opened. In PyCharm Preferences I've selected py.test as default test runner.

Details of my setup:

macOS - HighSierra v10.13

Appium desktop app - v1.2.6

Python - v2.7.10

xCode - v9.0.1

Simulator - iPhone 8, iOS v11.0

答:
How about simple code like:</p>

```<code>if __name__ == '__main__':
  unittest.main()
</code>```

Body:
I've created simple test case using Python (in PyCharm editor) which should click on Join/Login button on iOS app, but it doesn't work. Here is the code:

from appium import webdriver
import unittest
import os

class LoginTests(unittest.TestCase):
    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'iOS'
        desired_caps['platformVersion'] = '11.0'
        desired_caps['deviceName'] = 'iPhone Simulator' # Run on simulator
        desired_caps['bundleId'] = 'com.matchbook.MatchbookApp'
        desired_caps['app'] = os.path.abspath('/Users/majdukovic/Library/Developer/Xcode/DerivedData/MatchBook-bgvchkbwrithuaegnjgpoffewdag/Build/Products/Debug-iphonesimulator/MatchBook.app') # Path to .app
        self.wd = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
        self.wd.implicitly_wait(60)
        loginButton = self.wd.find_element_by_id("JOIN/LOGIN") # Button ID
        self.assertTrue(loginButton.is_displayed())
        loginButton.click()

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(LoginTests)
    unittest.TextTestRunner(verbosity=2).run(suite)

If I run this test case it returns:
"Ran 0 tests in 0.000s

OK"

Appium server is already running and app is opened. In PyCharm Preferences I've selected py.test as default test runner.

Details of my setup:

macOS - HighSierra v10.13

Appium desktop app - v1.2.6

Python - v2.7.10

xCode - v9.0.1

Simulator - iPhone 8, iOS v11.0

Body:
How about simple code like:

if __name__ == '__main__':
  unittest.main()


答:
From reference of @Rajamohan-s answer:

Change UINavigationBar back button text and font from AppDelegate using Swift

You can do it with below code;

```<code> extension UINavigationItem{

    override open func awakeFromNib() {
        super.awakeFromNib()

        let backItem = UIBarButtonItem()
        backItem.title = "Hello"

        if let font = UIFont(name: "Copperplate-Light", size: 32){
            backItem.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
        }else{

            print("Font Not available")
        }
        /*Changing color*/
        backItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.green], for: .normal)

        self.backBarButtonItem = backItem
    }

}
</code>```

Title: Setting Navigation bar back button Image for entire application in swift

Body:
From reference of @Rajamohan-s answer:

Change UINavigationBar back button text and font from AppDelegate using Swift

You can do it with below code;

 extension UINavigationItem{

    override open func awakeFromNib() {
        super.awakeFromNib()

        let backItem = UIBarButtonItem()
        backItem.title = "Hello"

        if let font = UIFont(name: "Copperplate-Light", size: 32){
            backItem.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
        }else{

            print("Font Not available")
        }
        /*Changing color*/
        backItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.green], for: .normal)

        self.backBarButtonItem = backItem
    }

}


问:
JavaFX + Maven + Ojdbc6 + IntelliJ (deploy oracle jar with Javafx application for windows)
I've been trying to deploy my JavaFX application with the Oracle client (ojdbc6) embedded into the same jar.

The application runs fine and connects to the database if I'm running it through IntelliJ, but once I run the "package" task and try and run the application from double clicking the jar or running:

```<code>"java -jar .\maven-Newton-1.0-SNAPSHOT.jar"
</code>```

The application starts, but it won't connect to the DB:

`

In the code I've tried both:

```<code>Class.forName("oracle.jdbc.driver.OracleDriver");
</code>```

and

```<code>Class.forName("oracle.jdbc.OracleDriver");
</code>```

I'm just starting with maven and I'm not too sure if my configurations are correct:

• I've tried adding the ojdbc6.jar to the global libraries:

• I've tried adding the ojdbc6.jar file to the SDK classpath:

• And I've messed around with the module dependencies:

But my problem may be lying on the POM file because the other jar that I want to embed within my application is not deploying as well (org.reflections)

• pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>Newton</groupId>
    <artifactId>maven-Newton</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <!-- Build an executable JAR -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>Controller.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>true</overWriteSnapshots>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.reflections</groupId>
                <artifactId>reflections</artifactId>
                <version>0.9.11</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
            </plugin>
            <plugin>
                <!-- https://mvnrepository.com/artifact/oracle/ojdbc6 -->
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc6</artifactId>
                <version>11.2.0</version>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0</version>
        </dependency>
    </dependencies>

</project>
</code>```

Not too sure where to go from here, any help would be very much appreciated.

Thanks

答:
The problem is that the single jar file, you produce with the 'package' goal does not contain the ojdbc.jar in itself.
You will have to run the jar file with a classpath, e.g.

```<code>java -cp ojdbc.jar;othernecessary.jar maven-newton-project-1.0.jar
</code>```

Btw, there is a distinction in maven between dependencies (which are needed for the code to work) and plugins (which are needed for maven to build). You dependency on maven-compiler-plugin and maven-resource-plugin suggests to me you are confusing these two concepts.

I would move these two into the section called <build><plugins> instead alongside the maven-jar-plugin.

If you want an easy to comprehend start, try this: http://www.darrencoxall.com/java/understanding-maven/

Body:
I've been trying to deploy my JavaFX application with the Oracle client (ojdbc6) embedded into the same jar.

The application runs fine and connects to the database if I'm running it through IntelliJ, but once I run the "package" task and try and run the application from double clicking the jar or running:

"java -jar .\maven-Newton-1.0-SNAPSHOT.jar"

The application starts, but it won't connect to the DB:

`

In the code I've tried both:

Class.forName("oracle.jdbc.driver.OracleDriver");

and

Class.forName("oracle.jdbc.OracleDriver");

I'm just starting with maven and I'm not too sure if my configurations are correct:

• I've tried adding the ojdbc6.jar to the global libraries:

• I've tried adding the ojdbc6.jar file to the SDK classpath:

• And I've messed around with the module dependencies:

But my problem may be lying on the POM file because the other jar that I want to embed within my application is not deploying as well (org.reflections)

• pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>Newton</groupId>
    <artifactId>maven-Newton</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>

                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>Controller.Main</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}</outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>true</overWriteSnapshots>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.reflections</groupId>
                <artifactId>reflections</artifactId>
                <version>0.9.11</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
            </plugin>
            <plugin>

                <groupId>com.oracle</groupId>
                <artifactId>ojdbc6</artifactId>
                <version>11.2.0</version>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0</version>
        </dependency>
    </dependencies>

</project>

Not too sure where to go from here, any help would be very much appreciated.

Thanks

Body:
The problem is that the single jar file, you produce with the 'package' goal does not contain the ojdbc.jar in itself.
You will have to run the jar file with a classpath, e.g.

java -cp ojdbc.jar;othernecessary.jar maven-newton-project-1.0.jar

Btw, there is a distinction in maven between dependencies (which are needed for the code to work) and plugins (which are needed for maven to build). You dependency on maven-compiler-plugin and maven-resource-plugin suggests to me you are confusing these two concepts.

I would move these two into the section called <build><plugins> instead alongside the maven-jar-plugin.

If you want an easy to comprehend start, try this: http://www.darrencoxall.com/java/understanding-maven/


问:
Activity is closed after onActivityResult is called
Activity Explanation:

Activity_A ... nfc activity that gets started when tag is read

Activity_B ... activity to capture user signature

Hi, my problem goes like that:
I have Activity_A and in that activity I call Activity_B with startActivityForResult() method. I then do some work in Activity_B and close it. After that method onActivityResult() is called in my Activity_A. I handle the returned data and all is great, but Activity_A is no longer visible.

If I close Activity_B with back button, then Activity_A is still visible. (onActivityResult() doesn't get called).

I would like my Activity_A to stay active and visible when I return from Activity_B.

I have tested on 2 devices both running Kitkat (4.4.2 and 4.4.4).
I can't test it on emulator, since Activity_A is NFC activity.

onActivityResult code:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult is called");
    switch(requestCode) {
        case SIGNATURE_ACTIVITY:
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                String signatureFile = data.getStringExtra("SIGNATURE_FILE");
                if(signatureFile !=null ) {
                    this.showToastMessage("Signature captured!");
                    presenter.loadSignatureImage(signatureFile);
                } else {
                    this.showToastMessage("Signature filename not returned!");
                }
            }
            break;
    }
}
</code>```

答:
Make sure you are not using         intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

before starting the current activity.

Body:
Activity Explanation:

Activity_A ... nfc activity that gets started when tag is read

Activity_B ... activity to capture user signature

Hi, my problem goes like that:
I have Activity_A and in that activity I call Activity_B with startActivityForResult() method. I then do some work in Activity_B and close it. After that method onActivityResult() is called in my Activity_A. I handle the returned data and all is great, but Activity_A is no longer visible.

If I close Activity_B with back button, then Activity_A is still visible. (onActivityResult() doesn't get called).

I would like my Activity_A to stay active and visible when I return from Activity_B.

I have tested on 2 devices both running Kitkat (4.4.2 and 4.4.4).
I can't test it on emulator, since Activity_A is NFC activity.

onActivityResult code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult is called");
    switch(requestCode) {
        case SIGNATURE_ACTIVITY:
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                String signatureFile = data.getStringExtra("SIGNATURE_FILE");
                if(signatureFile !=null ) {
                    this.showToastMessage("Signature captured!");
                    presenter.loadSignatureImage(signatureFile);
                } else {
                    this.showToastMessage("Signature filename not returned!");
                }
            }
            break;
    }
}


问:
ICalendar and event updates not working in Outlook
I'm generating ICalendar (.ics) files.

Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event

How do I get them to work for Outlook ?

Thanks

Tom

答:
I am using outlook 2003 (from reading the posts, 2007 appears to behave in the same way) and you need to clearly distinguish between the behaviour of the explicit file import of an ics file and the implicit import when an ics file is 'double clicked'.

On the Outlook menu File / Import and Export ... Outlook will load as many VEVENT entries as are in the file and no amount of changing UID:, SEQUENCE: or DTSTAMP: values changes this, i.e.if you change any data and re-import it you just get a duplicate set of entries.

If you double click on an ics file it processes the first VEVENT entry only.  However it does recognise the UID and, if the DTSTAMP: is later (the SEQUENCE can be the same but not lower) you will be prompted and it will update the event in your calendar.

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:www.membership-services.net
METHOD:REQUEST
BEGIN:VEVENT
DTSTART:20090126T210000
DTEND:20090126T220000
SUMMARY:Avondale - Thameside Away Game vs Croydon
LOCATION:Whitgift School
DESCRIPTION:http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=CR2+6YT
UID:AWPC_8
SEQUENCE:0
DTSTAMP:20090123T112600
END:VEVENT
BEGIN:VEVENT
DTSTART:20090202T213000
DTEND:20090202T223000
SUMMARY:Avondale - Thameside Home Game vs Orcas
LOCATION:Putney
DESCRIPTION:http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&ie=UTF8&ll=51.4635,-0.2285&spn=0.005,0.009613&t=h&z=17&iwloc=lyrftr:w2t.90,0x48760f04a04b1801:0x49ebf12503a5d5a9,51.463459,-0.228674
UID:AWPC_10
SEQUENCE:0
DTSTAMP:20090123T112600
END:VEVENT
END:VCALENDAR
</code>```

OwnerDisplayName: Tom Carter

LastEditorDisplayName: Tom Carter

Body:
I am using outlook 2003 (from reading the posts, 2007 appears to behave in the same way) and you need to clearly distinguish between the behaviour of the explicit file import of an ics file and the implicit import when an ics file is 'double clicked'.

On the Outlook menu File / Import and Export ... Outlook will load as many VEVENT entries as are in the file and no amount of changing UID:, SEQUENCE: or DTSTAMP: values changes this, i.e.if you change any data and re-import it you just get a duplicate set of entries.

If you double click on an ics file it processes the first VEVENT entry only.  However it does recognise the UID and, if the DTSTAMP: is later (the SEQUENCE can be the same but not lower) you will be prompted and it will update the event in your calendar.

BEGIN:VCALENDAR
VERSION:2.0
PRODID:www.membership-services.net
METHOD:REQUEST
BEGIN:VEVENT
DTSTART:20090126T210000
DTEND:20090126T220000
SUMMARY:Avondale - Thameside Away Game vs Croydon
LOCATION:Whitgift School
DESCRIPTION:http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=CR2+6YT
UID:AWPC_8
SEQUENCE:0
DTSTAMP:20090123T112600
END:VEVENT
BEGIN:VEVENT
DTSTART:20090202T213000
DTEND:20090202T223000
SUMMARY:Avondale - Thameside Home Game vs Orcas
LOCATION:Putney
DESCRIPTION:http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&ie=UTF8&ll=51.4635,-0.2285&spn=0.005,0.009613&t=h&z=17&iwloc=lyrftr:w2t.90,0x48760f04a04b1801:0x49ebf12503a5d5a9,51.463459,-0.228674
UID:AWPC_10
SEQUENCE:0
DTSTAMP:20090123T112600
END:VEVENT
END:VCALENDAR


问:
Old skype issues
I can't find any info on that so I am wondering maybe anyone have found any bypasses.

The issue is that skype stopped supporting old version, and I am forced to use web skype, or new skype for linux which doesn't meet my expectations.

When I launch old skype login screen pops, I enter my credentials and after clicking 'login' skype just exits.

I am using MINT 17.02.

Thank you.

答:
Skype runs on a closed, centrally  controlled communications protocolS. The controller of said protocol had advertised that the client version you are trying to use would no longer be operational after a certain date.

That is what happened.

Probably the protocol itself has migrated away from one that is known by the old skype client. There is a little chance however that the server just check the client by some version signature, much like web browsers send the User-Agent string.

In both cases, you'd have to binary patch the skype client to change the way it communicates with the server. If the protocol has not changed much, it would be just a matter of changing the client-identification string. But even if the protocol has not changed much, changing the client-id might already change the way the server communicates with the client, rendering it a paperweight.

If the protocol actually changed, then it is about 2 orders of magnitude worse: you'd have to reverse engineer the protocol, create a working implementation, and patch the old client to use it.

So, to sum up, if it is not obvious yet: you can't do that. Either use the web client, or change your messaging platform.

Title: Old skype issues


问:
Time for getting by comparable key from HashMap
AFAIK since java 8 bucket structure was changed from linked list to tree.

So in case hashCode() method return constant and our key class implements Comparable interface then complexity to get element from single cell will be reduced from O(n) to O(log n).

I tried to check it:

```<code> public static void main(String[] args) {
    int max = 30000;
    int times = 100;
    HashMap<MyClass, Integer> map = new HashMap<>();
    HashMap<MyComparableClass, Integer> compMap = new HashMap<>();

    for(int i = 0; i < max; i++) {
        map.put(new MyClass(i), i);
        compMap.put(new MyComparableClass(i), i);
    }

    long startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        compMap.get(new MyComparableClass(i));
    }
    System.out.println(String.format("Key is comparable:    %d", System.nanoTime() - startTime));

    startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        map.get(new MyClass(i));
    }
    System.out.println(String.format("Key isn't comparable: %d", System.nanoTime() - startTime));
}
</code>```

MyComparableClass:

```<code>public class MyComparableClass
        implements Comparable {
    public Integer value;

    public MyComparableClass(Integer value) {
        this.value = value;
    }

    @Override
    public int compareTo(Object o) {
        return this.value - ((MyComparableClass) o).value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyComparableClass myClass = (MyComparableClass) o;

        return value != null ? value.equals(myClass.value) : myClass.value == null;
    }

    @Override
    public int hashCode() {
        return 1;
    }
}
</code>```

MyClass is the same as MyComparableClass but doesn't implement Comparable interface.

And unexpectedly i always get results where time for getting value by non comparable key less than by comparable.

```<code>Key is comparable:    23380708
Key isn't comparable: 10721718
</code>```

Can someone explain?

答:
It still uses a binary tree even if your class is not comparable! As explained in https://stackoverflow.com/a/30180593/638028, it uses lower-level ways to compare two objects (such as System.identityHashCode) and your results are probably a combination of:

Not enough iterations, thereby not comparing JIT-compiled versions. Try reversing the timings (do non-comparable first, and then comparable) and see if you get different results. Use JMH to do proper benchmarking.

Calling your own compareTo method is not as fast as the methods HashMap uses internally for comparing non-comparables.

You are also timing the performance of the memory allocator, since you are creating a new class to pass to HashMap.get in each iteration (though the JVM will eventually perform escape analysis when the JIT compiler kicks in, and will turn this into a stack allocation).

Body:
AFAIK since java 8 bucket structure was changed from linked list to tree.

So in case hashCode() method return constant and our key class implements Comparable interface then complexity to get element from single cell will be reduced from O(n) to O(log n).

I tried to check it:

 public static void main(String[] args) {
    int max = 30000;
    int times = 100;
    HashMap<MyClass, Integer> map = new HashMap<>();
    HashMap<MyComparableClass, Integer> compMap = new HashMap<>();

    for(int i = 0; i < max; i++) {
        map.put(new MyClass(i), i);
        compMap.put(new MyComparableClass(i), i);
    }

    long startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        compMap.get(new MyComparableClass(i));
    }
    System.out.println(String.format("Key is comparable:    %d", System.nanoTime() - startTime));

    startTime = System.nanoTime();
    for (int i = max; i > max - times; i--){
        map.get(new MyClass(i));
    }
    System.out.println(String.format("Key isn't comparable: %d", System.nanoTime() - startTime));
}

MyComparableClass:

public class MyComparableClass
        implements Comparable {
    public Integer value;

    public MyComparableClass(Integer value) {
        this.value = value;
    }

    @Override
    public int compareTo(Object o) {
        return this.value - ((MyComparableClass) o).value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyComparableClass myClass = (MyComparableClass) o;

        return value != null ? value.equals(myClass.value) : myClass.value == null;
    }

    @Override
    public int hashCode() {
        return 1;
    }
}

MyClass is the same as MyComparableClass but doesn't implement Comparable interface.

And unexpectedly i always get results where time for getting value by non comparable key less than by comparable.

Key is comparable:    23380708
Key isn't comparable: 10721718

Can someone explain?


问:
Avoiding comma separator for the last value
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
</code>```

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

答:
If you change how you output to write the first object in the collection then everyone after preceded by a comma it should work fine.

```<code>        Response.Write("(" + "{");
        //
        Response.Write(Convert.ToString(k.GetValue(0)));
        for (Int32 i = 1; i < k.Length; i++)
        {
            Response.Write("," + Convert.ToString(k.GetValue(i)));
        }
        //
        Response.Write("}" + ")");
</code>```

An alternative would be writing to a stringbuilder and outputting all but the last character

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

Body:
If you change how you output to write the first object in the collection then everyone after preceded by a comma it should work fine.

        Response.Write("(" + "{");
        //
        Response.Write(Convert.ToString(k.GetValue(0)));
        for (Int32 i = 1; i < k.Length; i++)
        {
            Response.Write("," + Convert.ToString(k.GetValue(i)));
        }
        //
        Response.Write("}" + ")");

An alternative would be writing to a stringbuilder and outputting all but the last character


问:
Error: unexpected '}' in "}"
My code is as follows,

```<code>`FARS = read.csv("C:\\Users\\rb138\\Desktop\\FARS.csv", header = T, sep = ",", na.strings=c(""," ","NA-code","NA"))

Preprocessing = process() {

  FARS$X = NULL
  library(caTools)
  is.na(FARS) <- FARS == "NULL"
  miss<-function(x)
  {
    return(sum(is.na(x)/length(x)*100))
  }
  apply(FARS,2,FUN = miss)
  Mode <- function (x, na.rm) {
    xtab <- table(x)
    xmode <- names(which(xtab == max(xtab)))
    if (length(xmode) > 1) xmode <- ">1 mode"
    return(xmode)
  }
  for (var in 1:ncol(FARS)) {
    if (class(FARS[,var])=="numeric") {
      FARS[is.na(FARS[,var]),var] <- mean(FARS[,var], na.rm = TRUE)
    } else if (class(FARS[,var]) %in% c("character", "factor")) {
      FARS[is.na(FARS[,var]),var] <- Mode(FARS[,var], na.rm = TRUE)
    }
    }
  set.seed(45)
  split = sample.split(FARS$airbagDeploy, SplitRatio = 0.70)
  Train1 = subset(FARS, split == TRUE)
  Test1 = subset(FARS, split == FALSE)

  }`
</code>```

If is pass it outside the object it is not throwing any error. But when i am running it inside the function its throwing the following exception:

Error: unexpected '}' in "  }"

Also when i trying to save the Object in a RDS file, code as follows :

saveRDS(Preprocessing, file = "preprocessing_script.rds")

its is throwing the following exception :

Error in saveRDS(Preprocessing, file = "preprocessing_script.rds") :
  object 'Preprocessing' not found

Data set used for this is FARS.csv from the package "gamclass" in R.
In case if anyone requires the dataset, kindly as in your comments.

Thank you in advance.

答:
Try modifying your code like this with separate function:

```<code>FARS = read.csv("C:\\Users\\rb138\\Desktop\\FARS.csv", header = T, sep = ",", na.strings=c(""," ","NA-code","NA"))

Preprocessing = function(FARS) {

  FARS$X = NULL
  library(caTools)
  is.na(FARS) <- FARS == "NULL"
  miss<-function(x)
  {
    return(sum(is.na(x)/length(x)*100))
  }
  apply(FARS,2,FUN = miss)
  Mode <- function (x, na.rm) {
    xtab <- table(x)
    xmode <- names(which(xtab == max(xtab)))
    if (length(xmode) > 1) xmode <- ">1 mode"
    return(xmode)
  }
  for (var in 1:ncol(FARS)) {
    if (class(FARS[,var])=="numeric") {
      FARS[is.na(FARS[,var]),var] <- mean(FARS[,var], na.rm = TRUE)
    } else if (class(FARS[,var]) %in% c("character", "factor")) {
      FARS[is.na(FARS[,var]),var] <- Mode(FARS[,var], na.rm = TRUE)
    }
    }
  set.seed(45)
  split = sample.split(FARS$airbagDeploy, SplitRatio = 0.70)
  Train1 = subset(FARS, split == TRUE)
  Test1 = subset(FARS, split == FALSE)

  }

Preprocessing(FARS)
</code>```

Let me know if it works!

Title: Error: unexpected '}' in "}"

Body:
My code is as follows,

`FARS = read.csv("C:\\Users\\rb138\\Desktop\\FARS.csv", header = T, sep = ",", na.strings=c(""," ","NA-code","NA"))

Preprocessing = process() {

  FARS$X = NULL
  library(caTools)
  is.na(FARS) <- FARS == "NULL"
  miss<-function(x)
  {
    return(sum(is.na(x)/length(x)*100))
  }
  apply(FARS,2,FUN = miss)
  Mode <- function (x, na.rm) {
    xtab <- table(x)
    xmode <- names(which(xtab == max(xtab)))
    if (length(xmode) > 1) xmode <- ">1 mode"
    return(xmode)
  }
  for (var in 1:ncol(FARS)) {
    if (class(FARS[,var])=="numeric") {
      FARS[is.na(FARS[,var]),var] <- mean(FARS[,var], na.rm = TRUE)
    } else if (class(FARS[,var]) %in% c("character", "factor")) {
      FARS[is.na(FARS[,var]),var] <- Mode(FARS[,var], na.rm = TRUE)
    }
    }
  set.seed(45)
  split = sample.split(FARS$airbagDeploy, SplitRatio = 0.70)
  Train1 = subset(FARS, split == TRUE)
  Test1 = subset(FARS, split == FALSE)

  }`

If is pass it outside the object it is not throwing any error. But when i am running it inside the function its throwing the following exception:

Error: unexpected '}' in "  }"

Also when i trying to save the Object in a RDS file, code as follows :

saveRDS(Preprocessing, file = "preprocessing_script.rds")

its is throwing the following exception :

Error in saveRDS(Preprocessing, file = "preprocessing_script.rds") :
  object 'Preprocessing' not found

Data set used for this is FARS.csv from the package "gamclass" in R.
In case if anyone requires the dataset, kindly as in your comments.

Thank you in advance.

Body:
Try modifying your code like this with separate function:

FARS = read.csv("C:\\Users\\rb138\\Desktop\\FARS.csv", header = T, sep = ",", na.strings=c(""," ","NA-code","NA"))

Preprocessing = function(FARS) {

  FARS$X = NULL
  library(caTools)
  is.na(FARS) <- FARS == "NULL"
  miss<-function(x)
  {
    return(sum(is.na(x)/length(x)*100))
  }
  apply(FARS,2,FUN = miss)
  Mode <- function (x, na.rm) {
    xtab <- table(x)
    xmode <- names(which(xtab == max(xtab)))
    if (length(xmode) > 1) xmode <- ">1 mode"
    return(xmode)
  }
  for (var in 1:ncol(FARS)) {
    if (class(FARS[,var])=="numeric") {
      FARS[is.na(FARS[,var]),var] <- mean(FARS[,var], na.rm = TRUE)
    } else if (class(FARS[,var]) %in% c("character", "factor")) {
      FARS[is.na(FARS[,var]),var] <- Mode(FARS[,var], na.rm = TRUE)
    }
    }
  set.seed(45)
  split = sample.split(FARS$airbagDeploy, SplitRatio = 0.70)
  Train1 = subset(FARS, split == TRUE)
  Test1 = subset(FARS, split == FALSE)

  }

Preprocessing(FARS)

Let me know if it works!


问:
*ngIf equivalent in TypeScript code
How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

```<code><div *ngIf="exampleComponentProperty"></div>
</code>```

Is it possible to do the same check in .ts? How would the expression look then?

```<code>if (this.exampleComponentProperty != null) {
// some code...
}
</code>```

did not seem to work.

答:
You can try condition with avoiding all the possibilities :

In TS :

```<code>if (this.exampleComponentProperty && this.exampleComponentProperty != undefined && this.exampleComponentProperty != null) {
    // write code...
}
</code>```

In HTML :

```<code> <div *ngIf="exampleComponentProperty && exampleComponentProperty != undefined && exampleComponentProperty != null"></div>
</code>```

Title: *ngIf equivalent in TypeScript code

Body:
How is it possible check if the component property is undefined within the TypeScript code, in a method for instance?

In .html component template it is possible to do such check as a conditional on displaying html elements. To avoid the diplay in case they do not exist or not initialized yet.

Is it possible to do the same check in .ts? How would the expression look then?

if (this.exampleComponentProperty != null) {
// some code...
}

did not seem to work.

Body:
You can try condition with avoiding all the possibilities :

In TS :

if (this.exampleComponentProperty && this.exampleComponentProperty != undefined && this.exampleComponentProperty != null) {
    // write code...
}

In HTML :

 <div *ngIf="exampleComponentProperty && exampleComponentProperty != undefined && exampleComponentProperty != null"></div>


问:
How to get index of Escape Character in a String?
How to get index of Escape Character  in a String?

```<code>String test="1234\567890";
System.out.println("Result : "+test.lastIndexOf("\\"));
</code>```

Result i get:
  -1

Result i need: 4

答:
I don't think you can get that because when you use an escape character is for java to interpret the following character in a special way. In another words, the escape character and the next character you see in the string are really one entity from the point of view of program being executed.

When you search for "\\", you are searching for the literal character '\' not the escape character.

Here you can see the difference: java fiddle

While \5 is the character with code 0x5 (ENQ), 5 is the character 0x35. See the table.

Body:
How to get index of Escape Character  in a String?

String test="1234\567890";
System.out.println("Result : "+test.lastIndexOf("\\"));

Result i get:
  -1

Result i need: 4


问:
Codeigniter, using Form validation for no POST data
I'm using CodeIngiter to create a restful app.

I was wondering if is it possible to use the FormValidation class with a non $_POST data.

I was thinking: if the client send a GET request in this way:

https://myrestapp.com/controller?firstValue=val&secondValue=val2

how can I validate firstValue and secondValue using this:

```<code>//example
$this->form_validation->set_rules('firstValue', , 'required');
$this->form_validation->set_rules(secondValue, , 'required|integer');
</code>```

and, how can I convert <?php echo validation_errors(); ?> with an associative array like array('firstValue' => "The field secondValue must be integer")

答:
As per my comment - you can pass an associative array to the form validation instead of using the default $_POST array.

Now you can get at the form validation errors array via $this->form_validation->error_array(). You can also customise the error messages ( Left for you to look up )

Based upon a controller called rest_app
/rest_app?firstValue=val&secondValue=2
the index method might look like this - with debug.

Change what you need to, to make it suit your needs. This is just a little demo code.

```<code>public function index() {
    $this->load->library('form_validation');
    // Need to test this exists?
    $str = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : NULL;
    if ($str !== NULL) {
        // Grab the Query string and turn it into an associative array
        parse_str($str, $url_query_array);
        // DEBUG - Check the array looks correct
        var_dump($url_query_array);

        // Give the form validation the fields/Values to work with.
        $this->form_validation->set_data($url_query_array);

        // Now for the Validation Rules
        $this->form_validation->set_rules('firstValue', 'firstValue', 'required');
        $this->form_validation->set_rules('secondValue', 'secondValue', 'required|integer');

        // Did we get a valid
        if ($this->form_validation->run()) {
            echo "We got what we wanted, so do some stuff"; // DEBUG ONLY
            // add your code here

        } else {
            echo "Well that didn't work well.";
            $error_associative_array = $this->form_validation->error_array();
            var_dump($error_associative_array); // DEBUG ONLY
            // Send $error_associative_array back as a response
        }

    } else {
        echo "No query string present";
        // Handle this as an error condition or die silently.
    }
}
</code>```

Body:
I'm using CodeIngiter to create a restful app.

I was wondering if is it possible to use the FormValidation class with a non $_POST data.

I was thinking: if the client send a GET request in this way:

https://myrestapp.com/controller?firstValue=val&secondValue=val2

how can I validate firstValue and secondValue using this:

//example
$this->form_validation->set_rules('firstValue', , 'required');
$this->form_validation->set_rules(secondValue, , 'required|integer');

and, how can I convert <?php echo validation_errors(); ?> with an associative array like array('firstValue' => "The field secondValue must be integer")

Body:
As per my comment - you can pass an associative array to the form validation instead of using the default $_POST array.

Now you can get at the form validation errors array via $this->form_validation->error_array(). You can also customise the error messages ( Left for you to look up )

Based upon a controller called rest_app
/rest_app?firstValue=val&secondValue=2
the index method might look like this - with debug.

Change what you need to, to make it suit your needs. This is just a little demo code.

public function index() {
    $this->load->library('form_validation');
    // Need to test this exists?
    $str = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : NULL;
    if ($str !== NULL) {
        // Grab the Query string and turn it into an associative array
        parse_str($str, $url_query_array);
        // DEBUG - Check the array looks correct
        var_dump($url_query_array);

        // Give the form validation the fields/Values to work with.
        $this->form_validation->set_data($url_query_array);

        // Now for the Validation Rules
        $this->form_validation->set_rules('firstValue', 'firstValue', 'required');
        $this->form_validation->set_rules('secondValue', 'secondValue', 'required|integer');

        // Did we get a valid
        if ($this->form_validation->run()) {
            echo "We got what we wanted, so do some stuff"; // DEBUG ONLY
            // add your code here

        } else {
            echo "Well that didn't work well.";
            $error_associative_array = $this->form_validation->error_array();
            var_dump($error_associative_array); // DEBUG ONLY
            // Send $error_associative_array back as a response
        }

    } else {
        echo "No query string present";
        // Handle this as an error condition or die silently.
    }
}


问:
Unable to install Jumble tool Eclipse
I am trying to use jumble tool with but unable to use install it in eclipse.I am following the steps given here.
http://jumble.sourceforge.net/
now when i try to add jumble link into add new software option i get error .
cannot find http://jumble.sourceforge.net.

Can anyone please help me with this ?

答:
The error you see is the following:

```<code>Unable to read repository at http://jumble.sourceforge.net/update/content.xml.
Unable to read repository at http://jumble.sourceforge.net/update/content.xml.
Received fatal alert: handshake_failure
</code>```

This is because of new SSL policies added by SourceForge. Indeed, in January 2017 they did a change in the security settings used by their download servers.

The problem is caused by SourceForge mandating the use of strong encryption, while the Oracle JDK, due to export restrictions, is not able to handle strong encryption.

As stated here:

The solution is to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. In practical terms, this means replacing two JAR files in the JRE /lib/security folder.

Alternatively you could download and install the plugin manually.

For example you can download the update site as a zip archive, unpack it locally and use this folder as an update site.

See here as a similar problem with another Eclipse plugin and the relative solution.

Title: Unable to install Jumble tool Eclipse

Body:
The error you see is the following:

Unable to read repository at http://jumble.sourceforge.net/update/content.xml.
Unable to read repository at http://jumble.sourceforge.net/update/content.xml.
Received fatal alert: handshake_failure

This is because of new SSL policies added by SourceForge. Indeed, in January 2017 they did a change in the security settings used by their download servers.

The problem is caused by SourceForge mandating the use of strong encryption, while the Oracle JDK, due to export restrictions, is not able to handle strong encryption.

As stated here:

The solution is to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. In practical terms, this means replacing two JAR files in the JRE /lib/security folder.

Alternatively you could download and install the plugin manually.

For example you can download the update site as a zip archive, unpack it locally and use this folder as an update site.

See here as a similar problem with another Eclipse plugin and the relative solution.


问:
Creating a nested array from a single array
I have a search function in my app which gets data from a fetchedResultsController. The problem is when I display the filtered data in the tableView everytime it gets to a new section, the array starts over and over (due to indexPath.row being 0 everytime indexPath.section increments). I've never been good at nested arrays and I thought this is the perfect time to learn them, since I can't get over my problem without this array.

So I have this array which is the filtered data out of the fetchedResultsController:

```<code>filteredItems = (fetchedResultsController.fetchedObjects?.filter({(budget : Budget) -> Bool in
 return (budget.dataDescription?.lowercased().contains(searchText.lowercased()))!
        }))!
</code>```

How can I make an array called filteredObjects which sorts my items for sections? For example

- Section 1 (  filteredObjects[0] ):

item 1 (  filteredObjects[0][1] )

item 2 (  filteredObjects[0][2] )

-

Section 2 ( filteredObjects[1] ):

item 1 ( filteredObjects[1][0] )
etc

答:
```<code>    let budgets = [Budget]()
    let searchResult = [Budget]()
</code>```

You should always use searchResult array in tableview datasource methods. initially you should add all objects of budgets array to searchResult & load table view.

when search started remove all items from searchResult and add filtered result to search result array & reload tableview.

```<code>    func search(searchText:String){
        searchResult.removeAll()
        let result = budgets.filter({
            var budget = $0
            let filtered = budget.expenses.filter({
                if let deptName = $0.deptName{
                    return deptName.lowercased().contains(searchText.lowercased())
                }
                return false
            })
            budget.expenses = filtered
            return budget.expenses.count != 0
        })

        searchResult.append(contentsOf: result)
    }

struct Budget {
    var expenses = [Expense]()
 }

 struct Expense{
    var deptName:String?
 }
</code>```

Body:
I have a search function in my app which gets data from a fetchedResultsController. The problem is when I display the filtered data in the tableView everytime it gets to a new section, the array starts over and over (due to indexPath.row being 0 everytime indexPath.section increments). I've never been good at nested arrays and I thought this is the perfect time to learn them, since I can't get over my problem without this array.

So I have this array which is the filtered data out of the fetchedResultsController:

filteredItems = (fetchedResultsController.fetchedObjects?.filter({(budget : Budget) -> Bool in
 return (budget.dataDescription?.lowercased().contains(searchText.lowercased()))!
        }))!

How can I make an array called filteredObjects which sorts my items for sections? For example

- Section 1 (  filteredObjects[0] ):

item 1 (  filteredObjects[0][1] )

item 2 (  filteredObjects[0][2] )

-

Section 2 ( filteredObjects[1] ):

item 1 ( filteredObjects[1][0] )
etc

Body:
    let budgets = [Budget]()
    let searchResult = [Budget]()

You should always use searchResult array in tableview datasource methods. initially you should add all objects of budgets array to searchResult & load table view.

when search started remove all items from searchResult and add filtered result to search result array & reload tableview.

    func search(searchText:String){
        searchResult.removeAll()
        let result = budgets.filter({
            var budget = $0
            let filtered = budget.expenses.filter({
                if let deptName = $0.deptName{
                    return deptName.lowercased().contains(searchText.lowercased())
                }
                return false
            })
            budget.expenses = filtered
            return budget.expenses.count != 0
        })

        searchResult.append(contentsOf: result)
    }

struct Budget {
    var expenses = [Expense]()
 }

 struct Expense{
    var deptName:String?
 }


答:
you can decrease your loop instead increase... like

for (Int32 i = k.Length; i > 0; i--)

and put: if (i == 1) removeComa;

Title: Avoiding comma separator for the last value