问:
Unable to connect to Metabase h2 DB
I can not initialize the metabase setup, as I am getting error when connecting metabase to h2 db.

I did so far as below

1.Downloaded metabase.jar from here

2.From cmd prompt i executed  java -jar metabase.jar

I am getting Below error

```<code> 04-25 12:03:07 INFO metabase.core :: Setting up and migrating Metabase DB. Please sit tight, this may take a minute...
04-25 12:03:07 INFO metabase.db :: Verifying h2 Database Connection ...
04-25 12:03:12 ERROR metabase.driver :: Failed to connect to database: Timed out after 5000 milliseconds.
java.lang.AssertionError: Assert failed: Unable to connect to Metabase h2 DB.
(binding [*allow-potentailly-unsafe-connections* true] (require (quote metabase.driver)) ((resolve (quote metabase.drive
r/can-connect-with-details?)) engine details))
        at metabase.db$verify_db_connection.invokeStatic(db.clj:320)
        at metabase.db$verify_db_connection.invoke(db.clj:313)
        at metabase.db$verify_db_connection.invokeStatic(db.clj:316)
        at metabase.db$verify_db_connection.invoke(db.clj:313)
        at metabase.db$setup_db_BANG_.invokeStatic(db.clj:368)
        at metabase.db$setup_db_BANG_.doInvoke(db.clj:362)
        at clojure.lang.RestFn.invoke(RestFn.java:421)
        at metabase.core$init_BANG_.invokeStatic(core.clj:102)
        at metabase.core$init_BANG_.invoke(core.clj:81)
        at metabase.core$start_normally.invokeStatic(core.clj:186)
        at metabase.core$start_normally.invoke(core.clj:180)
        at metabase.core$_main.invokeStatic(core.clj:278)
        at metabase.core$_main.doInvoke(core.clj:273)
        at clojure.lang.RestFn.invoke(RestFn.java:397)
        at clojure.lang.AFn.applyToHelper(AFn.java:152)
        at clojure.lang.RestFn.applyTo(RestFn.java:132)
        at metabase.core.main(Unknown Source)
04-25 12:03:12 ERROR metabase.core :: Metabase Initialization FAILED:  Assert failed: Unable to connect to Metabase h2 D
B.
(binding [*allow-potentailly-unsafe-connections* true] (require (quote metabase.driver)) ((resolve (quote metabase.drive
r/can-connect-with-details?)) engine details))
04-25 12:03:12 INFO metabase.core :: Metabase Shutting Down ...
04-25 12:03:12 INFO metabase.core :: Metabase Shutdown COMPLETE
</code>```

Initially I didn't get an error. I did everything in metabase. After 2 days, when I tried the same, I am getting this error. Even after deleting everything and tried from start again and also with admin permisions. Nothing worked same error.

答:
Try Opening command prompt with admin credentials and run the below command</p>

```<code>java -jar metabase.jar
</code>```

Title: Unable to connect to Metabase h2 DB

Body:
I can not initialize the metabase setup, as I am getting error when connecting metabase to h2 db.

I did so far as below

1.Downloaded metabase.jar from here

2.From cmd prompt i executed  java -jar metabase.jar

I am getting Below error

 04-25 12:03:07 INFO metabase.core :: Setting up and migrating Metabase DB. Please sit tight, this may take a minute...
04-25 12:03:07 INFO metabase.db :: Verifying h2 Database Connection ...
04-25 12:03:12 ERROR metabase.driver :: Failed to connect to database: Timed out after 5000 milliseconds.
java.lang.AssertionError: Assert failed: Unable to connect to Metabase h2 DB.
(binding [*allow-potentailly-unsafe-connections* true] (require (quote metabase.driver)) ((resolve (quote metabase.drive
r/can-connect-with-details?)) engine details))
        at metabase.db$verify_db_connection.invokeStatic(db.clj:320)
        at metabase.db$verify_db_connection.invoke(db.clj:313)
        at metabase.db$verify_db_connection.invokeStatic(db.clj:316)
        at metabase.db$verify_db_connection.invoke(db.clj:313)
        at metabase.db$setup_db_BANG_.invokeStatic(db.clj:368)
        at metabase.db$setup_db_BANG_.doInvoke(db.clj:362)
        at clojure.lang.RestFn.invoke(RestFn.java:421)
        at metabase.core$init_BANG_.invokeStatic(core.clj:102)
        at metabase.core$init_BANG_.invoke(core.clj:81)
        at metabase.core$start_normally.invokeStatic(core.clj:186)
        at metabase.core$start_normally.invoke(core.clj:180)
        at metabase.core$_main.invokeStatic(core.clj:278)
        at metabase.core$_main.doInvoke(core.clj:273)
        at clojure.lang.RestFn.invoke(RestFn.java:397)
        at clojure.lang.AFn.applyToHelper(AFn.java:152)
        at clojure.lang.RestFn.applyTo(RestFn.java:132)
        at metabase.core.main(Unknown Source)
04-25 12:03:12 ERROR metabase.core :: Metabase Initialization FAILED:  Assert failed: Unable to connect to Metabase h2 D
B.
(binding [*allow-potentailly-unsafe-connections* true] (require (quote metabase.driver)) ((resolve (quote metabase.drive
r/can-connect-with-details?)) engine details))
04-25 12:03:12 INFO metabase.core :: Metabase Shutting Down ...
04-25 12:03:12 INFO metabase.core :: Metabase Shutdown COMPLETE

Initially I didn't get an error. I did everything in metabase. After 2 days, when I tried the same, I am getting this error. Even after deleting everything and tried from start again and also with admin permisions. Nothing worked same error.

Body:
Try Opening command prompt with admin credentials and run the below command

java -jar metabase.jar


来源: stackexchange

问:
How to edit a cell and delete a row by clicking icon in Angular JS 1.3?
Still be a angular learner.

I have my page like

The code is:

```<code>    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div ng-controller="EmpCtrl">
    <div>
        <h2 align="center">Angular JS Basic Example</h2>
        <h5 align="center">Employee List</h5>
        <table border="1" cellpadding="10" align="center">
            <tr>
                <th>
                    Edit
                </th>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
                <th>
                    Delete
                </th>
            </tr>
            <tr ng-repeat="emp in employees">
                <td>
                    <a href="#" class="btn btn-default btn-sm">
                        <i class="glyphicon glyphicon-edit"></i>
                    </a>
                </td>
                <td>
                    {{emp.EmployeeId}}
                </td>
                <td>
                    {{emp.EmployeeName}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                    {{emp.EmailId}}
                </td>
                <td>
                    <a href="#"
                       onclick="return confirm('Delete this Employee?');"
                       class="btn btn-default btn-sm">
                        <i class="glyphicon glyphicon-trash"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
</div>
</code>```

I have the js code for getting all employees. It works well.

```<code>app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
 }
});
</code>```

My asp mvc service code to delete methos is

```<code> [HttpDelete]
    public void DeleteEmployee(int id)
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            var employeeList = db.EmployeeModels.ToList();
            var temp = employeeList.Find(x => x.EmployeeId == id);
            employeeList.Remove(temp);
            db.SaveChanges();
        }
    }
</code>```

I want to click the edit/delete icon to edit or delete, I guess that I have to add other javascript functions to do that.(Maybe ng-clcik??) But I don't know exactly, so how to edit a cell or delete a row?

答:
```<code><a href="#"
    ng-click="delFn(emp.EmployeeId)"
    class="btn btn-default btn-sm">
    <i class="glyphicon glyphicon-trash"></i>
  </a>
</td>
</code>```

//this way u can achieve it

```<code>$scope.delFn = function(id){

   EmployeeService.delEmployee(id).then(function (data) {
        GetAllEmployee();
    }, function () {
        alert('Data not found');
    });
}
</code>```

then add service

```<code>this.delEmployee= function (id) {
        return $http.post('controller/delEmployee', data={id:id});
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Still be a angular learner.

I have my page like

The code is:

    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Angular JS Basic Example

Employee List

                    Edit

                    Employee Id

                    Employee Name

                    Address

                    Email Id

                    Delete

                    {{emp.EmployeeId}}

                    {{emp.EmployeeName}}

                    {{emp.Address}}

                    {{emp.EmailId}}

I have the js code for getting all employees. It works well.

app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
 }
});

My asp mvc service code to delete methos is

 [HttpDelete]
    public void DeleteEmployee(int id)
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            var employeeList = db.EmployeeModels.ToList();
            var temp = employeeList.Find(x => x.EmployeeId == id);
            employeeList.Remove(temp);
            db.SaveChanges();
        }
    }

I want to click the edit/delete icon to edit or delete, I guess that I have to add other javascript functions to do that.(Maybe ng-clcik??) But I don't know exactly, so how to edit a cell or delete a row?

Body:
<a href="#"
    ng-click="delFn(emp.EmployeeId)"
    class="btn btn-default btn-sm">
    <i class="glyphicon glyphicon-trash"></i>
  </a>
</td>

//this way u can achieve it

$scope.delFn = function(id){

   EmployeeService.delEmployee(id).then(function (data) {
        GetAllEmployee();
    }, function () {
        alert('Data not found');
    });
}

then add service

this.delEmployee= function (id) {
        return $http.post('controller/delEmployee', data={id:id});
    }


问:
update multiple data codeigniter with checkbox
I am trying to update multiple data through AJAX but I have tried several times, but the data has not changed, please help to fix it in order to run perfectly.

Controllers:

```<code>function update_notif() {
    $this->My_model->update_multiple();
    $this->session->set_flashdata('msg',
                '<div class="callout callout-warning">
                    <h4>Success</h4>
                </div>');
}
</code>```

Models:

```<code>function update_multiple() {
    $update = $this->input->post('id_pesan');
    for ($i=0; $i < count($update) ; $i++) {
        $data = array('notif' => 0);
        $this->db->where('id', $delete[$i]);
        $this->db->update('my_table', $data);
    }
}
</code>```

Views:

```<code><button type="button" id="btn_delete" ></button>

<table class="table table-hover table-striped">
    <thead>
        <tr>
            <td><input id="selecctall" type="checkbox"></td>
            <td>No</td>
            <td>Name</td>
            <td>Telp</td>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($show_data as $row) { ?>
        <tr>
            <td><input type="checkbox" class="select_update" name="select_update[]" value="<?php echo $row->id; ?>"></td>
            <td><?php echo $row->no; ?></td>
            <td><?php echo $row->nama; ?></td>
            <td><?php echo $row->telp; ?></td>
        </tr>
    </tbody>
    <?php } } ?>
</table>
</code>```

Ajax:

```<code>var getVar = [];
$(".select_update:checked").each(function() {
        getVar.push($(this).val());
});

$.ajax({
    url : url,
    type: 'POST',
    data: 'id_pesan='+getVar,
    dataType: 'json',
    success: function(response)
    {
        if(response){
            location.reload();
        }
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Error');
    }
 });
</code>```

答:
How does your Ajax looks like?
I think you have to change

$update = $this->input->post('select_id');

into

$update = $this->input->post('select_update'); or $this->input->post('select_update[]');

because of the name attribute of your checkboxes and change

$this->db->where('id', $delete[$i]);

into

$this->db->where('id', $update[$i]);

or use it in a foreach

```<code>function update_multiple() {
    $updates = $this->input->post('select_update');

    foreach ($updates as $update) {
        $data = array('notif' => 0);
        $this->db->where('id', $update);
        $this->db->update('my_table', $data);
    }
}
</code>```

Update #1

Your Ajax should look like this - keep scope on data of ajax

```<code>$.ajax({
  url : url,
  type: 'POST',
  data: $(".select_update:checked").serialize(),
  dataType: 'json',
  success: function(response) { ... },
  error: function (jqXHR, textStatus, errorThrown) { ... }
});
</code>```

Body:
I am trying to update multiple data through AJAX but I have tried several times, but the data has not changed, please help to fix it in order to run perfectly.

Controllers:

function update_notif() {
    $this->My_model->update_multiple();
    $this->session->set_flashdata('msg',
                '

Success

');
}

Models:

function update_multiple() {
    $update = $this->input->post('id_pesan');
    for ($i=0; $i < count($update) ; $i++) {
        $data = array('notif' => 0);
        $this->db->where('id', $delete[$i]);
        $this->db->update('my_table', $data);
    }
}

Views:

<button type="button" id="btn_delete" ></button>

            <input id="selecctall" type="checkbox">
            No
            Name
            Telp

        <?php foreach ($show_data as $row) { ?>

            <input type="checkbox" class="select_update" name="select_update[]" value="<?php echo $row->id; ?>">
            <?php echo $row->no; ?>
            <?php echo $row->nama; ?>
            <?php echo $row->telp; ?>

    <?php } } ?>

Ajax:

var getVar = [];
$(".select_update:checked").each(function() {
        getVar.push($(this).val());
});

$.ajax({
    url : url,
    type: 'POST',
    data: 'id_pesan='+getVar,
    dataType: 'json',
    success: function(response)
    {
        if(response){
            location.reload();
        }
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        alert('Error');
    }
 });

Body:
How does your Ajax looks like?
I think you have to change

$update = $this->input->post('select_id');

into

$update = $this->input->post('select_update'); or $this->input->post('select_update[]');

because of the name attribute of your checkboxes and change

$this->db->where('id', $delete[$i]);

into

$this->db->where('id', $update[$i]);

or use it in a foreach

function update_multiple() {
    $updates = $this->input->post('select_update');

    foreach ($updates as $update) {
        $data = array('notif' => 0);
        $this->db->where('id', $update);
        $this->db->update('my_table', $data);
    }
}

Update #1

Your Ajax should look like this - keep scope on data of ajax

$.ajax({
  url : url,
  type: 'POST',
  data: $(".select_update:checked").serialize(),
  dataType: 'json',
  success: function(response) { ... },
  error: function (jqXHR, textStatus, errorThrown) { ... }
});


问:
Why is it impossible to mix Python2 with Python3?
Despite all that has been said and written on Python2 vs Python3, I have been unable to identify why the developers made it impossible to mix Python2 and Python3 code. Surely there must be a reason for this?

In Fortran, for instance, the many versions are incompatible with each other, but they can still happily co-exist within the same project. The same applies to C and C++: some C code is not compatible with C++, but the compiler is able to recognize the correct language using the file extension. Is there a specific reason for why this approach was not chosen for Python3? That is, let Python3 modules be identified by a .py3 extension (or a shebang comment), and use one single interpreter for both .py and .py3 code?

EDIT:

There is already a question named Why is Python 3 not backwards compatible? , but this question is different. I know that Python 3 introduces new features and breaks backwards compatibility because of this. It still does not mean that Python 2 and 3 cannot coexist the same way C and C++ can.

答:
Is there a specific reason for why this approach was not chosen for Python3? That is, let Python3 modules be identified by a .py3 extension (or a shebang comment), and use one single interpreter for both .py and .py3 code?

Because it's completely unnecessary! With the help of modules like six, it's quite easy to write code which is compatible with both Python2 and Python3 with no source-code changes. This isn't just a parlour trick; major projects like Django have been written this way.


问:
a large scale java project solution
I would like to start up a project from scratch. I am a java developer for years. I did even write my own mvc framework some time ago for fun. Now I am working in a company using in-house framework - which i think is a total loss of time and money. I respect the idea of  teaming up with different skilled people for a large scale project. The separation of the project is very important; Graphics guys, front end developers, software architectures, software developers, database experts, etc. I cannot risk to use a scripting language like php.

Lately, I am researching java technologies for a large scale project in every aspects. What I mean by that, for the front layer I come across with very famous technologies.

Spring

MyFaces

Tapestry

Google Web Toolkit

Cocoon

Velocity

Every one of them states that it is the simplest, the fastest, the latest technology and whatsoever. Of course only one them can hold the truth. I need a front end technology for fast implementation for ajax, customer/administrator security, themes, templates, internationalization, caching static pages, clustering and a support of ejb. It should also have IDE support, community support, rich documentation and online tutorials. Still I have no experience of those frameworks which to choose from. Maybe there is even better one? And most importantly, I cannot risk to start up on a technology which has development limitations. Is there any suggestions for this layer?

For the business layer, I am sure of EJB and JPA. I do even considering a web service for facade of this layer for interoperability purposes for future extensions. However, I have no idea about securing that layer (it could be applied on its web service level) which is still a problem for me. For the application server I am considering GlassFish.

And for the last question is what IDE should be picked for development. Regarding all the technologies, which are going to be used, an IDE should help me in every step, either doing the configuration for me or helping me configuring with its ready wizards. I suppose the IDE will have proper plugins for to be used technologies.

I know that I want too much, however I have a hope for a combination of technologies which will help me saving time and money in my future plans.

I ll be really glad to hear your responses, experiences for a bigger picture.

edited: There is no ultimate answer, I know that. I am just taking advice. Any answer is appreciated.

答:
Well, first of all, your question is not good. Every technology has it's bright sides and dark sides. To choose some specific technology - you need experience in all of them to estimate which problems can emerge with your project. Given your definition: fast implementation for ajax, customer/administrator security, themes, templates, internationalization, caching static pages, clustering and a support of ejb - 90% of frameworks support all of it either directly or using some plugins.

Moreover, various technologies are better optimized for various needs. You can't have a all-in-one-super-framework that is flawless and does everything the best way possible. Given that the framework is highly scalable and fast (example: Spring and/or Portlets) will make it hard to configure for some small tasks.

So the only thing I can recommend is to google "Java Web Framework Comparison" and hope for the best.

As about IDE, I can see only 2 choices: IntelliJ Idea and Eclipse. Again, there is no clear winner so yet again google is the only source of information you can get.

Added:
Talking about frameworks again, complex projects use several of them at once taking the best parts of each to aid with the specific project needs. But to do that effectively - you need to be a guru in all of the mixed technologies.

ContentLicense: CC BY-SA 2.5

Title: a large scale java project solution


问:
How to change the values on the view onclick of button without reloading of the page using mvc
i m trying to create a view in which the header of page contain some button and according to the button click the content on the page should be change.
should i use partial view?</p>

答:
You can use ajax and webapi.
e.g.

default text
<input type=button value="change text by webapi" />
```

Body:
You can use ajax and webapi.
e.g.

<span id="test_span">default text</span>
<input type=button value="change text by webapi" />
<script>
    $(document).ready(function(){
        $("#test_span").click(function(){
            $.ajax({
                type:'GET',
                url:'webapi url',
                success: function(data){
                    $("#test_span").text(data);
                }
            });
        });
    });
</script>


问:
Task is to export excel data to MySQL and display graphs.!
Excel workbook needs to be exported to MySQL and display graphs. Few columns are dependent (with the formula on other columns) on other so every time user performs any CRUD operation simultaneously other dependent columns needs to be updated and the graphs as well.

I am using Python, Django, MySQL, and angularJS.

Is this possible? Any ideas?..

答:
Not sure if the following steps can help you:

1 - open your excel file, and export as .csv

2 - import this .csv file into your MySQL table via SIDU or similar tools

3 - Use SIDU to produce graphs based on your need: eg

Topnew SIDU uses Topnew SVG Chart plug-in to produce bar chart, line chart, pie chart according to your SQLs

For more info, visit topnew.net/sidu


问:
SELECT INTO query to create MEMORY_OPTIMIZED table
is it possible to generate a MEMORY_OPTIMIZED table with an SELECT INTO statement?
Something like:

```<code>SELECT *
INTO MemoryOptimizedTargetTable
FROM SourceTable;
</code>```

Or at least convert the target after the SELECT INTO with an ALTER statement?

Thanks

答:
No.

With SQL Server 2017 it will be possible to specify a filegroup, but that's as far as it goes into customizing the created table.

Since SELECT ... INTO ... is equivalent to CREATE TABLE, to be fully customizable it would require all options CREATE TABLE has. This is not really feasible. Once you realizE that in effect you are creating a table and inserting rows into it, why not do just that?

```<code>CREATE TABLE ...
INSERT ... SELECT ...
</code>```

Body:
is it possible to generate a MEMORY_OPTIMIZED table with an SELECT INTO statement?
Something like:

SELECT *
INTO MemoryOptimizedTargetTable
FROM SourceTable;

Or at least convert the target after the SELECT INTO with an ALTER statement?

Thanks

Body:
No.

With SQL Server 2017 it will be possible to specify a filegroup, but that's as far as it goes into customizing the created table.

Since SELECT ... INTO ... is equivalent to CREATE TABLE, to be fully customizable it would require all options CREATE TABLE has. This is not really feasible. Once you realizE that in effect you are creating a table and inserting rows into it, why not do just that?

CREATE TABLE ...
INSERT ... SELECT ...


问:
Golang Invalid Receiver Type in Method Func
I'm trying to make a simple package to send SSH commands to a server.

I have the following code:

```<code>type Connection *ssh.Client

func Connect(addr, user, password string) (conn Connection, err error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err = ssh.Dial("tcp", addr, sshConfig)
    return
}

func (conn Connection) SendCommand() ([]byte, error) {
    session, err := (*ssh.Client)(conn).NewSession()
    // ...
}
</code>```

My problem is on the two lines func (conn Connection) SendCommand() ([]byte, error) and session, err := (*ssh.Client)(conn).NewSession().

I can't figure out how to use the methods available for *ssh.Client from my overlaying Connection type.

I understand that I need to do some conversion, and using ssh.Client(*conn).NewSession() would work, but it copies the values of the *ssh.Client which doesn't seem to be the right method.

What should do to access the methods available for a *ssh.Client when working with my custom type Connection *ssh.Client type?

答:
This is the best I can come up with:

```<code>type Connection ssh.Client

func (conn *Connection) SendCommand() ([]byte, error) {
    (*ssh.Client)(conn).NewSession()
</code>```

Note that I've changed the type to not be a pointer type (but then I've made a pointer receiver for SendCommand). I'm not sure there's any way to create a function with a pointer type as a receiver.

Body:
I'm trying to make a simple package to send SSH commands to a server.

I have the following code:

type Connection *ssh.Client

func Connect(addr, user, password string) (conn Connection, err error) {
    sshConfig := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
        HostKeyCallback: ssh.HostKeyCallback(func(hostname string, remote net.Addr, key ssh.PublicKey) error { return nil }),
    }

    conn, err = ssh.Dial("tcp", addr, sshConfig)
    return
}

func (conn Connection) SendCommand() ([]byte, error) {
    session, err := (*ssh.Client)(conn).NewSession()
    // ...
}

My problem is on the two lines func (conn Connection) SendCommand() ([]byte, error) and session, err := (*ssh.Client)(conn).NewSession().

I can't figure out how to use the methods available for *ssh.Client from my overlaying Connection type.

I understand that I need to do some conversion, and using ssh.Client(*conn).NewSession() would work, but it copies the values of the *ssh.Client which doesn't seem to be the right method.

What should do to access the methods available for a *ssh.Client when working with my custom type Connection *ssh.Client type?

Body:
This is the best I can come up with:

type Connection ssh.Client

func (conn *Connection) SendCommand() ([]byte, error) {
    (*ssh.Client)(conn).NewSession()

Note that I've changed the type to not be a pointer type (but then I've made a pointer receiver for SendCommand). I'm not sure there's any way to create a function with a pointer type as a receiver.


问:
Combining Either and Pair monads with transformers
I haven't used monad transformers before but I think it's what I need in my case. Here's some sample code below:

```<code>Prelude> (+) <$> Right 2 <*> Right 3
Right 5

Prelude> (+) <$> (['a'],2) <*> (['b'],3)
("ab",5)
</code>```

But I want to combine these two behaviours like so:

```<code>Prelude> (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)
</code>```

Naturally this fails to compile as numeric addition is not defined on (String, Int).

The Monad transformers Haskell wiki page suggests I need to use a transformer for the inner monad, which is in this case a pair, but searching for PairT on Hayoo! or Hoogle didn't reveal anything relevant.

Do I have to implement this transformer myself, or is there something on Hackage I've missed, or am I just misunderstanding how this should be done?

Note:

The actual outer monad I'm using isn't Either, it's a custom monad I've detailed in this question, which however is quite similar to Either.

答:
An alternative:</p>

```<code>> liftA2 (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)
</code>```

Body:
I haven't used monad transformers before but I think it's what I need in my case. Here's some sample code below:

Prelude> (+) <$> Right 2 <*> Right 3
Right 5

Prelude> (+) <$> (['a'],2) <*> (['b'],3)
("ab",5)

But I want to combine these two behaviours like so:

Prelude> (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)

Naturally this fails to compile as numeric addition is not defined on (String, Int).

The Monad transformers Haskell wiki page suggests I need to use a transformer for the inner monad, which is in this case a pair, but searching for PairT on Hayoo! or Hoogle didn't reveal anything relevant.

Do I have to implement this transformer myself, or is there something on Hackage I've missed, or am I just misunderstanding how this should be done?

Note:

The actual outer monad I'm using isn't Either, it's a custom monad I've detailed in this question, which however is quite similar to Either.

Body:
An alternative:

> liftA2 (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)


答:
It seems you have pasted your code from your delete_multiple method and this is why you use $delete instead of $update here

```<code>function update_multiple() {
    $update = $this->input->post('select_id');
    for ($i=0; $i < count($update) ; $i++) {
        $data = array('notif' => 0);
        $this->db->where('id', $delete[$i]);
        $this->db->update('my_table', $data);
    }
}
</code>```

Solution:

```<code>function update_multiple() {
    $update = $this->input->post('select_id');
    for ($i=0; $i < count($update) ; $i++) {
        $data = array('notif' => 0);
        $this->db->where('id', $update[$i]);
        $this->db->update('my_table', $data);
    }
}
</code>```

Inspired from UfguFugullu, who was apparently inspired by my answer as well:

select_update is needed instead of select_id

Title: update multiple data codeigniter with checkbox

Body:
It seems you have pasted your code from your delete_multiple method and this is why you use $delete instead of $update here

function update_multiple() {
    $update = $this->input->post('select_id');
    for ($i=0; $i < count($update) ; $i++) {
        $data = array('notif' => 0);
        $this->db->where('id', $delete[$i]);
        $this->db->update('my_table', $data);
    }
}

Solution:

function update_multiple() {
    $update = $this->input->post('select_id');
    for ($i=0; $i < count($update) ; $i++) {
        $data = array('notif' => 0);
        $this->db->where('id', $update[$i]);
        $this->db->update('my_table', $data);
    }
}

Inspired from UfguFugullu, who was apparently inspired by my answer as well:

select_update is needed instead of select_id


问:
Logging when an Azure (Basic) Web App Exceeds Quotas
Running a basic, free Windows Azure Web application for testing purposes I often exceed the CPU Time (short) quota of 3 minutes.

For example, when trialling the image optimisation Nuget package AzureImageOptimizer which is implemented as a Web Job, the initial optimisation run exceeded the limit and stopped the server.

I notice these events are not being recorded in the Web App's Activity Log. Why?

Questions:

Are these events logged?

Is it because this is a Free Web App?

Can the Web App be configured so that they are logged?

Is there an alternative way to catch these
events?

Bonus question:

Can I receive a notification before a quota is exceeded?

答:
Are these events logged?

No. If an application in its usage exceeds the CPU (short), CPU (Day), or bandwidth quota then the application will be stopped until the quota re-sets. No log will be written to any place.

Is it because this is a Free Web App?

Both Free and Shared Plan have the resources limits.

Can the Web App be configured so that they are logged?

I also haven't found any way to do it.

Is there an alternative way to catch these events?

Since you are using WebJob, you could add a CancellationToken parameter in your function. If the Web App is stopped. The IsCancellationRequested property will be set to true before the function stopped.

```<code>public static void ProcessQueueMessage([QueueTrigger("myqueue")] string message, CancellationToken cancellationToken)
{
    Task.Run(new Action(longTimeJob), cancellationToken);
    while (true)
    {
        Thread.Sleep(1000);
        if (cancellationToken.IsCancellationRequested)
        {
            Console.WriteLine("The function has been Cancelled since the Web App is stopped!");
        }
    }
}
</code>```

Here is the information I captured from Azure WebJobs Dashboard when the Web App is stopped.

```<code>[06/07/2017 07:52:53 > 9d3635: INFO] The function has been Cancelled since the Web App is stopped!
[06/07/2017 07:52:53 > 9d3635: ERR ] Thread was being aborted.
[06/07/2017 07:52:53 > 9d3635: SYS INFO] WebJob process was aborted
[06/07/2017 07:52:54 > 9d3635: SYS INFO] Status changed to Stopped
</code>```

Body:
Are these events logged?

No. If an application in its usage exceeds the CPU (short), CPU (Day), or bandwidth quota then the application will be stopped until the quota re-sets. No log will be written to any place.

Is it because this is a Free Web App?

Both Free and Shared Plan have the resources limits.

Can the Web App be configured so that they are logged?

I also haven't found any way to do it.

Is there an alternative way to catch these events?

Since you are using WebJob, you could add a CancellationToken parameter in your function. If the Web App is stopped. The IsCancellationRequested property will be set to true before the function stopped.

public static void ProcessQueueMessage([QueueTrigger("myqueue")] string message, CancellationToken cancellationToken)
{
    Task.Run(new Action(longTimeJob), cancellationToken);
    while (true)
    {
        Thread.Sleep(1000);
        if (cancellationToken.IsCancellationRequested)
        {
            Console.WriteLine("The function has been Cancelled since the Web App is stopped!");
        }
    }
}

Here is the information I captured from Azure WebJobs Dashboard when the Web App is stopped.

[06/07/2017 07:52:53 > 9d3635: INFO] The function has been Cancelled since the Web App is stopped!
[06/07/2017 07:52:53 > 9d3635: ERR ] Thread was being aborted.
[06/07/2017 07:52:53 > 9d3635: SYS INFO] WebJob process was aborted
[06/07/2017 07:52:54 > 9d3635: SYS INFO] Status changed to Stopped


问:
Perl Regex match incorrect
I'm a little confused as to why the output to this search is only the capital letter T. Shouldn't the + operator match the entire word "GREAT"? Any help is appreciated.</p>

```<code>my $content = "The 39 Steps - a GREAT book - colours_15";

    if($content =~ /([A-Z]+)/) {
        print "Matched $1\n";
    }
    else {
        print "No match\n";
    }
</code>```

答:
The Perl regex engine is lazy. It will return the leftmost match in your string. As soon as it finds a match, it will stop looking for "better" matches.

The regex engine's internal dialogue for this code might go something like this:

Ok, so we're looking for one or more capital letters. Right, so let's start looking at this string. What's the first character? Oh, a capital 'T'. That matches. But we're looking for one or more characters, so keep looking. What's next? A lower-case 'h'. Ok, that doesn't match. Looks like we're done then. The first sequence of one or more capital letters I found was just the letter 'T'. Stick that in $1 and it looks like we can knock off early. Who's putting the kettle on?

Title: Perl Regex match incorrect

Body:
I'm a little confused as to why the output to this search is only the capital letter T. Shouldn't the + operator match the entire word "GREAT"? Any help is appreciated.

my $content = "The 39 Steps - a GREAT book - colours_15";

    if($content =~ /([A-Z]+)/) {
        print "Matched $1\n";
    }
    else {
        print "No match\n";
    }


问:
HTTP Status 500-/index.jsp "/struts-tags" not found
Hi Can anyone help me out to resolve the error mentioned above.
I used a index.jsp file

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Hello World</title>
    </head>
    <body>
        <h1>Hello World From Struts2</h1>
       <form action="hello">
          <label for="name">Please enter your name</label><br/>
          <input type="text" name="name"/>
          <input type="submit" value="Say Hello"/>
       </form>
    </body>
    </html>
</code>```

After writing all the classes and xml files,I have run the classes by tomcat server but got an error as follows

Can anyone help me out as I am new to Struts

答:
The taglib is included in struts-core.jar, and the container will discover it automatically.

for some reason, a taglib configuration is needed within web.xml, extract the TLD file from the struts-core.jar META-INF folder, and add a taglib element to the web.xml.

```<code> <!-- ... -->
    </welcome-file-list>

    <taglib>
       <taglib-uri>/s</taglib-uri>
       <taglib-location>/WEB-INF/struts-tags.tld</taglib-location>
    </taglib>
</web-app>
</code>```

Body:
Hi Can anyone help me out to resolve the error mentioned above.
I used a index.jsp file

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Hello World</title>

Hello World From Struts2

       <form action="hello">
          Please enter your name

          <input type="text" name="name"/>
          <input type="submit" value="Say Hello"/>
       </form>

After writing all the classes and xml files,I have run the classes by tomcat server but got an error as follows

Can anyone help me out as I am new to Struts

Body:
The taglib is included in struts-core.jar, and the container will discover it automatically.

for some reason, a taglib configuration is needed within web.xml, extract the TLD file from the struts-core.jar META-INF folder, and add a taglib element to the web.xml.

 <!-- ... -->
    </welcome-file-list>

    <taglib>
       <taglib-uri>/s</taglib-uri>
       <taglib-location>/WEB-INF/struts-tags.tld</taglib-location>
    </taglib>
</web-app>


问:
Live traffic conditions on google map in iOS app?
How can I add current traffic conditions in ios app using google maps sdk or api as shown in below image.
There is javascript api but I didn't find any solution for iOS app.

答:
Just add a line of code to enable or disable live traffic in iOS SDK

```<code>_googleMapsView.trafficEnabled = YES;
_googleMapsView.trafficEnabled = NO;
</code>```

Where _googleMapsView is object for GMSMapView.

Body:
Just add a line of code to enable or disable live traffic in iOS SDK

_googleMapsView.trafficEnabled = YES;
_googleMapsView.trafficEnabled = NO;

Where _googleMapsView is object for GMSMapView.


问:
In kotlin, how to make the setter of properties in primary constructor private?
In kotlin, how to make the setter of properties in primary constructor private?

```<code>class City(val id: String, var name: String, var description: String = "") {

    fun update(name: String, description: String? = "") {
        this.name = name
        this.description = description ?: this.description
    }
}
</code>```

I  want the setter of properties name to be private, and the getter of it public, how can I do?

答:
The solution is to create a property outside of constructor and set setter's visibility.

```<code>class Sample(var id: Int, name: String) {

    var name: String = name
        private set

}
</code>```

Update:

They're discussing it here: https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640

Body:
In kotlin, how to make the setter of properties in primary constructor private?

class City(val id: String, var name: String, var description: String = "") {

    fun update(name: String, description: String? = "") {
        this.name = name
        this.description = description ?: this.description
    }
}

I  want the setter of properties name to be private, and the getter of it public, how can I do?

Body:
The solution is to create a property outside of constructor and set setter's visibility.

class Sample(var id: Int, name: String) {

    var name: String = name
        private set

}

Update:

They're discussing it here: https://discuss.kotlinlang.org/t/private-setter-for-var-in-primary-constructor/3640

ContentLicense: CC BY-SA 4.0


问:
iOS – Run/Debug/Install builds over Wi-Fi
We have iPad and iPhone devices, but short of wires. Is there any way that we can install/debug the builds over Wi-Fi in iOS?

I know the way in Android, but not of iOS.

答:
Requirements: iOS 11 and XCode 9, iOS device and computer on same wifi network.
Connect your device with USB Cable, launch Xcode, then on Xcode menu, choose: Window->Devices and Simulators. Choose device and check "Connect via network". Now you can disconnect USB and develop on device using wifi.
ScreenShot</p>


问:
How to fix this error which comes building the VirtualplannetBuilder source on visual studio 2013?
I already installed GDAL 1.11.4 32Bit and OpenSceneGraph-3.4.0 on my windows 10 machine.   </p>

```<code>1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLAllocConnect@8 referenced in function "public: int __thiscall CPLODBCSession::EstablishSession(char const *,char const *,char const *)" (?EstablishSession@CPLODBCSession@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLAllocEnv@4 referenced in function "public: int __thiscall CPLODBCSession::EstablishSession(char const *,char const *,char const *)" (?EstablishSession@CPLODBCSession@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLAllocStmt@8 referenced in function "public: __thiscall CPLODBCStatement::CPLODBCStatement(class CPLODBCSession *)" (??0CPLODBCStatement@@QAE@PAVCPLODBCSession@@@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLColAttribute@28 referenced in function "public: int __thiscall CPLODBCStatement::CollectResultsInfo(void)" (?CollectResultsInfo@CPLODBCStatement@@QAEHXZ)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLColumns@36 referenced in function "public: int __thiscall CPLODBCStatement::GetColumns(char const *,char const *,char const *)" (?GetColumns@CPLODBCStatement@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLConnect@28 referenced in function "public: int __thiscall CPLODBCSession::EstablishSession(char const *,char const *,char const *)" (?EstablishSession@CPLODBCSession@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLDescribeCol@36 referenced in function "public: int __thiscall CPLODBCStatement::CollectResultsInfo(void)" (?CollectResultsInfo@CPLODBCStatement@@QAEHXZ)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLDisconnect@4 referenced in function "public: int __thiscall CPLODBCSession::CloseSession(void)" (?CloseSession@CPLODBCSession@@QAEHXZ)
</code>```

答:
You need to link with the appropriate library. I seem to remember that you, in this case, need either ODBC32.lib or ODBCCP32.lib, or both libraries.

Here is answer on how to add additional libraries.

Body:
I already installed GDAL 1.11.4 32Bit and OpenSceneGraph-3.4.0 on my windows 10 machine.

1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLAllocConnect@8 referenced in function "public: int __thiscall CPLODBCSession::EstablishSession(char const *,char const *,char const *)" (?EstablishSession@CPLODBCSession@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLAllocEnv@4 referenced in function "public: int __thiscall CPLODBCSession::EstablishSession(char const *,char const *,char const *)" (?EstablishSession@CPLODBCSession@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLAllocStmt@8 referenced in function "public: __thiscall CPLODBCStatement::CPLODBCStatement(class CPLODBCSession *)" (??0CPLODBCStatement@@QAE@PAVCPLODBCSession@@@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLColAttribute@28 referenced in function "public: int __thiscall CPLODBCStatement::CollectResultsInfo(void)" (?CollectResultsInfo@CPLODBCStatement@@QAEHXZ)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLColumns@36 referenced in function "public: int __thiscall CPLODBCStatement::GetColumns(char const *,char const *,char const *)" (?GetColumns@CPLODBCStatement@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLConnect@28 referenced in function "public: int __thiscall CPLODBCSession::EstablishSession(char const *,char const *,char const *)" (?EstablishSession@CPLODBCSession@@QAEHPBD00@Z)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLDescribeCol@36 referenced in function "public: int __thiscall CPLODBCStatement::CollectResultsInfo(void)" (?CollectResultsInfo@CPLODBCStatement@@QAEHXZ)
    1>gdal.lib(cpl_odbc.obj) : error LNK2019: unresolved external symbol _SQLDisconnect@4 referenced in function "public: int __thiscall CPLODBCSession::CloseSession(void)" (?CloseSession@CPLODBCSession@@QAEHXZ)


问:
What is the proper way to refer to resource directory path in one source set in gradle?
In my build.gradle file, I have defined a separate sourceSet for integration tests:

```<code>sourceSets {
    integtest {
        java.srcDir 'src/integtest/java/io/attil/integration'
        resources.srcDir 'src/integtest/resources'
    }
}
</code>```

I would like to use the path to resources of the integration tests in one of my manually defined tasks (a task that prefills the data-base for integration tests; the sql script is located in the mentioned resource folder).

I have now the following solution:

```<code>task prefillDatabase {
    // ... snip!

        String sqlString = new File(sourceSets.integtest.resources.srcDirs.iterator().next().toString() + '/setup_integration_tests.sql').text

    // ... snip!
}
</code>```

While this works, it is quite cumbersome.

Is there a better, shorter way to achieve the same? (I'm looking for something like sourceSets.integtest.resources.srcDir.)

答:
I'm not sure this is less verbose, but I'd argue it's more correct

```<code>File file = sourceSets.integtest.resources.matching {
    include 'setup_integration_tests.sql'
}.singleFile

String sqlString = file.text
</code>```

See FileTree.matching(Closure) and FileCollection.getSingleFile()

Also, this looks wrong to me

```<code>java.srcDir 'src/integtest/java/io/attil/integration'
</code>```

I'd think it would be

```<code>java.srcDir 'src/integtest/java'
java.include 'io/attil/integration/**'
</code>```

Body:
In my build.gradle file, I have defined a separate sourceSet for integration tests:

sourceSets {
    integtest {
        java.srcDir 'src/integtest/java/io/attil/integration'
        resources.srcDir 'src/integtest/resources'
    }
}

I would like to use the path to resources of the integration tests in one of my manually defined tasks (a task that prefills the data-base for integration tests; the sql script is located in the mentioned resource folder).

I have now the following solution:

task prefillDatabase {
    // ... snip!

        String sqlString = new File(sourceSets.integtest.resources.srcDirs.iterator().next().toString() + '/setup_integration_tests.sql').text

    // ... snip!
}

While this works, it is quite cumbersome.

Is there a better, shorter way to achieve the same? (I'm looking for something like sourceSets.integtest.resources.srcDir.)

Body:
I'm not sure this is less verbose, but I'd argue it's more correct

File file = sourceSets.integtest.resources.matching {
    include 'setup_integration_tests.sql'
}.singleFile

String sqlString = file.text

See FileTree.matching(Closure) and FileCollection.getSingleFile()

Also, this looks wrong to me

java.srcDir 'src/integtest/java/io/attil/integration'

I'd think it would be

java.srcDir 'src/integtest/java'
java.include 'io/attil/integration/**'


问:
Unable to call function assigned to a variable in python
I have the following code in which the function is not being called and an error is being returned. Following is the code -

```<code>def deleteExistingBackupFiles(step):
    try:
        for setting in step.Setting:
            key = setting['key']
            value = setting['value']
            configTable.update({key: value})
            if os.path.isfile(value):
                os.remove(value)
            elif os.path.isdir(value):
                shutil.rmtree(value)
    except:
        report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

def main():
    scriptPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    configFilePath = os.path.abspath(os.path.realpath(scriptPath + '\config.xml'))
    parsedXML = ET.parse(configFilePath)

    #try:
    for step in parsedXML.iter('Step'):
        for setting in step.iter('Setting'):
            print setting.attrib.get('key')
            print setting.attrib.get('value')
            configTable.update({setting.attrib.get('key'): setting.attrib.get('value')})

    for step in tqdm(parsedXML.iter('Step'), desc='Wordpress Backup Restoration : '):
        methodName = step.attrib.get('methodname')
        result = methodName
        result(step)
</code>```

While trying to execute the last statement, I am getting the following error -

```<code>Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1585, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 119, in <module>
    main()
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 106, in main
    result(step)
TypeError: 'str' object is not callable
</code>```

The methodName contains DeleteExistingBackupFiles yet it is still not working. Any idea what is going wrong?

Although when I try to execute the following code, it works fine -

```<code>def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

result = (sampleFunc)

result("Hello World!")
</code>```

Have a nice day!

答:
Embed the function in to a class object,

```<code>class Foo(object):

    def function_name(self, args):
        pass
</code>```

Now, you can access the function from a string like this,

```<code>foo = Foo()
func_name = "function_name"
func = getattr(foo, func_name, None):
if func:
    func(arg)
</code>```

In your code, if you wrap the function in a class, (say Foo),

```<code>class Foo(object):

    def deleteExistingBackupFiles(self, step):
        try:
            for setting in step.Setting:
                key = setting['key']
                value = setting['value']
                configTable.update({key: value})
                if os.path.isfile(value):
                    os.remove(value)
                elif os.path.isdir(value):
                    shutil.rmtree(value)
        except:
            report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})
</code>```

Then you could access the function,

```<code>foo = Foo()
result = getattr(foo, methodName, None)
if result:
    result(step)
</code>```

Body:
I have the following code in which the function is not being called and an error is being returned. Following is the code -

def deleteExistingBackupFiles(step):
    try:
        for setting in step.Setting:
            key = setting['key']
            value = setting['value']
            configTable.update({key: value})
            if os.path.isfile(value):
                os.remove(value)
            elif os.path.isdir(value):
                shutil.rmtree(value)
    except:
        report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

def main():
    scriptPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    configFilePath = os.path.abspath(os.path.realpath(scriptPath + '\config.xml'))
    parsedXML = ET.parse(configFilePath)

    #try:
    for step in parsedXML.iter('Step'):
        for setting in step.iter('Setting'):
            print setting.attrib.get('key')
            print setting.attrib.get('value')
            configTable.update({setting.attrib.get('key'): setting.attrib.get('value')})

    for step in tqdm(parsedXML.iter('Step'), desc='Wordpress Backup Restoration : '):
        methodName = step.attrib.get('methodname')
        result = methodName
        result(step)

While trying to execute the last statement, I am getting the following error -

Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1585, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files\JetBrains\PyCharm 2017.1.2\helpers\pydev\pydevd.py", line 1015, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 119, in <module>
    main()
  File "C:/Users/Pranav/PycharmProjects/DevEnv/Blog.py", line 106, in main
    result(step)
TypeError: 'str' object is not callable

The methodName contains DeleteExistingBackupFiles yet it is still not working. Any idea what is going wrong?

Although when I try to execute the following code, it works fine -

def sampleFunc(arg):
    print('you called sampleFunc({})'.format(arg))

result = (sampleFunc)

result("Hello World!")

Have a nice day!

Body:
Embed the function in to a class object,

class Foo(object):

    def function_name(self, args):
        pass

Now, you can access the function from a string like this,

foo = Foo()
func_name = "function_name"
func = getattr(foo, func_name, None):
if func:
    func(arg)

In your code, if you wrap the function in a class, (say Foo),

class Foo(object):

    def deleteExistingBackupFiles(self, step):
        try:
            for setting in step.Setting:
                key = setting['key']
                value = setting['value']
                configTable.update({key: value})
                if os.path.isfile(value):
                    os.remove(value)
                elif os.path.isdir(value):
                    shutil.rmtree(value)
        except:
            report.update({"DeleteExistingBackup":"There was a problem while trying to delete old files."})

Then you could access the function,

foo = Foo()
result = getattr(foo, methodName, None)
if result:
    result(step)


问:
Mark event as explicitly NOT passive

[Violation] Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive.

This warning is kinda getting on my nerves to be honest. I have an event where I sometimes need to call preventDefault()

Is there  a way to mark the event as explicitly NOT passive and to get rid of this warning? I know it doesn't hamper execution flow, but it's an annoyance. All I can find is how to mark it passive, but it's a desktop app, which doesn't need the passive marker for scroll optimization.

I'm not sure what chrome thought when they implemented this as default warning to clutter up the dev console. I feel like it's something like the agree button now on EULAS, don't read, just click ok, cookie warning, just click ok...
I don't wish to fix it, I wish to ignore it, consiously.

答:
Specify passive: false when you add the listener:

el.addEventListener('click', someFn, { passive: false });

See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Title: Mark event as explicitly NOT passive


问:
HTML table with JSON
I have a different format of JSON below, I need to put it with HTML table and display it. I need to do this in AngularJS. I tried with normal JSON format it was working fine but for this JSON it's not working. This example is for indexing search, so I need to maintain JSON like that.

For example:

                Name
                Position
                Office

       {{x.Name}}
       {{x.City}}
       {{x.Country}}

```

<p>Now I need to do the same thing with the below JSON format:</p>

<pre class="lang-js prettyprint-override"><code>{
    "data": [
            [
                "1",
                "supply chain Management",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "1"

            ],

            [
                "2",
                "Data Tower",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "2"
            ],
            [
                "3",
                "Enter business",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "3"
            ],
            [
                "4",
                "IOT",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "4"
            ],
            [
                "5",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "5"
            ],
            [
                "6",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "6"
            ]

        ]
    }
</code>```

答:
```<code><div ng-app="myApp" ng-controller="myCtrl">
  <div class="container">
    <h2>To Access Single Array</h2>
    <div class="panel panel-default" ng-repeat="data in datas">
      <div class="panel-heading">{{data[$index]}} </div>
    </div>
  </div>
  <div class="container">
    <h2>To Access all data Array</h2>
    <div class="panel panel-default" ng-repeat="data in datas">
      <div class="panel-heading">{{data}} </div>
    </div>
  </div>
</div>
</code>```

AngularFile

```<code>var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  var data = '{"data": [["1","supply chain Management", "https://www.google.co.in/","abc", 1234567,"abc@gmail.com","assdadsddsf",  "1"  ], [ "2", "Data Tower", "https://www.google.co.in/", "abc", 1234567, "abc@gmail.com", "assdadsddsf", "2" ], ["3","Enter business", "https://www.google.co.in/", "abc", 1234567, "abc@gmail.com","assdadsddsf", "3" ]]}'

  $scope.datas = JSON.parse(data);
});
</code>```

Play code here https://jsfiddle.net/ikismail7/2uufzqqh/

Title: HTML table with JSON

Body:
I have a different format of JSON below, I need to put it with HTML table and display it. I need to do this in AngularJS. I tried with normal JSON format it was working fine but for this JSON it's not working. This example is for indexing search, so I need to maintain JSON like that.

For example:

                Name
                Position
                Office

       {{x.Name}}
       {{x.City}}
       {{x.Country}}

Now I need to do the same thing with the below JSON format:

{
    "data": [
            [
                "1",
                "supply chain Management",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "1"

            ],

            [
                "2",
                "Data Tower",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "2"
            ],
            [
                "3",
                "Enter business",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "3"
            ],
            [
                "4",
                "IOT",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "4"
            ],
            [
                "5",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "5"
            ],
            [
                "6",
                "Supplys Chain",
                "https://www.google.co.in/",
                "abc",
                1234567,
                "abc@gmail.com",
                "assdadsddsf",
                "6"
            ]

        ]
    }

Body:
<div ng-app="myApp" ng-controller="myCtrl">
  <div class="container">
    <h2>To Access Single Array</h2>
    <div class="panel panel-default" ng-repeat="data in datas">
      <div class="panel-heading">{{data[$index]}} </div>
    </div>
  </div>
  <div class="container">
    <h2>To Access all data Array</h2>
    <div class="panel panel-default" ng-repeat="data in datas">
      <div class="panel-heading">{{data}} </div>
    </div>
  </div>
</div>

AngularFile

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

  var data = '{"data": [["1","supply chain Management", "https://www.google.co.in/","abc", 1234567,"abc@gmail.com","assdadsddsf",  "1"  ], [ "2", "Data Tower", "https://www.google.co.in/", "abc", 1234567, "abc@gmail.com", "assdadsddsf", "2" ], ["3","Enter business", "https://www.google.co.in/", "abc", 1234567, "abc@gmail.com","assdadsddsf", "3" ]]}'

  $scope.datas = JSON.parse(data);
});

Play code here https://jsfiddle.net/ikismail7/2uufzqqh/


问:
Possible to have a floating horizontal scrollbar?
I have a site with a large table on it, It is very high and because of this to get to the horizontal scroll bar I have to scroll to the bottom of the page.

Is there anyway to have the horizontal scroll bar floating at the bottom of the window and always accessible without having to scroll to the bottom of the webpage first?

答:
R. Oosterholt's answer is beautiful and great. But as I am noob, it kill my 4 hour to make it working. To save other's time: you have to put following style on div:

```<code>.spacious-container {
    overflow: auto;
    width: 100%;
}
</code>```

And then call

```<code>$(document).ready(function () {
    $(".spacious-container").floatingScroll();
});
</code>```

Note: attachScroll() is old method and will remove in future release.

Plugin's details can be found here (floating-scroll)

Body:
R. Oosterholt's answer is beautiful and great. But as I am noob, it kill my 4 hour to make it working. To save other's time: you have to put following style on div:

.spacious-container {
    overflow: auto;
    width: 100%;
}

And then call

$(document).ready(function () {
    $(".spacious-container").floatingScroll();
});

Note: attachScroll() is old method and will remove in future release.

Plugin's details can be found here (floating-scroll)


问:
Setting up enviroment variables in Windows 10 to use java and javac
I got a new laptop with Windows 10 and I want to set it up so I can use java and javac from the command line.

I have searched online but all the guides are for previous versions, and I don't want to mess around with something I don't understand.

答:
Right click Computer

Click the properties

On the left pane    select Advanced System Settings

Select Environment Variables

Under the System Variables, Select PATH and click edit,

and then click new and add path as C:\Program

Files\Java\jdk1.8.0_131\bin (depending on your installation path)

and finally click ok

Next restart your command prompt and open it and try javac


问:
Setting path parameters in AWS API Gateway JavaScript SDK
I'm trying to set path parameters when making calls to API Gateway endpoints via the JavaScript SDK and not having any luck.  It looks like I either have something misconfigured or there is a bug in the SDK generation.

I am able to successfully call endpoints that do not take path parameters but when I try to pass in a parameter to be used as a path parameter the SDK just replaces the path parameter with a blank and my call fails.

Example, assume client is a properly initialized API Gateway client.  I have an endpoint called /measurement with a child of /measurement/{id}.  I am able to call both directly.

client.measurementGet({},{}); - successfully calls my /measurement endpoint
client.measurementIdGet({"id": "1234"}, {}); - Browser makes a call to /measurement/ instead of /measurement/1234

Looking at the source of my apigClient.js, it appears that the SDK generator is not putting path parameters into the list of parameters that it's looking for.  For example, the code of my generated measurementIdGet method looks like this:

```<code>    apigClient.measurementIdGet = function (params, body, additionalParams) {
        if(additionalParams === undefined) { additionalParams = {}; }

        apiGateway.core.utils.assertParametersDefined(params, [], ['body']);

        var measurementIdGetRequest = {
            verb: 'get'.toUpperCase(),
            path: pathComponent + uritemplate('/measurement/{id}').expand(apiGateway.core.utils.parseParametersToObject(params, [])),
            headers: apiGateway.core.utils.parseParametersToObject(params, []),
            queryParams: apiGateway.core.utils.parseParametersToObject(params, []),
            body: body
        };

        return apiGatewayClient.makeRequest(measurementIdGetRequest, authType, additionalParams, config.apiKey);
    };
</code>```

I dug into the assertParametersDefined and parseParametersToObject and it looks like those methods are expecting a list of parameters to look for.  In both cases the SDK has generated empty lists instead of putting my path parameter in there.

If I manually update the generated file to change the two lines to

apiGateway.core.utils.assertParametersDefined(params, ['id'], ['body']);

and

apiGateway.core.utils.parseParametersToObject(params, ['id'])

The SDK makes the proper call.

Am I missing something in my configuration or is there a bug in the code generator?

答:
If you are using cloud formation like me. You will need to add it in the RequestParameters.

for a resource like this /api/pets/{id}/attributes/{attrid}  following code works

```<code>  PetsByIdAttributesByAttridGetMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref MyApi
      ResourceId: !Ref PetsByIdAttributesByAttridResource
      HttpMethod: GET
      AuthorizationType: AWS_IAM
      RequestParameters:
        method.request.path.id : true
        method.request.path.attrid : true
      Integration:
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambda.Arn}/invocations
</code>```

Body:
I'm trying to set path parameters when making calls to API Gateway endpoints via the JavaScript SDK and not having any luck.  It looks like I either have something misconfigured or there is a bug in the SDK generation.

I am able to successfully call endpoints that do not take path parameters but when I try to pass in a parameter to be used as a path parameter the SDK just replaces the path parameter with a blank and my call fails.

Example, assume client is a properly initialized API Gateway client.  I have an endpoint called /measurement with a child of /measurement/{id}.  I am able to call both directly.

client.measurementGet({},{}); - successfully calls my /measurement endpoint
client.measurementIdGet({"id": "1234"}, {}); - Browser makes a call to /measurement/ instead of /measurement/1234

Looking at the source of my apigClient.js, it appears that the SDK generator is not putting path parameters into the list of parameters that it's looking for.  For example, the code of my generated measurementIdGet method looks like this:

    apigClient.measurementIdGet = function (params, body, additionalParams) {
        if(additionalParams === undefined) { additionalParams = {}; }

        apiGateway.core.utils.assertParametersDefined(params, [], ['body']);

        var measurementIdGetRequest = {
            verb: 'get'.toUpperCase(),
            path: pathComponent + uritemplate('/measurement/{id}').expand(apiGateway.core.utils.parseParametersToObject(params, [])),
            headers: apiGateway.core.utils.parseParametersToObject(params, []),
            queryParams: apiGateway.core.utils.parseParametersToObject(params, []),
            body: body
        };

        return apiGatewayClient.makeRequest(measurementIdGetRequest, authType, additionalParams, config.apiKey);
    };

I dug into the assertParametersDefined and parseParametersToObject and it looks like those methods are expecting a list of parameters to look for.  In both cases the SDK has generated empty lists instead of putting my path parameter in there.

If I manually update the generated file to change the two lines to

apiGateway.core.utils.assertParametersDefined(params, ['id'], ['body']);

and

apiGateway.core.utils.parseParametersToObject(params, ['id'])

The SDK makes the proper call.

Am I missing something in my configuration or is there a bug in the code generator?

Body:
If you are using cloud formation like me. You will need to add it in the RequestParameters.

for a resource like this /api/pets/{id}/attributes/{attrid}  following code works

  PetsByIdAttributesByAttridGetMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      RestApiId: !Ref MyApi
      ResourceId: !Ref PetsByIdAttributesByAttridResource
      HttpMethod: GET
      AuthorizationType: AWS_IAM
      RequestParameters:
        method.request.path.id : true
        method.request.path.attrid : true
      Integration:
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambda.Arn}/invocations


问:
Is it possible to assign names of these checkboxes dynamically according to the batch in the back end php script?
batch1

                center1
                center2

```<code>            center3    <input type="checkbox" name=center$a[] value="3">

            center4    <input type="checkbox" name=center$a[] value="4"><br>

      batch2  <br>
              center1   <input type="checkbox" name=center$a[] value="1">
             center2    <input type="checkbox" name=center$a[] value="2">

             center3    <input type="checkbox" name=center$a[] value="3">

             center4   <input type="checkbox" name=center$a[] value="4"><br>

 batch3       <br>

             center1   <input type="checkbox" name=center$a[] value="1">
             center2   <input type="checkbox" name=center$a[] value="2">

              center3  <input type="checkbox" name=center$a[] value="3">

             center4   <input type="checkbox" name=center$a[] value="4"><br>

   batch4    <br>

           center1     <input type="checkbox" name=center$a[] value="1">
             center2   <input type="checkbox" name=center$a[] value="2">

             center3   <input type="checkbox" name=center$a[] value="3">

             center4   <input type="checkbox" name=center$a[] value="4"><br>

    <input type="submit" name="submit">
        Is it possible to assign names of these checkboxes dynamically according to the batch in the back end php script?
</code>```

I tried using a variable in the name but while receiving values in the backend php script it does not take the variable separately hence I am not able to assign dynamic values according to batch.

答:
Is is probably because the variables aren't evaluated, try to change the lines like:

```<code><input type="checkbox" name="center<?= $a ?>" value="1">
</code>```

Although at this moment you will have everywhere the same variable $a assigned - so it should be something more like name="center<?= $yourArray[$iteration] ?>" so the names would be unique, or like name="center[]" id="center<?= $iteration ?>" depending what you need.

Update:
If you want four (or any number) of "batches" of sets the better answer (as noticed Harrie de Laat in the comments below) would be:

```<code><input type="checkbox" name="center<?= $a ?>[]" value="1">
</code>```

Of course you'd have to change the $a variable with every batch.

Body:
batch1

                center1
                center2

            center3    <input type="checkbox" name=center$a[] value="3">

            center4    <input type="checkbox" name=center$a[] value="4">

      batch2

              center1   <input type="checkbox" name=center$a[] value="1">
             center2    <input type="checkbox" name=center$a[] value="2">

             center3    <input type="checkbox" name=center$a[] value="3">

             center4   <input type="checkbox" name=center$a[] value="4">

 batch3

             center1   <input type="checkbox" name=center$a[] value="1">
             center2   <input type="checkbox" name=center$a[] value="2">

              center3  <input type="checkbox" name=center$a[] value="3">

             center4   <input type="checkbox" name=center$a[] value="4">

   batch4

           center1     <input type="checkbox" name=center$a[] value="1">
             center2   <input type="checkbox" name=center$a[] value="2">

             center3   <input type="checkbox" name=center$a[] value="3">

             center4   <input type="checkbox" name=center$a[] value="4">

    <input type="submit" name="submit">
        Is it possible to assign names of these checkboxes dynamically according to the batch in the back end php script?

I tried using a variable in the name but while receiving values in the backend php script it does not take the variable separately hence I am not able to assign dynamic values according to batch.

Body:
Is is probably because the variables aren't evaluated, try to change the lines like:

<input type="checkbox" name="center<?= $a ?>" value="1">

Although at this moment you will have everywhere the same variable $a assigned - so it should be something more like name="center<?= $yourArray[$iteration] ?>" so the names would be unique, or like name="center[]" id="center<?= $iteration ?>" depending what you need.

Update:
If you want four (or any number) of "batches" of sets the better answer (as noticed Harrie de Laat in the comments below) would be:

<input type="checkbox" name="center<?= $a ?>[]" value="1">

Of course you'd have to change the $a variable with every batch.


问:
Get most common column for each column value
I want the most common letter for each number. I've tried a variety of things; not sure what's the right way.

```<code>import pandas as pd
from pandas import DataFrame, Series

original = DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}
})

expected = DataFrame({'most_common_letter': {'01': 'A', '02': 'B'}})
</code>```

Ideally I'm looking to maximize readability.

答:
We can use DataFrame.mode() method:</p>

```<code>In [43]: df.groupby('number')[['letter']] \
           .apply(lambda x: x.mode()) \
           .reset_index(level=1, drop=True)
Out[43]:
       letter
number
01          A
02          B
</code>```

Body:
I want the most common letter for each number. I've tried a variety of things; not sure what's the right way.

import pandas as pd
from pandas import DataFrame, Series

original = DataFrame({
    'letter': {0: 'A', 1: 'A', 2: 'A', 3: 'B', 4: 'B'},
    'number': {0: '01', 1: '01', 2: '02', 3: '02', 4: '02'}
})

expected = DataFrame({'most_common_letter': {'01': 'A', '02': 'B'}})

Ideally I'm looking to maximize readability.

Body:
We can use DataFrame.mode() method:

In [43]: df.groupby('number')[['letter']] \
           .apply(lambda x: x.mode()) \
           .reset_index(level=1, drop=True)
Out[43]:
       letter
number
01          A
02          B


问:
Persistent bridge between a React VR component and native module code
I am trying to have my browser send in some DOM events into the React VR components.

The closest I got is this code using "native modules."

(client.js)

```<code>const windowEventsModule = new WindowEventsModule();

function init(bundle, parent, options) {
  const vr = new VRInstance(bundle, 'WelcomeToVR', parent, {
    ...options,
    nativeModules: [windowEventsModule]
  });

  windowEventsModule.init(vr.rootView.context);

  vr.start();

  return vr;
}

window.ReactVR = {init};
</code>```

(WindowEventsModule.js)

```<code>export default class WindowEventsModule extends Module {
  constructor() {
    super('WindowEventsModule');

    this.listeners = {};

    window.onmousewheel = event => {
      this._emit('onmousewheel', event);
    };
  }

  init(rnctx) {
    this._rnctx = rnctx;
  }

  _emit(name, ob) {
    if (!this._rnctx) {
      return;
    }

    Object.keys(this.listeners).forEach(key => {
      this._rnctx.invokeCallback(this.listeners[key], [ob]);
    });
  }

  onMouseWheel(listener) {
    const key = String(Math.random());
    this.listeners[key] = listener;
    return () => {
      delete this.listeners[key];
    };
  }
}
</code>```

So my components can now call WindowEvents.onMouseWheel(function() {}), and get a callback from the DOM world.

Unfortunately, this only works once. RN will apparently invalidate my callback after it is called.

I also investigated this._rnctx.callFunction(), which can call an arbitrary function on something called "callable module". I don't see how I can get from there to my components.

Is there something I am missing? What's the pattern to feed arbitrary messages from the native world into the ReactVR background worker?

答:
I figured it out... sort of.

The trick was to create my own "BatchedBridge", which I can then reach using the callFunction() from the context.

(index.vr.js)

```<code>import React from 'react';
import {AppRegistry, asset, Pano, View} from 'react-vr';
import BatchedBridge from 'react-native/Libraries/BatchedBridge/BatchedBridge';
import lodash from 'lodash';

class BrowserBridge {
    constructor() {
        this._subscribers = {};
    }

    subscribe(handler) {
        const key = String(Math.random());
        this._subscribers[key] = handler;
        return () => {
            delete this._subscribers[key];
        };
    }

    notifyEvent(name, event) {
        lodash.forEach(this._subscribers, handler => {
            handler(name, event);
        });
    }
}

const browserBridge = new BrowserBridge();
BatchedBridge.registerCallableModule(BrowserBridge.name, browserBridge);

export default class WelcomeToVR extends React.Component {
    constructor(props) {
        super(props);

        this.onBrowserEvent = this.onBrowserEvent.bind(this);
    }

    componentWillMount() {
        this.unsubscribe = browserBridge.subscribe(this.onBrowserEvent);
    }

    onBrowserEvent(name, event) {
        // Do the thing here
    }

    componentWillUnmount() {
        if (this.unsubscribe) {
            this.unsubscribe();
            delete this.unsubscribe;
        }
    }

    render() {
        //...
    }
};

AppRegistry.registerComponent('WelcomeToVR', () => WelcomeToVR);
</code>```

(WindowEventsModule.js)

```<code>import {Module} from 'react-vr-web';
import lodash from 'lodash';

const eventToOb = (event) => {
    const eventOb = {};
    for (let key in event) {
        const val = event[key];
        if (!(lodash.isFunction(val) || lodash.isObject(val))) {
            eventOb[key] = val;
        }
    }
    return eventOb;
};

export default class WindowEventsModule extends Module {
    constructor() {
        super('WindowEventsModule');

        this._bridgeName = 'BrowserBridge';

        window.onmousewheel = event => {
            this._emit('onmousewheel', event);
        };
    }

    init(rnctx) {
        this._rnctx = rnctx;
    }

    _emit(name, event) {
        if (!this._rnctx) {
            return;
        }

        const eventOb = eventToOb(event);

        this._rnctx.callFunction(this._bridgeName, 'notifyEvent', [name, eventOb]);
    }
}
</code>```

This feels very hacky, as it doesn't seem BatchedBridge was ever meant to be exposed to consumers.

But until there is a better option, I think I'll go with this.

Body:
I am trying to have my browser send in some DOM events into the React VR components.

The closest I got is this code using "native modules."

(client.js)

const windowEventsModule = new WindowEventsModule();

function init(bundle, parent, options) {
  const vr = new VRInstance(bundle, 'WelcomeToVR', parent, {
    ...options,
    nativeModules: [windowEventsModule]
  });

  windowEventsModule.init(vr.rootView.context);

  vr.start();

  return vr;
}

window.ReactVR = {init};

(WindowEventsModule.js)

export default class WindowEventsModule extends Module {
  constructor() {
    super('WindowEventsModule');

    this.listeners = {};

    window.onmousewheel = event => {
      this._emit('onmousewheel', event);
    };
  }

  init(rnctx) {
    this._rnctx = rnctx;
  }

  _emit(name, ob) {
    if (!this._rnctx) {
      return;
    }

    Object.keys(this.listeners).forEach(key => {
      this._rnctx.invokeCallback(this.listeners[key], [ob]);
    });
  }

  onMouseWheel(listener) {
    const key = String(Math.random());
    this.listeners[key] = listener;
    return () => {
      delete this.listeners[key];
    };
  }
}

So my components can now call WindowEvents.onMouseWheel(function() {}), and get a callback from the DOM world.

Unfortunately, this only works once. RN will apparently invalidate my callback after it is called.

I also investigated this._rnctx.callFunction(), which can call an arbitrary function on something called "callable module". I don't see how I can get from there to my components.

Is there something I am missing? What's the pattern to feed arbitrary messages from the native world into the ReactVR background worker?

Body:
I figured it out... sort of.

The trick was to create my own "BatchedBridge", which I can then reach using the callFunction() from the context.

(index.vr.js)

import React from 'react';
import {AppRegistry, asset, Pano, View} from 'react-vr';
import BatchedBridge from 'react-native/Libraries/BatchedBridge/BatchedBridge';
import lodash from 'lodash';

class BrowserBridge {
    constructor() {
        this._subscribers = {};
    }

    subscribe(handler) {
        const key = String(Math.random());
        this._subscribers[key] = handler;
        return () => {
            delete this._subscribers[key];
        };
    }

    notifyEvent(name, event) {
        lodash.forEach(this._subscribers, handler => {
            handler(name, event);
        });
    }
}

const browserBridge = new BrowserBridge();
BatchedBridge.registerCallableModule(BrowserBridge.name, browserBridge);

export default class WelcomeToVR extends React.Component {
    constructor(props) {
        super(props);

        this.onBrowserEvent = this.onBrowserEvent.bind(this);
    }

    componentWillMount() {
        this.unsubscribe = browserBridge.subscribe(this.onBrowserEvent);
    }

    onBrowserEvent(name, event) {
        // Do the thing here
    }

    componentWillUnmount() {
        if (this.unsubscribe) {
            this.unsubscribe();
            delete this.unsubscribe;
        }
    }

    render() {
        //...
    }
};

AppRegistry.registerComponent('WelcomeToVR', () => WelcomeToVR);

(WindowEventsModule.js)

import {Module} from 'react-vr-web';
import lodash from 'lodash';

const eventToOb = (event) => {
    const eventOb = {};
    for (let key in event) {
        const val = event[key];
        if (!(lodash.isFunction(val) || lodash.isObject(val))) {
            eventOb[key] = val;
        }
    }
    return eventOb;
};

export default class WindowEventsModule extends Module {
    constructor() {
        super('WindowEventsModule');

        this._bridgeName = 'BrowserBridge';

        window.onmousewheel = event => {
            this._emit('onmousewheel', event);
        };
    }

    init(rnctx) {
        this._rnctx = rnctx;
    }

    _emit(name, event) {
        if (!this._rnctx) {
            return;
        }

        const eventOb = eventToOb(event);

        this._rnctx.callFunction(this._bridgeName, 'notifyEvent', [name, eventOb]);
    }
}

This feels very hacky, as it doesn't seem BatchedBridge was ever meant to be exposed to consumers.

But until there is a better option, I think I'll go with this.


答:
I think it's more a comment, but I can't write it because of my low reputation.

Are you sure you want a density? Without it you get a nice histogram:

```<code>dt <- data.frame(am = c(1,0,0,1,1,0,1,1,1,1),
predictions = c(1,7.884922e-12,7.884924e-12,1,7.884886e-12,7.884923e-12,1,7.884916e-12,1,7.884918e-12))
dt$am <- factor(dt$am, levels = c("1" , "0"))

g <- ggplot(dt, aes(x = predictions, fill = am))
g+geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) +
labs(title = "Predicted Probabilities per am in the Test Dataset",
x = "Predicted Probability of being in am 1", y = "Count") +
scale_fill_manual(limits=c('1', '0'),
labels = c("Positive", "Negative"),
values = c("red", 'blue')) +
labs(fill="am")
</code>```

I just deleted geom_density (and color mapping, you already have fill!).
And that's what I got:
Histogram

The problem with density may occur because the data is wierd. For am = 0 you have a 100% probability to get in an interval between 7.88492e-12 and 7.88493e-12. Though it doesn't even use your colors...

Title: ggplot - histogram - density plot by group : Only one group appears

Body:
I have a small dataset and I want to plot a histogram/density plot using ggplot by group.  My dataset is the following:

> data_Test_augm
     mpg cyl4 cyl6 cyl8  disp  hp drat    wt  qsec vs0 vs1 gear3 gear4 gear5 carb1 carb2 carb3 carb4 carb6 carb8 am  predictions
 1: 21.0    0    1    0 160.0 110 3.90 2.620 16.46   1   0     0     1     0     0     0     0     1     0     0  1 1.000000e+00
 2: 21.4    0    1    0 258.0 110 3.08 3.215 19.44   0   1     1     0     0     1     0     0     0     0     0  0 7.884922e-12
 3: 17.8    0    1    0 167.6 123 3.92 3.440 18.90   0   1     0     1     0     0     0     0     1     0     0  0 7.884924e-12
 4: 32.4    1    0    0  78.7  66 4.08 2.200 19.47   0   1     0     1     0     1     0     0     0     0     0  1 1.000000e+00
 5: 30.4    1    0    0  75.7  52 4.93 1.615 18.52   0   1     0     1     0     0     1     0     0     0     0  1 7.884886e-12
 6: 19.2    0    0    1 400.0 175 3.08 3.845 17.05   1   0     1     0     0     0     1     0     0     0     0  0 7.884923e-12
 7: 26.0    1    0    0 120.3  91 4.43 2.140 16.70   1   0     0     0     1     0     1     0     0     0     0  1 1.000000e+00
 8: 30.4    1    0    0  95.1 113 3.77 1.513 16.90   0   1     0     0     1     0     1     0     0     0     0  1 7.884916e-12
 9: 19.7    0    1    0 145.0 175 3.62 2.770 15.50   1   0     0     0     1     0     0     0     0     1     0  1 1.000000e+00
10: 21.4    1    0    0 121.0 109 4.11 2.780 18.60   0   1     0     1     0     0     1     0     0     0     0  1 7.884918e-12

My code is the following:

data_Test_augm$am <- factor(data_Test_augm$am, levels = c("1" , "0"))  #Sets the faactor levels in the desired order

ggplot(data_Test_augm, aes(x = predictions, fill = am , color = am )) +
  geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) + guides(color = FALSE) +
  geom_density (alpha = 0.5)+
  labs(title = "Predicted Probabilities per am in the Test Dataset",
       x = "Predicted Probability of being in am 1", y = "Count") +
  scale_fill_manual(limits=c('1', '0'),              # Defines the mapping between factor levels, labels and colors
                    labels = c("Positive", "Negative"),
                    values = c("red", 'blue')) +
  labs(fill="am")+  # Sets the title of the legend
  guides(color=FALSE)  # Hides the legend for Color

And this is the output:

I don't understand why only one of the levels of the grouping variable am appears in the plot.

Body:
I think it's more a comment, but I can't write it because of my low reputation.

Are you sure you want a density? Without it you get a nice histogram:

dt <- data.frame(am = c(1,0,0,1,1,0,1,1,1,1),
predictions = c(1,7.884922e-12,7.884924e-12,1,7.884886e-12,7.884923e-12,1,7.884916e-12,1,7.884918e-12))
dt$am <- factor(dt$am, levels = c("1" , "0"))

g <- ggplot(dt, aes(x = predictions, fill = am))
g+geom_histogram(aes(y=..density..), position="identity",alpha = 0.4) +
labs(title = "Predicted Probabilities per am in the Test Dataset",
x = "Predicted Probability of being in am 1", y = "Count") +
scale_fill_manual(limits=c('1', '0'),
labels = c("Positive", "Negative"),
values = c("red", 'blue')) +
labs(fill="am")

I just deleted geom_density (and color mapping, you already have fill!).
And that's what I got:
Histogram

The problem with density may occur because the data is wierd. For am = 0 you have a 100% probability to get in an interval between 7.88492e-12 and 7.88493e-12. Though it doesn't even use your colors...