问:
In Bootstrap Material design, my dropdown is toggling by itself and flashing error
Here In the code I'm using Bootstrap Material Design and Bootstrap CDN both. while in Drawer If I try to open the category dropdown menu means it's just flashing. I tries to do it other sides also. like within container. But there also same flashing error.

I copied from Bootstrap official site as well as from Material bootstrap also both also I tried but the "Categories dropdown menu is showing the same"

<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
  <link rel="stylesheet" type="text/css" href="css/index.css">
  <link rel="icon" href="img/logo.png">
  <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  <title>aabbaaaa</title>

          <button class="navbar-toggler" type="button" data-toggle="drawer" data-target="#dw-s2">
            Toggle drawer
            menu
            </button>
          aabbaaaa

          0

          Home

                Categories

                Action
                Another action
                Something else here

Product

Shopping Cart

Checkout

My Order

My wishlist

My account

My notifications

Help Center

          <button class="btn bmd-btn-icon" for="search" data-toggle="collapse" data-target="#collapse-search" aria-expanded="false" aria-controls="collapse-search">
            search
            </button>

            <input class="form-control" type="text" id="search" placeholder="Enter your query...">

Main content

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

```

答:
you just add code comments for bootstrap 4 CDNs after commenting that all thing are works fine. you can check it in below snippet.

<!DOCTYPE html>

  <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
  <link rel="stylesheet" type="text/css" href="css/index.css">
  <link rel="icon" href="img/logo.png">
  <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">

  <title>aabbaaaa</title>

          <button class="navbar-toggler" type="button" data-toggle="drawer" data-target="#dw-s2">
            Toggle drawer
            menu
          </button>
          aabbaaaa

          0

          Home

                Categories

                Action
                Another action
                Something else here

Product

Shopping Cart

Checkout

My Order

My wishlist

My account

My notifications

Help Center

          <button class="btn bmd-btn-icon" for="search" data-toggle="collapse" data-target="#collapse-search" aria-expanded="false" aria-controls="collapse-search">
            search
          </button>

            <input class="form-control" type="text" id="search" placeholder="Enter your query...">

Main content

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?

```

Note: MDB(Material Design Bootstrap) and BS4 (Bootstrap 4) both are use same grid structures. But in MDB some additional functionalities are added so you can use MDB only. no need to use BS4 with MDB because that make some code conflicting for the click events and like burger menu and drop-down menu etc.

I hope this works fine for you.

Thank You...

Body:
you just add code comments for bootstrap 4 CDNs after commenting that all thing are works fine. you can check it in below snippet.

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
  <link rel="stylesheet" type="text/css" href="css/index.css">
  <link rel="icon" href="img/logo.png">
  <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> -->
  <style>
  </style>
  <title>aabbaaaa</title>
</head>
<body>
  <div>
    <div class="bmd-layout-container bmd-drawer-f-l bmd-drawer-overlay" id="d1">
      <header class="bmd-layout-header">
        <div class="navbar navbar-light bg-faded">
          <button class="navbar-toggler" type="button" data-toggle="drawer" data-target="#dw-s2">
            <span class="sr-only">Toggle drawer</span>
            <i class="material-icons">menu</i>
          </button>
          <a href="index.html" class="navbar-brand" style="padding-right: 30%;">aabbaaaa</a>
          <i class="far fa-user-circle" style="padding:0;"></i></i>
          <i class="fas fa-shopping-cart"><sup><span class="badge badge-info">0</span></sup></i>
        </div>
      </header>
      <div id="dw-s2" class="bmd-layout-drawer bg-faded">
        <header style="display: inline-block;">
          <a href="index.html" style="text-decoration: none;"><i class="fas fa-home"></i>Home</a>
          <a class="navbar-brand" href="index.html" style="padding-left: 50%;;"><img src="img/logo.png" class="img-fluid" style="height: 25px;width: 25px;"></a>
        </header>
        <ul class="list-group">
          <li class="list-group-item">
            <div class="dropdown show">
              <a class="dropdown-toggle text-dark" href="#" role="link" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                Categories
              </a>
              <div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
                <a class="dropdown-item" href="#">Action</a>
                <a class="dropdown-item" href="#">Another action</a>
                <a class="dropdown-item" href="#">Something else here</a>
              </div>
            </div>
          </li>
          <li class="list-group-item">Product</li>
          <li class="list-group-item">Shopping Cart</li>
          <li class="list-group-item">Checkout</li>
          <li class="list-group-item">My Order</li>
          <li class="list-group-item">My wishlist</li>
          <li class="list-group-item">My account</li>
          <li class="list-group-item">My notifications</li>
          <li class="list-group-item">Help Center</li>
        </ul>
      </div>
      <main class="bmd-layout-content">
        <div class="bmd-form-group bmd-collapse-inline pull-xs-right">
          <button class="btn bmd-btn-icon" for="search" data-toggle="collapse" data-target="#collapse-search" aria-expanded="false" aria-controls="collapse-search">
            <i class="material-icons">search</i>
          </button>
          <span id="collapse-search" class="collapse">
            <input class="form-control" type="text" id="search" placeholder="Enter your query...">
          </span>
        </div>
        <div class="container">
          <p>Main content</p>
          <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?</p>
          <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?</p>
          <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?</p>
          <p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis velit consequuntur error! Rem fugiat, quibusdam dolorum laborum quo reprehenderit non? Blanditiis dolorum rem nisi, quidem delectus explicabo aliquid ipsum sequi?</p>
        </div>
      </main>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
  <!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> -->
  <!-- <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> -->
  <!-- <script src="https://unpkg.com/popper.js@1.12.6/dist/umd/popper.js"></script> -->
  <script src="https://unpkg.com/bootstrap-material-design@4.1.1/dist/js/bootstrap-material-design.js"></script>
  <script>$(document).ready(function() { $('body').bootstrapMaterialDesign(); });</script>
  <script type="text/javascript" src="cordova.js"></script>
  <script type="text/javascript" src="js/index.js"></script>
  <script src="https://kit.fontawesome.com/596df9a01c.js" crossorigin="anonymous"></script>
</body>
</html>

Note: MDB(Material Design Bootstrap) and BS4 (Bootstrap 4) both are use same grid structures. But in MDB some additional functionalities are added so you can use MDB only. no need to use BS4 with MDB because that make some code conflicting for the click events and like burger menu and drop-down menu etc.

I hope this works fine for you.

Thank You...


来源: stackexchange

问:
Vue component only updating on console hover, window resize, etc, after FirebaseUI redirect
I'm working on a Vue(tify) login using FirebaseUI. The login occurs in a v-dialog and redirects to an "account" page. The relevant script:

```<code>export default {
  data() {
    let uiConfig = {
      signInSuccessUrl: "/account",
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
      ]
    },
    return {
      uiConfig: uiConfig
    }
  }
}
</code>```

The account page, on the other hand, looks like this:

```<code><template>
  <div v-if="user">{{ user.displayName }}</div>
</template>

<script>
export default {
  data() {
    return {
      user: null
    }
  },
  created() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.user = { displayName: user.displayName };
      }
    });
  }
}
</script>
</code>```

My expected behavior: I click one of the login options (let's say Google) and it redirects me to /account. Then it renders the div and shows me my username.

Actual behavior: after redirect the page remains blank. The page renders correctly when I open the drawer, or resize the window, or hover over the Vue developer console in chrome DevTools.

I think this is because the DOM isn't getting rendered successfully... but no matter what I try I can't make it work.

Any ideas?

答:
In the end the problem seems to be how FirebaseUI's SignInSuccessful method plays with vue-router: not well. To avoid this problem I've taken out the method and added a callback that fires on a successful sign in.

```<code>uiConfig: {
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID
  ],
  callbacks: {
    signInSuccessWithAuthResult: function() {this.$router.push({ path: 'account' })}
  }
},
</code>```

With this change the expected behavior is achieved.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a Vue(tify) login using FirebaseUI. The login occurs in a v-dialog and redirects to an "account" page. The relevant script:

export default {
  data() {
    let uiConfig = {
      signInSuccessUrl: "/account",
      signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
      ]
    },
    return {
      uiConfig: uiConfig
    }
  }
}

The account page, on the other hand, looks like this:

<template>

{{ user.displayName }}

</template>

My expected behavior: I click one of the login options (let's say Google) and it redirects me to /account. Then it renders the div and shows me my username.

Actual behavior: after redirect the page remains blank. The page renders correctly when I open the drawer, or resize the window, or hover over the Vue developer console in chrome DevTools.

I think this is because the DOM isn't getting rendered successfully... but no matter what I try I can't make it work.

Any ideas?

Body:
In the end the problem seems to be how FirebaseUI's SignInSuccessful method plays with vue-router: not well. To avoid this problem I've taken out the method and added a callback that fires on a successful sign in.

uiConfig: {
  signInOptions: [
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
    firebase.auth.FacebookAuthProvider.PROVIDER_ID
  ],
  callbacks: {
    signInSuccessWithAuthResult: function() {this.$router.push({ path: 'account' })}
  }
},

With this change the expected behavior is achieved.


问:
AngularJS: Selected Id is not passed to the Service
To edit the user information ,when I change the role of user and submit the form, the old "id" is passed to the service, however when I change the role ,it shows the id is changed (I print it on the screen
Selected Value is : {{selectedItemvalue}}
).
but still old "id" is passed like if the user role is admin with id number 2 and if I change it to user with id number 1, role id 1 should be passed instead of 2 but the old one which is 2 is passed.

I have checked below post but it didn't work out.
AngularJS: Get selected Item

```<code>     <div class="col-md-7">
            <select ng-model="selectedItemvalue">
             <option ng-repeat="role in roless" ng-       selected="selectedItemvalue ==  role.id"
            value="{{role.id}}">{{role.name}}</option>
    </select>
    <p>Selected Value is : {{selectedItemvalue}}</p>
     </div>

        <form ng-submit="submitUserForm(user.id)" name="myForm"
                class="form-horizontal">
</code>```

app.controller('usersDetailsController',
          function($rootScope,$scope,$http,

```<code>      $location,$routeParams,$route) {

       if ($rootScope.authenticated && $rootScope.role=="ADMIN") {

        $scope.roless = [{"id": 1, "name": "USER"}, {"id": 2,  "name":"ADMIN"}];

        $scope.userId = $routeParams.id;
        $http({
        method: 'GET',
        url: 'http://localhost:8080/api/user/' + $scope.userId
        }).then(function (response) {

        $scope.user = response.data;
        $scope.selectedItemvalue = $scope.user.roles[0].id;
        console.log("CurrentRole..."+ $scope.selectedItemvalue);
        console.log("Current data of user..."+           JSON.stringify(response.data));});

         $scope.submitUserForm = function (userId) {

         $http({
            method: 'PUT',
            url: 'http://localhost:8080/api/user/' + userId,
            data: $scope.user

         }).then(
            function (response) {
                console.log("Updated Role data..."+ JSON.stringify(response.data));
                $location.path("/list-all-users");
                $route.reload();
                },
                function (errResponse) {
                $scope.errorMessage = "Error while updating User - Error Message: '" + errResponse.data.errorMessage;
            });
            }
</code>```

答:
Finally found where the problem is and issue solved by adding below line of    code to $scope.submitUserForm...  actually when you submit the form, it needs to get the id from ng-model and set it to user's role id like this...

$scope.user.roles[0].id = $scope.selectedItemvalue;

Body:
To edit the user information ,when I change the role of user and submit the form, the old "id" is passed to the service, however when I change the role ,it shows the id is changed (I print it on the screen
Selected Value is : {{selectedItemvalue}}
).
but still old "id" is passed like if the user role is admin with id number 2 and if I change it to user with id number 1, role id 1 should be passed instead of 2 but the old one which is 2 is passed.

I have checked below post but it didn't work out.
AngularJS: Get selected Item

            <select ng-model="selectedItemvalue">
             <option ng-repeat="role in roless" ng-       selected="selectedItemvalue ==  role.id"
            value="{{role.id}}">{{role.name}}</option>
    </select>

Selected Value is : {{selectedItemvalue}}

        <form ng-submit="submitUserForm(user.id)" name="myForm"
                class="form-horizontal">

app.controller('usersDetailsController',
          function($rootScope,$scope,$http,

      $location,$routeParams,$route) {

       if ($rootScope.authenticated && $rootScope.role=="ADMIN") {

        $scope.roless = [{"id": 1, "name": "USER"}, {"id": 2,  "name":"ADMIN"}];

        $scope.userId = $routeParams.id;
        $http({
        method: 'GET',
        url: 'http://localhost:8080/api/user/' + $scope.userId
        }).then(function (response) {

        $scope.user = response.data;
        $scope.selectedItemvalue = $scope.user.roles[0].id;
        console.log("CurrentRole..."+ $scope.selectedItemvalue);
        console.log("Current data of user..."+           JSON.stringify(response.data));});

         $scope.submitUserForm = function (userId) {

         $http({
            method: 'PUT',
            url: 'http://localhost:8080/api/user/' + userId,
            data: $scope.user

         }).then(
            function (response) {
                console.log("Updated Role data..."+ JSON.stringify(response.data));
                $location.path("/list-all-users");
                $route.reload();
                },
                function (errResponse) {
                $scope.errorMessage = "Error while updating User - Error Message: '" + errResponse.data.errorMessage;
            });
            }


问:
AutoCloseable-ish method but runs only on catch

I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.

Like:

```<code>SomeService service = CreateService().andOpenTransaction()

try {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}
</code>```

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

答:
Well you could define your own interface, and then some static runner method:

```<code>public interface ErrorHandlingCloseable extends AutoCloseable {
     void run() throws Exception;
     void onError(Exception e);

     static void execute(ErrorHandlingClosable ehc) throws Exception {
         try(ErrorHandlingClosable temp = ehc) {
             ehc.run();
         } catch(Exception e) {
             ehc.onError(e);
             throw e;
         }
     }
}
</code>```

Which you then could then call like this:

```<code>SomeService service = CreateService().andOpenTransaction();
ErrorHandlingCloseable.execute(new ErrorHandlingCloseable() {
    public void run() throws Exception { service.doSomeMessyThingsInsideDB(); }
    public void onError(Exception e) { service.rollbackTransaction(); }
    public void close() throws Exception { service.closeConnection(); }
});
</code>```

But you see, it's still messy.

You could even implement this interface in your SomeService but then you're restricted that the run() method will always call doSomeMessyThingsInsideDB().

Another way but still similar would be to use Java8 and create a helper functional interface:

```<code>public interface ThrowingRunnable {
   void run() throws Exception;
}
</code>```

And then a static method somewhere:

```<code>public static void execute(ThrowingRunnable action,
                           ThrowingRunnable onCatch,
                           ThrowingRunnable onFinally) throws Exception {
   try(AutoCloseable ao = onFinally) {
       action.run();
   } catch(Exception e) {
       onCatch.run();
       throw e;
   }
}
</code>```

The interesting part is probably this: try(AutoCloseable ao = onFinally), which "registers" your onFinally method to be called when finally is reached.

This could then be called like this:

```<code>execute(
    service::doSomeMessyThingsInsideDB,
    service::rollbackTransaction,
    service::closeConnection
);
</code>```

Body:
I would like to two have two different methods running in catch and final blocks. I have found AutoCloseable interface, but I need something to fire in case of exception only.

Like:

SomeService service = CreateService().andOpenTransaction()

try {
    service.doSomeMessyThingsInsideDB();
} catch (Exception e) {
    service.rollbackTransaction();
    throw e;
} finally {
    service.closeConnection();
}

Is there any way to make it simpler? As I said I am familiar with AutoCloseable, but it helps me only with finally block. I still cannot use it inside the catch.

Body:
Well you could define your own interface, and then some static runner method:

public interface ErrorHandlingCloseable extends AutoCloseable {
     void run() throws Exception;
     void onError(Exception e);

     static void execute(ErrorHandlingClosable ehc) throws Exception {
         try(ErrorHandlingClosable temp = ehc) {
             ehc.run();
         } catch(Exception e) {
             ehc.onError(e);
             throw e;
         }
     }
}

Which you then could then call like this:

SomeService service = CreateService().andOpenTransaction();
ErrorHandlingCloseable.execute(new ErrorHandlingCloseable() {
    public void run() throws Exception { service.doSomeMessyThingsInsideDB(); }
    public void onError(Exception e) { service.rollbackTransaction(); }
    public void close() throws Exception { service.closeConnection(); }
});

But you see, it's still messy.

You could even implement this interface in your SomeService but then you're restricted that the run() method will always call doSomeMessyThingsInsideDB().

Another way but still similar would be to use Java8 and create a helper functional interface:

public interface ThrowingRunnable {
   void run() throws Exception;
}

And then a static method somewhere:

public static void execute(ThrowingRunnable action,
                           ThrowingRunnable onCatch,
                           ThrowingRunnable onFinally) throws Exception {
   try(AutoCloseable ao = onFinally) {
       action.run();
   } catch(Exception e) {
       onCatch.run();
       throw e;
   }
}

The interesting part is probably this: try(AutoCloseable ao = onFinally), which "registers" your onFinally method to be called when finally is reached.

This could then be called like this:

execute(
    service::doSomeMessyThingsInsideDB,
    service::rollbackTransaction,
    service::closeConnection
);


问:
Count the Number of Changes in a Date Column based on another Attribute
Hi everyone I have faced a problem during my data validation. I need to have the number of changes in a date column for every unique variable in name column. For example:

```<code>student.data <- data.frame(student_id = c (1:7),
                            student_name=c("Rick","Rick","Michelle","Michelle","Rick","Michelle","John"),
                            mark = c(623.3,515.2,611.0,729.0,843.25,459.4,846.65),
                            date_of_exam = as.Date(c("2014-01-01","2013-09-23","2014-11-15","2014-05-11", "2014-01-01","2016-04-14","2015-05-12")))
</code>```

I know for a fact that it is kind of complicated but the result must be:

```<code>>table

>"Rick"
1
>"Michelle"
2
>"John"
0
</code>```

thanks in advance for your help.

答:
You can group by student and count the number of distinct dates and subtract one:</p>

```<code>library(dplyr)

student.data %>%
  group_by(student_name) %>%
  summarise(cnt = n_distinct(date_of_exam) -1)

# A tibble: 3 x 2
  student_name   cnt
  <fct>        <dbl>
1 John             0
2 Michelle         2
3 Rick             1
</code>```

Body:
Hi everyone I have faced a problem during my data validation. I need to have the number of changes in a date column for every unique variable in name column. For example:

student.data <- data.frame(student_id = c (1:7),
                            student_name=c("Rick","Rick","Michelle","Michelle","Rick","Michelle","John"),
                            mark = c(623.3,515.2,611.0,729.0,843.25,459.4,846.65),
                            date_of_exam = as.Date(c("2014-01-01","2013-09-23","2014-11-15","2014-05-11", "2014-01-01","2016-04-14","2015-05-12")))

I know for a fact that it is kind of complicated but the result must be:

>table

>"Rick"
1
>"Michelle"
2
>"John"
0

thanks in advance for your help.

Body:
You can group by student and count the number of distinct dates and subtract one:

library(dplyr)

student.data %>%
  group_by(student_name) %>%
  summarise(cnt = n_distinct(date_of_exam) -1)

# A tibble: 3 x 2
  student_name   cnt
  <fct>        <dbl>
1 John             0
2 Michelle         2
3 Rick             1


问:
Should I normalize this table?
I have a table Items which stores fetched book data from Amazon.  This Amazon data is inserted into Items as users browse the site, so any INSERT that occurs needs to be efficient.

Here's the table:

```<code>CREATE TABLE IF NOT EXISTS `items` (
  `Item_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Item_ISBN` char(13) DEFAULT NULL,
  `Title` varchar(255) NOT NULL,
  `Edition` varchar(20) DEFAULT NULL,
  `Authors` varchar(255) DEFAULT NULL,
  `Year` char(4) DEFAULT NULL,
  `Publisher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Item_ID`),
  UNIQUE KEY `Item_Data` (`Item_ISBN`,`Title`,`Edition`,`Authors`,`Year`,`Publisher`),
  KEY `ISBN` (`Item_ISBN`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=1 ;
</code>```

Normalizing this table would presumably mean creating tables for Titles, Authors, and Publishers.  My concern with doing this is that the insert would become too complex.. To insert a single Item, I'd have to:

Check for the Publisher in Publishers to SELECT Publisher_ID, otherwise insert it and use mysql_insert_id() to get Publisher_ID.

Check for the Authors in Authors to SELECT Authors_ID, otherwise insert it and use mysql_insert_id() to get Authors_ID.

Check for the Title in Titles to SELECT Title_ID, otherwise insert it and use mysql_insert_id() to get Title_ID.

Use those ID's to finally insert the Item (which may in fact be a duplicate, so this whole process would have been a waste..)

Does that argue against normalization for this table?

Note: The goal of Items is not to create a comprehensive database of books, so that a user would say "Show me all the books by Publisher X."  The Items table is just used to cache Items for my users' search results.

答:
The only place where i can see normalization useful in your case is if you want to store information about each author.

However -
Where normalization could help you - Saving space! Especially if there is a lot of repetition in terms of publishers, authors (that is, if you normalize individual authors table).

So if you are dealing with 10s of millions of rows, normalization will show an impact in terms of space(even performance). If you don't face that situation (which i believe should be the case) you don't need to normalize.

ps - Also think of the future... will there ever be a need? DBs are a long term infrastructure... never design them keeping the now in mind.

ContentLicense: CC BY-SA 3.0

Title: Should I normalize this table?

Body:
I have a table Items which stores fetched book data from Amazon.  This Amazon data is inserted into Items as users browse the site, so any INSERT that occurs needs to be efficient.

Here's the table:

CREATE TABLE IF NOT EXISTS `items` (
  `Item_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Item_ISBN` char(13) DEFAULT NULL,
  `Title` varchar(255) NOT NULL,
  `Edition` varchar(20) DEFAULT NULL,
  `Authors` varchar(255) DEFAULT NULL,
  `Year` char(4) DEFAULT NULL,
  `Publisher` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`Item_ID`),
  UNIQUE KEY `Item_Data` (`Item_ISBN`,`Title`,`Edition`,`Authors`,`Year`,`Publisher`),
  KEY `ISBN` (`Item_ISBN`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT AUTO_INCREMENT=1 ;

Normalizing this table would presumably mean creating tables for Titles, Authors, and Publishers.  My concern with doing this is that the insert would become too complex.. To insert a single Item, I'd have to:

Check for the Publisher in Publishers to SELECT Publisher_ID, otherwise insert it and use mysql_insert_id() to get Publisher_ID.

Check for the Authors in Authors to SELECT Authors_ID, otherwise insert it and use mysql_insert_id() to get Authors_ID.

Check for the Title in Titles to SELECT Title_ID, otherwise insert it and use mysql_insert_id() to get Title_ID.

Use those ID's to finally insert the Item (which may in fact be a duplicate, so this whole process would have been a waste..)

Does that argue against normalization for this table?

Note: The goal of Items is not to create a comprehensive database of books, so that a user would say "Show me all the books by Publisher X."  The Items table is just used to cache Items for my users' search results.


问:
Why and when should I use READ UNCOMMITTED isolation level in Spring transaction isolation level
This might be a very generic question. But, still I'm not able to find a proper solution/answer when and why I should use READ UNCOMMITTED isolation level. Most of the articles and spring doc says, the most efficient way is to use SERIALIZABLE. In that case, why spring transaction management has come up with READ UNCOMMITTED & READ COMMITTED isolation levels if they are not efficient.

I hope at least here I could get answers.

Thanks in advance

答:
I will start by saying that I do share the belief that it's rather hard to encounter cases where such levels of isolation are necessary.
Most of the time you want to start with either REPEATABLE READ or SERIALIZABLE.

One possible (albeit insane) use of READ UNCOMMITTED is for distributed systems that run different database sessions but all need to get prospect indexes for "loose" foreign keys.
Say you have two services that communicate to each other through REST and that manage transactionality by coordinating one another:

A inserts a row and makes a call to B passing the prospected key that the database generated, then waits for B

B inserts in a different table using the key provided by A to retrieve some data, then commits its own transaction and finally returns a success for use by A

A commits its own transaction

At this point rows in both tables have been inserted with correct keys. The problem is then shifted to the hopefully rare cases where something goes wrong in step (3).

I would argue among other things that the key shouldn't be generated by the database... but for existing systems you don't necessarily have the freedom to decide where keys are generated nor you have the freedom to re-implement something even when you are left flabbergasted by how bad the implementation is.

One possible use of READ COMMITTED could be a software that exposes one database session per user, while at the same time wanting the user to be able to refresh the contents and see new data generated by different transactions. One good example are database management frontends (Sql Server Management Studio, Toad, Squirrel and so on).

The following link explains a bit more in detail how these isolation levels are used in the industry. An excerpt is also copied here for easier referencing:

http://www.dbta.com/Columns/DBA-Corner/The-Danger-of-Dirty-Reads-98511.aspx

Programs that read database data can access numerous rows and are therefore susceptible to concurrency problems. To get around this issue, most major RDBMS products support read-through locks, also known as “dirty read” or “uncommitted read,” to help overcome concurrency problems. When using uncommitted reads (UR), an application program can access data that has been changed, but is not yet committed. Dirty read capability is commonly implemented using an isolation level, but the exact naming and implementation differs by DBMS vendor.

A program using dirty reads will read data without taking locks. This enables the application program to read data contained in the table as it is being manipulated. And it generally improves performance and availability of data because no locking mechanism is invoked during the process.

...

There are a few specific situations in which the dirty read capability may make sense. Consider the following cases:

Access is required to a reference, code, or look-up table that is basically static in nature. Due to the non-volatile nature of the data, a dirty read would be no different than a normal read the majority of the time. In those cases when the code data is being modified, any application reading the data would incur minimal, if any, problems.

Statistical processing must be performed on a large amount of data. For example, you may wish to determine the average age of female employees within a certain pay range. The impact of an uncommitted read on an average of multiple rows may be minimal because a single value changed may not greatly impact the result.

Dirty read can prove invaluable in a data warehousing environment. A data warehouse is used for online analytical processing and, other than periodic data propagation and/or replication, access is read-only. An uncommitted read is perfect in a read-only environment since it can cause little damage because the data is generally not changing.

In those rare cases when a table, or set of tables, is used by a single user only, UR can make a lot of sense. If only one individual can be modifying and accessing the data, locking is only adding overhead.

Finally, if the data being accessed is already inconsistent, little harm can be done using a dirty read to access the information.

The dirty read capability can provide relief to concurrency problems and deliver faster performance in very specific situations. Be certain to understand the implications of the UR isolation level and the “problems” it can cause before diving headlong into implementing it in your production applications.

```<code>
</code>```


问:
yocto poky-tiny does not create rcS symbolic links
I am trying to build poky-tiny based system but faced with problem - it does not create symbolic links to the init scripts which are placed in /etc/init.d/

poky-tiny is using busybox-inittab and accordingto the busybox recipe:
https://git.yoctoproject.org/cgit.cgi/poky/plain/meta/recipes-core/busybox/busybox.inc
It has INITSCRIPT_NAME and INITSCRIPT_PARAMS variables defined which are used in  https://git.yoctoproject.org/cgit.cgi/poky/plain/meta/classes/update-rc.d.bbclass
I expect that it should create for example link /etc/rcS.d/S10syslog -> /etc/ini.d/syslog, the init script /etc/ini.d/syslog is installed but I dont see any symbolic links and folder /etc/rcS at all.

Of cause I can create this manual but I prefer to use standard yocto way of adding init scripts to system bootup.

How to add syslog to system startup while normal poky-tiny build ?

答: poky-tiny doesn't set / removes "sysvinit" from DISTRO_FEATURES. This is required for having symlinks in rootfs / after package installation.</p>


问:
How to calculate the distance between two points, for many consequent points, within groups in python
I have the following df

```<code>       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6
</code>```

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?

答:
I dont know if there is a more efficient way to do this, but here is a solution:

```<code>import numpy as np
df['xx_diff'] = df.groupby('id')['xx'].rolling(window=2).apply(lambda x: (x[1] - x[0])**2).reset_index(drop=True)
df['yy_diff'] = df.groupby('id')['yy'].rolling(window=2).apply(lambda x: (x[1] - x[0])**2).reset_index(drop=True)
df['distance_meters'] = np.sqrt(df['xx_diff'] + df['yy_diff'])
</code>```

A more pythonic answer will be accepted :)

Body:
I have the following df

       id             xx            yy  time
0       1  553343.041098  4.178420e+06     1
1       1  553343.069815  4.178415e+06     2
2       1  553343.069815  4.178415e+06     3
3       2  553343.950755  4.178415e+06     1
4       2  553341.343829  4.178410e+06     6

The xx and yy is the position of each id at a certain point in time.

I would like to create an extra column in this df, which will be the difference in distance from one point of time to another (going from the smallest value of time to the next bigger, to the next bigger one etc), within the id group.

Is there a Pythonic way of doing so ?

Body:
I dont know if there is a more efficient way to do this, but here is a solution:

import numpy as np
df['xx_diff'] = df.groupby('id')['xx'].rolling(window=2).apply(lambda x: (x[1] - x[0])**2).reset_index(drop=True)
df['yy_diff'] = df.groupby('id')['yy'].rolling(window=2).apply(lambda x: (x[1] - x[0])**2).reset_index(drop=True)
df['distance_meters'] = np.sqrt(df['xx_diff'] + df['yy_diff'])

A more pythonic answer will be accepted :)


问:
Equal space after li of unordered list
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

```<code>ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}
</code>```

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>My abc</li>
<li>LiveColor</li>
<li>LiveFood</li>
<li>Ola</li>
<li>Uber</li>
<li>Good Chat</li>
<li>Food Panda</li>
<li>Domino'd</li>
<li>Clickfood</li>
<li>Smartyo</li>
<li>Tide</li>
<li>Webseries</li>
<li>GoPro</li>
<li>Liveshow</li>
</ol></code>```

In addition to it, the font-family is such a way that all the numbers have different spaces.

答:
You can try a table layout without the need of setting a fixed width and it will work whataver the numbers you will be using.

ol {
  counter-reset: item;
  columns: 2;
}

ol li {
  display: table-row;
}

ol li::before {
  display:table-cell;
  /*text-align:right; uncomment this if you want to align to the right  */
  content: counter(item) " ";
  counter-increment: item 99;
  padding-right: 30px;
  padding-bottom: 10px;
  /* we use background instead of border */
  background: linear-gradient(rgba(37, 194, 240, 0.8),rgba(37, 194, 240, 0.8))
     right 15px top 0/ /* right=padding right*/
     2.5px calc(100% - 10px) /* width=2.5px height=100% - padding bottom */
     no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>My abc</li>
  <li>LiveColor</li>
  <li>LiveFood</li>
  <li>Ola</li>
  <li>Uber</li>
  <li>Good Chat</li>
  <li>Food Panda</li>
  <li>Domino'd</li>
  <li>Clickfood</li>
  <li>Smartyo</li>
  <li>Tide</li>
  <li>Webseries</li>
  <li>GoPro</li>
  <li>Liveshow</li>
</ol></code>```

Title: Equal space after li of unordered list

Body:
I've removed dot(.) after the
 of
 and gave '|' after the number.

I've achieved it by using below code:

ol {
    counter-reset: item;
}
ol li::before {
    content: counter(item) " ";
    counter-increment: item;
    padding-right: 15px;
    border-right: 2.5px solid rgba(37, 194, 240, 0.8);
    margin-right: 15px;
}

But the space after the numbers are not equal.

I need uniform spacing after the numbers.
Please help me to resolve this issue.

ol{counter-reset: item;columns: 2;}
ol li{display:block;margin-bottom:10px;}
ol li::before {
 content: counter(item) " ";
 counter-increment: item;
 padding-right: 15px;
 border-right: 2.5px solid rgba(37, 194, 240, 0.8);
 margin-right: 15px;
}

My abc

LiveColor

LiveFood

Ola

Uber

Good Chat

Food Panda

Domino'd

Clickfood

Smartyo

Tide

Webseries

GoPro

Liveshow

In addition to it, the font-family is such a way that all the numbers have different spaces.

Body:
You can try a table layout without the need of setting a fixed width and it will work whataver the numbers you will be using.

ol {
  counter-reset: item;
  columns: 2;
}

ol li {
  display: table-row;
}

ol li::before {
  display:table-cell;
  /*text-align:right; uncomment this if you want to align to the right  */
  content: counter(item) " ";
  counter-increment: item 99;
  padding-right: 30px;
  padding-bottom: 10px;
  /* we use background instead of border */
  background: linear-gradient(rgba(37, 194, 240, 0.8),rgba(37, 194, 240, 0.8))
     right 15px top 0/ /* right=padding right*/
     2.5px calc(100% - 10px) /* width=2.5px height=100% - padding bottom */
     no-repeat;
}

<ol>
  <li>My abc</li>
  <li>LiveColor</li>
  <li>LiveFood</li>
  <li>Ola</li>
  <li>Uber</li>
  <li>Good Chat</li>
  <li>Food Panda</li>
  <li>Domino'd</li>
  <li>Clickfood</li>
  <li>Smartyo</li>
  <li>Tide</li>
  <li>Webseries</li>
  <li>GoPro</li>
  <li>Liveshow</li>
</ol>


问:
Firebase Storage gs url to http
I downloaded a Unity project that use images stored in Firebase server using the following link:
https://zplayer360-86b30.firebaseapp.com

Now I want to reproduce this with my own file. I created a Firebase project using Firebase Console, uploaded manually the images, but now I click "copy folder url" button and it provide me only this link:
gs://insidehome-29c9e.appspot.com/

I need a free HTTP public link.
How can I obtain this?

答:
If there are no rules on Firebase storage. You are not protected.

Then it's publicly-readable-and-guessable, One can convert gs:// URL to https:// to download any file without Google SDK's.

https://firebasestorage.googleapis.com/v0/b/[projectID].appspot.com/o/[folderName]%2F[fileName]

Google Storage URL

gs://invitepeople-5d38c.appspot.com/profilePhotos/profile_1.jpg

Https downloadable URL

https://firebasestorage.googleapis.com/v0/b/invitepeople-5d38c.appspot.com/o/profilePhotos%2Fprofile_1.jpg?alt=media

Don't guess profile_2.jpg :)

Title: Firebase Storage gs url to http


问:
How to remove the back button in the header react native
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

```<code>import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};
</code>```

How can I remove the button back?

答:
```<code>import React from 'react';
import { View, TouchableOpacity, Image, Text } from 'react-native';
import PropTypes from 'prop-types';
import style from '../../../utils/style';
import images from '../../../images/images';

class Header extends React.Component {
    constructor(props) {
        super(props);
    }

    onRightIconPress = () => {
        if (this.props.onRightIconPress) {
            this.props.onRightIconPress();
        }
    };

    render() {
        const { title, navigation, showBackIcon, showRightIcon, rightIcon } = this.props;

        return (
            <View style={style.headerrowcontainer}>
                {/* Back  Button*/}
                {showBackIcon ? (
                    <TouchableOpacity onPress={() => navigation.goBack()}>
                        <Image resizeMode="contain" source={images.iconback} style={style.backimage} />
                    </TouchableOpacity>
                ) : (
                    <View />
                )}
                {/* Title */}
                <Text style={style.titleheader}>{title}</Text>
                {/* Right Icon */}
                {showRightIcon ? (
                    <Image name={rightIcon} style={style.rightIcon} onPress={this.onRightIconPress} />
                ) : (
                    <View />
                )}
            </View>
        );
    }
}

Header.defaultProps = {
    title: '',
};
Header.propTypes = {
    title: PropTypes.string,
};
export default Header;
</code>```

Body:
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};

How can I remove the button back?


问:
python Decimal - checking if integer
I am using the Decimal library in Python, and printing out the values using
format(value, 'f'), where value is a Decimal. I get numbers in the form 10.00000, which reflects the precision on the decimal. I know that float  supports is_integer, but there seems to be a lack of a similar API for decimals. I was wondering if there was a way around this.

答:
You can call as_tuple() on a Decimal object to get the sign, the sequence of digits, and the exponent which together define the Decimal value.

If the exponent of a normalized Decimal is non-negative, then your value doesn't have a fractional component, i.e., it is an integer.  So you can check for this very easily:

def is_integer(dec):
    """True if the given Decimal value is an integer, False otherwise."""
    return dec.normalize().as_tuple()[2] >= 0
```

<p>Try it and see:</p>

<pre class="lang-python prettyprint-override"><code>from decimal import Decimal

decimals = [
    Decimal('0'),
    Decimal('0.0000'),
    Decimal('1'),
    Decimal('-1'),
    Decimal('1000000'),
    Decimal('0.1'),
    Decimal('-0.0000000009'),
    Decimal('32.4')]

for d in decimals:
    print("Is {} an integer? {}".format(d, is_integer(d)))
</code>```

Is 0 an integer? True
Is 0.0000 an integer? True
Is 1 an integer? True
Is -1 an integer? True
Is 1000000 an integer? True
Is 0.1 an integer? False
Is -9E-10 an integer? False
Is 32.4 an integer? False
```

Title: python Decimal - checking if integer

Body:
You can call as_tuple() on a Decimal object to get the sign, the sequence of digits, and the exponent which together define the Decimal value.

If the exponent of a normalized Decimal is non-negative, then your value doesn't have a fractional component, i.e., it is an integer.  So you can check for this very easily:

def is_integer(dec):
    """True if the given Decimal value is an integer, False otherwise."""
    return dec.normalize().as_tuple()[2] >= 0

Try it and see:

from decimal import Decimal

decimals = [
    Decimal('0'),
    Decimal('0.0000'),
    Decimal('1'),
    Decimal('-1'),
    Decimal('1000000'),
    Decimal('0.1'),
    Decimal('-0.0000000009'),
    Decimal('32.4')]

for d in decimals:
    print("Is {} an integer? {}".format(d, is_integer(d)))

Is 0 an integer? True
Is 0.0000 an integer? True
Is 1 an integer? True
Is -1 an integer? True
Is 1000000 an integer? True
Is 0.1 an integer? False
Is -9E-10 an integer? False
Is 32.4 an integer? False


问:
Why can this constructor declared with two parameters be called with just one?
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

```<code>Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}
</code>```

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...

答:
top and bottom are arguments with implicit values. That means you can skip them when calling the function and their implicit values will be used for calling the function.

So with the given constructor you can say Rational r; and r will have top 0 and bottom 1, or Rational r(42), in witch case top will be 42 and bottom 1, or Rational r(1,2); and top be 1 and bottom 2.

Body:
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...


问:
VueX update state from action with commit
I'm pretty new to Vuex, can someone tell me why I can't access the state from an action, modify it, and then commit it? I make a "deep" copy of the state array before I change it. What is the alternative best practice way of doing this?

This is my action:

```<code>[Action.UPDATE_CHERRYPICK_SIZE] ({ state, commit }, { recipe, size }) {
    var shoppinglist = [...state.shoppinglist]
    var cp = shoppinglist.find(v => v.recipe.id === recipe.id)
    cp.size = size
    commit(Mutation.SET_SHOPPINGLIST, shoppinglist)
}
</code>```

答:
The best practice is to write a mutation to update the state. In the SET_SHOPPINGLIST mutation, you can access the state and set values.

The only way to actually change state in a Vuex store is by committing
  a mutation. Vuex mutations are very similar to events: each mutation
  has a string type and a handler. The handler function is where we
  perform actual state modifications, and it will receive the state as
  the first argument:

Please refer to the link to see the code examples.

Body:
I'm pretty new to Vuex, can someone tell me why I can't access the state from an action, modify it, and then commit it? I make a "deep" copy of the state array before I change it. What is the alternative best practice way of doing this?

This is my action:

[Action.UPDATE_CHERRYPICK_SIZE] ({ state, commit }, { recipe, size }) {
    var shoppinglist = [...state.shoppinglist]
    var cp = shoppinglist.find(v => v.recipe.id === recipe.id)
    cp.size = size
    commit(Mutation.SET_SHOPPINGLIST, shoppinglist)
}


问:
autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete
I have an form with autocomplete disabled but it does not works and makes the autocomplete to be enabled in firefox and higher version of chrome

```<code><form method="post" autocomplete="off" action="">
    <ul class="field-set">
    <li>
        <label>Username:</label>
        <input type="text" name="acct" id="username" maxlength="100" size="20">
    </li>
    <li>
        <label>Password:</label>
        <input type="password" name="pswd" id="password" maxlength="16" size="20" >
    </li>
    <li>
        <input type="submit" class="button" value="Login" id="Login" name="Login">
    </li>
    </ul>
</form>
</code>```

When the type is changed from password to text it works in all browser.
Can anyone help to solve this issue?

答:
You should absolutely not do this

By disallowing and interfering with password completion you are making your users less safe. The correct coding for a password field should include:

```<code>autocomplete="current-password"
</code>```

Making a user type a password means that that they have to use a weak password that they can accurately type, not use a password manager and a complex, unique, and long password.
For a detailed discussion on this see: https://www.ncsc.gov.uk/blog-post/let-them-paste-passwords

Body:
I have an form with autocomplete disabled but it does not works and makes the autocomplete to be enabled in firefox and higher version of chrome

<form method="post" autocomplete="off" action="">

        Username:
        <input type="text" name="acct" id="username" maxlength="100" size="20">

        Password:
        <input type="password" name="pswd" id="password" maxlength="16" size="20" >

        <input type="submit" class="button" value="Login" id="Login" name="Login">

</form>

When the type is changed from password to text it works in all browser.
Can anyone help to solve this issue?

Body:
You should absolutely not do this

By disallowing and interfering with password completion you are making your users less safe. The correct coding for a password field should include:

autocomplete="current-password"

Making a user type a password means that that they have to use a weak password that they can accurately type, not use a password manager and a complex, unique, and long password.
For a detailed discussion on this see: https://www.ncsc.gov.uk/blog-post/let-them-paste-passwords


问:
XmlWriter - disposable
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();
```

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

答:
Ultimately, the purpose of the Dispose() in this case is to allow the XmlWriter to assume ownership of whatever it is writing to - for example, if you create an XmlWriter over a Stream, calling Dispose() on the XmlWriter can (by default) flush the xml writer and then call Dispose() on the stream. This makes it easy to pass an XmlWriter to APIs without also having to pass them a chain of other objects they need to dispose when they're done (it could, for example, be an XmlWriter talking to a CompressionStream talking to a SslStream talking to a NetworkStream, etc).

In the general case, the purpose of the Dispose() on the final end thing is to close the underlying resource (which could be a file, a socket, a pipe, etc)

In this specific case, you're talking to a StringBuilder. The Dispose() here is basically a no-op, as there is no external resource. It'll just be collected by the GC either way, at some point in the future. As such, no: there is no memory leak problem here; the GC can  see what you're doing.

So: in this case it won't make a functional difference, but: it is good practice to get into the habit of calling Dispose()  (usually via using) when that is part of the API, as in many cases this is really, really important.

Title: XmlWriter - disposable

Body:
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?


问:
QGraphics Scene Zooming in and out
Here I am again worrying about how to Zoom in and out a QGraphicsPixmapItem in a graphics scene. I looked for a direct method for this but could not find any in graphics scene or in pix map. Can someone help me with this. Do I have to extend QGraphicsPixmapItem and implement methods for this.

Thanks again for help and I really do appreciate it.

~Tharanga

答:
setScale() changes the size of the item, not the view scale of the scene. For a one item scene, it's effectively the same. But if you have more than one item in the scene, it changes the relation between items.

QGraphicsView::setTransform() should be used if you want to keep the item's relationship to the scene and other items.

Title: QGraphics Scene Zooming in and out


问:
Solr: How to update only selected field using curl or command?
I have Solr document as below

```<code>{
    "SKU":"1905/SHIRT DRESS-0",
    "DateCreated":["2019-08-18T15:21:04.090Z"],
    "DateModified":["2020-01-17T02:31:16.803Z"],
    "Name":"TIGRESS COLLECTION - SHIRT DRESS, SIZE 0 (6-8)",
    "Price":["249.00 AUD"],
    "PriceSale":["99.50 AUD"],
    "Size":["SIZE 0 (6-8)"],
    "StockLevel":["in stock"],
    "SubCategory":["KAFTAN"],
    "IsDeleted":[0],
    "ProductAddedOn":["2020-02-14T10:38:43.047Z"],
    "_version_":1658508251550973952
}
</code>```

I want to update only 1 field from this document.

I want to update IsDeleted = 1 where ProductAddedOn is less than today's date

How to do this?

Also, I tried to update name with below command

```<code>curl -X POST -H 'Content-Type: application/json' 'http://10.7.0.106:8983/solr/prashant1/update?_version_:1658508177093689344&versions=true&commit=true' --data-binary ' [{ "SKU" : "1905/SHIRT DRESS-0", "Name" : "update attempt with correct existing version" }]'
</code>```

But this command removes all other fields from the document except Name and SKU.

So I want to update only 1 field from the document and other fields should remain as it is.

答:
Solr supports simple atomic updates (also called partial updates) to single documents via field modifiers such as add and set.

Optimistic concurrency control is another method of atomically updating documents.

Modifiers
Solr supports several modifiers that atomically update values of a document.

set – set or replace a particular value, or remove the value if null is specified as the new value

Example :

```<code>curl http://10.224.143.172:8983/solr/knowledge_combined/update?commit=true --data-binary $'[{"id" : "1", "site_name"  : {"set":"Test new change"} }]'
</code>```

Body:
I have Solr document as below

{
    "SKU":"1905/SHIRT DRESS-0",
    "DateCreated":["2019-08-18T15:21:04.090Z"],
    "DateModified":["2020-01-17T02:31:16.803Z"],
    "Name":"TIGRESS COLLECTION - SHIRT DRESS, SIZE 0 (6-8)",
    "Price":["249.00 AUD"],
    "PriceSale":["99.50 AUD"],
    "Size":["SIZE 0 (6-8)"],
    "StockLevel":["in stock"],
    "SubCategory":["KAFTAN"],
    "IsDeleted":[0],
    "ProductAddedOn":["2020-02-14T10:38:43.047Z"],
    "_version_":1658508251550973952
}

I want to update only 1 field from this document.

I want to update IsDeleted = 1 where ProductAddedOn is less than today's date

How to do this?

Also, I tried to update name with below command

curl -X POST -H 'Content-Type: application/json' 'http://10.7.0.106:8983/solr/prashant1/update?_version_:1658508177093689344&versions=true&commit=true' --data-binary ' [{ "SKU" : "1905/SHIRT DRESS-0", "Name" : "update attempt with correct existing version" }]'

But this command removes all other fields from the document except Name and SKU.

So I want to update only 1 field from the document and other fields should remain as it is.

Body:
Solr supports simple atomic updates (also called partial updates) to single documents via field modifiers such as add and set.

Optimistic concurrency control is another method of atomically updating documents.

Modifiers
Solr supports several modifiers that atomically update values of a document.

set – set or replace a particular value, or remove the value if null is specified as the new value

Example :

curl http://10.224.143.172:8983/solr/knowledge_combined/update?commit=true --data-binary $'[{"id" : "1", "site_name"  : {"set":"Test new change"} }]'


问:
Gradle Kotlin Dsl Build for a Kotlin Gradle Plugin, which depends on a Groovy Class in the same Project
I have a Gradle plugin implemented with Kotlin, which is built with a gradle kotlin DSL build script. This works fine.  The build script is as follows and is located in the buildSrc directory of project:

```<code>plugins {
    groovy
    `kotlin-dsl`
}

repositories {
    mavenLocal()
    mavenCentral()
    jcenter()

}

dependencies {
    testImplementation(gradleTestKit())
    implementation(kotlin("gradle-plugin"))
    implementation ("com.bmuschko:gradle-docker-plugin:6.1.3")
}
</code>```

Now i want to call a existing Groovy Class in the same buildSrc Source Tree from the Kotlin Plugin code. This works fine in Intellij.

But when building with gradle i get a : unresolved reference Class for the Groovy Class.
Looking at the build, i see that the compileKotlin task is executed first. When i uncomment the failing reference, i see that the groovyCompile produces the correct binaries.

So i tried this:

```<code>tasks.compileKotlin {
    dependsOn(tasks.compileGroovy)
}
</code>```

Naturally that is not good enough, but i tried to get the build to compile the  Groovy code first.

I got the following error:

```<code>Circular dependency between the following tasks:
:buildSrc:compileGroovy
\--- :buildSrc:compileJava
     \--- :buildSrc:compileKotlin
          \--- :buildSrc:compileGroovy (*)
</code>```

So i tried without succeeding , to remove the compileJava task dependency from compileGroovy:

```<code>tasks.compileGroovy {
    dependsOn.remove(tasks.compileJava)
}
</code>```

Some problem as above. Basically it is unclear to me how to remove precondigured taskdependencies in gradle

What i really need is something equivalent to gradle groovy build as :

```<code>compileGroovy.dependsOn = compileGroovy.taskDependencies.values - 'compileJava'
compileKotlin.dependsOn compileGroovy
compileKotlin.classpath += files(compileGroovy.destinationDir)
classes.dependsOn compileKotlin
</code>```

How would look that like the Gradle Kotlin Dsl?
Or are there better ways to solve this Groovy / Kotlin  Code Dependency problem?

Version Info:

```<code>------------------------------------------------------------
Gradle 5.2.1
------------------------------------------------------------

Build time:   2019-02-08 19:00:10 UTC
Revision:     f02764e074c32ee8851a4e1877dd1fea8ffb7183

Kotlin DSL:   1.1.3
Kotlin:       1.3.20
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          1.8.0_232 (AdoptOpenJDK 25.232-b09)
OS:           Mac OS X 10.15.3 x86_64
</code>```

答:
I think this is equivalent, though I think it just knocks Java out of the picture, so Groovy/Kotlin/Java buildSrc code won't work...:

```<code>tasks {
    val compileJava = named("compileJava", JavaCompile::class).get()
    val compileKotlin = named("compileKotlin", KotlinCompile::class).get()
    val compileGroovy = named("compileGroovy", GroovyCompile::class).get()
    val classes by getting

    compileGroovy.dependsOn.remove("compileJava")
    compileKotlin.setDependsOn(mutableListOf(compileGroovy))
    compileKotlin.classpath += files(compileGroovy.destinationDir)
    classes.setDependsOn(mutableListOf(compileKotlin))
}
</code>```

This has been vastly improved in Gradle 6.1

https://docs.gradle.org/6.1/release-notes.html#defining-compilation-order-between-groovy,-scala-and-java

And I'm not sure the above works for test ordering if they have unexpected language dependency ordering

Body:
I have a Gradle plugin implemented with Kotlin, which is built with a gradle kotlin DSL build script. This works fine.  The build script is as follows and is located in the buildSrc directory of project:

plugins {
    groovy
    `kotlin-dsl`
}

repositories {
    mavenLocal()
    mavenCentral()
    jcenter()

}

dependencies {
    testImplementation(gradleTestKit())
    implementation(kotlin("gradle-plugin"))
    implementation ("com.bmuschko:gradle-docker-plugin:6.1.3")
}

Now i want to call a existing Groovy Class in the same buildSrc Source Tree from the Kotlin Plugin code. This works fine in Intellij.

But when building with gradle i get a : unresolved reference Class for the Groovy Class.
Looking at the build, i see that the compileKotlin task is executed first. When i uncomment the failing reference, i see that the groovyCompile produces the correct binaries.

So i tried this:

tasks.compileKotlin {
    dependsOn(tasks.compileGroovy)
}

Naturally that is not good enough, but i tried to get the build to compile the  Groovy code first.

I got the following error:

Circular dependency between the following tasks:
:buildSrc:compileGroovy
\--- :buildSrc:compileJava
     \--- :buildSrc:compileKotlin
          \--- :buildSrc:compileGroovy (*)

So i tried without succeeding , to remove the compileJava task dependency from compileGroovy:

tasks.compileGroovy {
    dependsOn.remove(tasks.compileJava)
}

Some problem as above. Basically it is unclear to me how to remove precondigured taskdependencies in gradle

What i really need is something equivalent to gradle groovy build as :

compileGroovy.dependsOn = compileGroovy.taskDependencies.values - 'compileJava'
compileKotlin.dependsOn compileGroovy
compileKotlin.classpath += files(compileGroovy.destinationDir)
classes.dependsOn compileKotlin

How would look that like the Gradle Kotlin Dsl?
Or are there better ways to solve this Groovy / Kotlin  Code Dependency problem?

Version Info:

------------------------------------------------------------
Gradle 5.2.1
------------------------------------------------------------

Build time:   2019-02-08 19:00:10 UTC
Revision:     f02764e074c32ee8851a4e1877dd1fea8ffb7183

Kotlin DSL:   1.1.3
Kotlin:       1.3.20
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          1.8.0_232 (AdoptOpenJDK 25.232-b09)
OS:           Mac OS X 10.15.3 x86_64

Body:
I think this is equivalent, though I think it just knocks Java out of the picture, so Groovy/Kotlin/Java buildSrc code won't work...:

tasks {
    val compileJava = named("compileJava", JavaCompile::class).get()
    val compileKotlin = named("compileKotlin", KotlinCompile::class).get()
    val compileGroovy = named("compileGroovy", GroovyCompile::class).get()
    val classes by getting

    compileGroovy.dependsOn.remove("compileJava")
    compileKotlin.setDependsOn(mutableListOf(compileGroovy))
    compileKotlin.classpath += files(compileGroovy.destinationDir)
    classes.setDependsOn(mutableListOf(compileKotlin))
}

This has been vastly improved in Gradle 6.1

https://docs.gradle.org/6.1/release-notes.html#defining-compilation-order-between-groovy,-scala-and-java

And I'm not sure the above works for test ordering if they have unexpected language dependency ordering


问:
golang ssh dial timeout
What is the best way to create DialTimeout on ssh connection? For example, this code always returns "Ping deadline exceed":

```<code>func (t *Tunnel) ping(sshConn *ssh.Client, addr string) (net.Conn, error) {
    var (
        conn net.Conn
        err  error
        done chan int
    )
    go func() {
        time.Sleep(getSeconds(10))
        err = errors.New("Ping deadline exceed")
        log.Printf("%v\nStatus: bad %s -> %s", err, t.serverAddr, addr)
        t.writeStatus(bad)
        done <- 1
        close(done)
    }()
    go func() {
        conn, err = sshConn.Dial("tcp", addr)
        if err != nil {
            t.writeStatus(bad)
            log.Printf("%v\nStatus: bad %s -> %s", err, t.serverAddr, addr)
        }
        done <- 1
        close(done)
    }()
    <-done
    return conn, err
}
</code>```

PS Timeout in ssh.ClientConfig is set to 5 seconds

答:
It's been two years but, may someone need the solution. So here it is.

In ssh.Dial, you can give configuration via ssh.ClientConfig,

```<code>config := &ssh.ClientConfig { Timeout: time.Minute }
client, _ := ssh.Dial("tcp", t.ServerAddr, config)
</code>```

You can find more in here:

// A Timeout of zero means no timeout.
  Timeout time.Duration

Title: golang ssh dial timeout

Body:
What is the best way to create DialTimeout on ssh connection? For example, this code always returns "Ping deadline exceed":

func (t *Tunnel) ping(sshConn *ssh.Client, addr string) (net.Conn, error) {
    var (
        conn net.Conn
        err  error
        done chan int
    )
    go func() {
        time.Sleep(getSeconds(10))
        err = errors.New("Ping deadline exceed")
        log.Printf("%v\nStatus: bad %s -> %s", err, t.serverAddr, addr)
        t.writeStatus(bad)
        done <- 1
        close(done)
    }()
    go func() {
        conn, err = sshConn.Dial("tcp", addr)
        if err != nil {
            t.writeStatus(bad)
            log.Printf("%v\nStatus: bad %s -> %s", err, t.serverAddr, addr)
        }
        done <- 1
        close(done)
    }()
    <-done
    return conn, err
}

PS Timeout in ssh.ClientConfig is set to 5 seconds

Body:
It's been two years but, may someone need the solution. So here it is.

In ssh.Dial, you can give configuration via ssh.ClientConfig,

config := &ssh.ClientConfig { Timeout: time.Minute }
client, _ := ssh.Dial("tcp", t.ServerAddr, config)

You can find more in here:

// A Timeout of zero means no timeout.
  Timeout time.Duration


问:
How to find peak value in density plot
I want to find and draw the peak values of my distribution graphs. All the methods that I have seen online are for numpy arrays. How can I find out the peak values from a data frame?

```<code>sns.set(rc={'figure.figsize':(20,8.27)})
sns.set_context("poster")
g = sns.kdeplot(df1['actual_fee'], color='b', Label='Primary', legend = True)
g = sns.kdeplot(df2['actual_fee'], color='y', Label='Secondary', legend = True)
g.set(xlim = [5,700]) plt.xlabel('Fee')  plt.ylabel('Probability Density')
plt.savefig("overall.png")
</code>```

答: You could convert your dataframe to a numpy array (Look here) and use one of the methods you have found online for numpy arrays. </p>

Title: How to find peak value in density plot

Body:
I want to find and draw the peak values of my distribution graphs. All the methods that I have seen online are for numpy arrays. How can I find out the peak values from a data frame?

sns.set(rc={'figure.figsize':(20,8.27)})
sns.set_context("poster")
g = sns.kdeplot(df1['actual_fee'], color='b', Label='Primary', legend = True)
g = sns.kdeplot(df2['actual_fee'], color='y', Label='Secondary', legend = True)
g.set(xlim = [5,700]) plt.xlabel('Fee')  plt.ylabel('Probability Density')
plt.savefig("overall.png")


问:
Can not pass Data To ContainerView
I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue
Here is without segue method

ViewController

```<code> class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }
</code>```

ContainerView

```<code>class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}
</code>```

result: favposid has Nill Value

UPDATE this is with segue method

```<code>class DetailPostBookReviewVC: UIViewController {

     var postid: String!

     @IBAction func Menubutton(_ sender: Any) {
        print(postid!)

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}
</code>```

答: I think you postid is not String type so print the null value</p>

Title: Can not pass Data To ContainerView

Body:
I have tried 2 methods to pass the data from ViewController to ContainerView, with and without segue
Here is without segue method

ViewController

 class DetailPostBookReviewVC: UIViewController {

        var postid: String!

        @IBAction func Menubutton(_ sender: Any) {

        print(postid!)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        let vc = storyboard.instantiateViewController(withIdentifier: "MenuBookReviewVC") as! MenuBookReviewVC

        vc.favpostid = postid
 }

ContainerView

class MenuBookReviewVC: UIViewController {

    var favpostid = String()
     @IBAction func Deletepost(_ sender: Any) {
        print(favpostid)
    }
}

result: favposid has Nill Value

UPDATE this is with segue method

class DetailPostBookReviewVC: UIViewController {

     var postid: String!

     @IBAction func Menubutton(_ sender: Any) {
        print(postid!)

     func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "toMenuBookReviewVC") { //"toMenuBookReviewVC" is identifier

       let vc = segue.destination as! MenuBookReviewVC
        vc.favpostid = postid!
    }
}


问:
No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate
Repository class:

```<code> package ru.spb.repository.user;

@Repository
public class AnketUserRepository implements UserRepository {

     @Autowired
     private CrudUserRepository crudRepository;

 }
</code>```

Interface:

```<code>package ru.spb.repository;

public interface UserRepository {
}
</code>```

Service:

```<code>package ru.spb.service;

@Service
public class UserService {

   private final UserRepository repository;

   @Autowired
   public UserService (UserRepository repository){
       this.repository = repository;
   }
}
</code>```

Configs:
in spring-app.xml:

```<code> <context:component-scan base-package="ru.spb.service"/>
</code>```

in spring-db.xml:

```<code> <context:component-scan base-package="ru.spb.repository.user"/>
</code>```

But I catch the following exception:

```<code> NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
</code>```

I tried to add @Repository on UserRepository-interface, but without success.

答:
You need to Annotate the Interface also</p>

```<code>package ru.spb.repository;

@Repository
public interface UserRepository {
}
</code>```

Body:
Repository class:

 package ru.spb.repository.user;

@Repository
public class AnketUserRepository implements UserRepository {

     @Autowired
     private CrudUserRepository crudRepository;

 }

Interface:

package ru.spb.repository;

public interface UserRepository {
}

Service:

package ru.spb.service;

@Service
public class UserService {

   private final UserRepository repository;

   @Autowired
   public UserService (UserRepository repository){
       this.repository = repository;
   }
}

Configs:
in spring-app.xml:

 <context:component-scan base-package="ru.spb.service"/>

in spring-db.xml:

 <context:component-scan base-package="ru.spb.repository.user"/>

But I catch the following exception:

 NoSuchBeanDefinitionException: No qualifying bean of type 'ru.spb.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

I tried to add @Repository on UserRepository-interface, but without success.

Body:
You need to Annotate the Interface also

package ru.spb.repository;

@Repository
public interface UserRepository {
}


答:
Use Series.sum with level parameter what working same like groupby with level parameter:

```<code>s = df.amount.sum(level=[0,1,2])
print (s)
date        id  type
2012-01-06  1   a        2
                b       12
2012-02-06  2   a        7
            3   b        3
2012-03-06  5   b        3
Name: amount, dtype: int64
</code>```

Title: How to turn a grouped df with hierarchical index back to a df with multi level index

Body:
My Dataframe:

df = pd.DataFrame([["2012-01-06",1,"a",2],["2012-01-06",1,"b",3],["2012-01-06",1,"b",4],["2012-01-06",1,"b",5],["2012-02-06",2,"a",3],["2012-02-06",2,"a",4],["2012-02-06",3,"b",3],["2012-03-06",5,"b",3]],columns=["date","id","type", "amount"])
df = df.set_index(["date","id","type"])
df

results in:

                    amount
date       id type
2012-01-06 1  a          2
              b          3
              b          4
              b          5
2012-02-06 2  a          3
              a          4
           3  b          3
2012-03-06 5  b          3

After I perform grouping

gr = df.groupby(df.index).agg({'amount':sum})
gr

I get:

                    amount
(2012-01-06, 1, a)       2
(2012-01-06, 1, b)      12
(2012-02-06, 2, a)       7
(2012-02-06, 3, b)       3
(2012-03-06, 5, b)       3

What do I need to turn gr into the same structure as my original df, i.e.

                    amount
date       id type
2012-01-06 1  a          2
              b         12
2012-02-06 2  a          7
           3  b          3
2012-03-06 5  b          3

Body:
Use Series.sum with level parameter what working same like groupby with level parameter:

s = df.amount.sum(level=[0,1,2])
print (s)
date        id  type
2012-01-06  1   a        2
                b       12
2012-02-06  2   a        7
            3   b        3
2012-03-06  5   b        3
Name: amount, dtype: int64


问:
Click button doing the same as the CTRL-V event
I have a function that recognizes that CTRL-V was pressed and performs the onPaste () function. I intend to do the same, but without using ctrl-v, in this case using a click on the button.

My problem is that if you do ctrl-v everything works, but if you click the button and execute the function, it doesn't work, I get the following error: Cannot read property 'getData' of undefined.

How can I solve this problem?

Thanks

DEMO

code

```<code>@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

<button (click)="onPaste($event)">Do the Same as PASTE (ctrl-v)</button>
</code>```

答:
They're not the same events: When you click a MouseEvent is emitted, when you use ctrl+v a ClipboardEvent event is emitted. MouseEvent does not have clipbordData param, thus your error.

To get access to the clipboard on click you'll need to use the Clipboard API that will ask for access permissions.

```<code>  onPaste(e: ClipboardEvent) {
    console.log(e);
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
  }

  clickPaste() {
    navigator.clipboard.readText().then(clipboard => alert(clipboard));
  }
</code>```

Stackblitz

Body:
I have a function that recognizes that CTRL-V was pressed and performs the onPaste () function. I intend to do the same, but without using ctrl-v, in this case using a click on the button.

My problem is that if you do ctrl-v everything works, but if you click the button and execute the function, it doesn't work, I get the following error: Cannot read property 'getData' of undefined.

How can I solve this problem?

Thanks

DEMO

code

@HostListener('paste', ['$event'])
  onPaste(e: ClipboardEvent) {
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
}

<button (click)="onPaste($event)">Do the Same as PASTE (ctrl-v)</button>

Body:
They're not the same events: When you click a MouseEvent is emitted, when you use ctrl+v a ClipboardEvent event is emitted. MouseEvent does not have clipbordData param, thus your error.

To get access to the clipboard on click you'll need to use the Clipboard API that will ask for access permissions.

  onPaste(e: ClipboardEvent) {
    console.log(e);
    let clipboardData = e.clipboardData || (window as any).clipboardData;
    let pastedData = clipboardData.getData('text');
    alert(pastedData)
  }

  clickPaste() {
    navigator.clipboard.readText().then(clipboard => alert(clipboard));
  }

Stackblitz


问:
Vuejs vue-easy-slider before-next question
I'm trying to stop the slider looping content using before-next.

The docs say this takes a function that returns true to allow the next slide to show.

If I pass a method in the slider html

```<code><slider :before-next="check()" :v-model="Slide">
  <slider-item v-for="(item, index) in items"></slider>
</slider>
methods: {
check: function () {
 if(this.Slide = this.items.length -1) {
 return {
   false
 } else {
   return {
     true
   }
  }
 }
}
</code>```

I get an expected function got boolean error

If a pass

```<code> methods: function () {
   this.Slide < this.items.length - 2
 }
</code>```

I get no error but also a slider that still loops

答:
After some experimenting this works.

```<code>  <slider :before-next="() => Slide < gallery.length - 1" :before-previous="() => Slide > 0"  :v-model="Slide">
    <slider-item v-for="(item, index) in items">
      <img src="gallery" />
    </slider-item>
  </slider>
</code>```

It now doesn't loop

Body:
I'm trying to stop the slider looping content using before-next.

The docs say this takes a function that returns true to allow the next slide to show.

If I pass a method in the slider html

<slider :before-next="check()" :v-model="Slide">
  <slider-item v-for="(item, index) in items"></slider>
</slider>
methods: {
check: function () {
 if(this.Slide = this.items.length -1) {
 return {
   false
 } else {
   return {
     true
   }
  }
 }
}

I get an expected function got boolean error

If a pass

 methods: function () {
   this.Slide < this.items.length - 2
 }

I get no error but also a slider that still loops

Body:
After some experimenting this works.

  <slider :before-next="() => Slide < gallery.length - 1" :before-previous="() => Slide > 0"  :v-model="Slide">
    <slider-item v-for="(item, index) in items">
      <img src="gallery" />
    </slider-item>
  </slider>

It now doesn't loop


问:
Using a filter on a time series graph with OR statement
I have a time series graph in Google Data Studio that connects to Search Console. In the graph I have a filter to only show search "queries" featuring a certain phrase. It works fine when I use one query. In the image I've blanked out the term as it's a clients brand name.

However when I add an OR element and then a second query the time series chart breaks.

When I add the second query it shows the error "Data Studio Cannot Connect to Your Data Set".

query 2:

Error message:

答:
Tried it out earlier today using a Filter, and REGEXP_MATCH with a Pipe operator

```<code>|
</code>```

For example, if you are searching for a Query that contains X or Y or Z, this does the trick:

```<code>Include Query RegExp Match .*(X|Y|Z).*
</code>```

Body:
Tried it out earlier today using a Filter, and REGEXP_MATCH with a Pipe operator

|

For example, if you are searching for a Query that contains X or Y or Z, this does the trick:

Include Query RegExp Match .*(X|Y|Z).*


问:
Creating a collapsible navigation bar in iOS
I wish to create a collapsible navigation like the one shown in the video linked below (the screen cast is for the android version of the app).
screencast

I'd like to know what classes I should use to accomplish this effect. Also note that the tagline "I am the founder" can vary in length so the expanded layout can vary in length. How would I be able to size the expanded nav bar dynamically (the only example I found had static sizes for the expanded and contracted states)?

答:
For this purpose, you can use 3rd party cocoa pod. The link is given below.
https://github.com/vicentesuarez/Swift-FlexibleHeightBar</p>


问:
Pytorch transforms.RandomRotation() does not work on Google Colab
Normally i was working on letter&digit recognition on my computer and I wanted to move my project to Colab but unfortunately there was an error (you can see the error below).
after some debugging i found which line is giving me error.

```<code>transforms.RandomRotation(degrees=(90, -90))
</code>```

below i wrote simple abstract code to show this error.This code does not work on colab but it works fine at my own computer environment.Problem might be about the different versions of pytorch library i have version 1.3.1 on my computer and colab uses version 1.4.0.

```<code>import torch
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
    transformOpt = transforms.Compose([
            transforms.RandomRotation(degrees=(90, -90)),
            transforms.ToTensor()
        ])

    train_set = datasets.MNIST(
        root='', train=True, transform=transformOpt, download=True)
    test_set = datasets.MNIST(
        root='', train=False, transform=transformOpt, download=True)

    train_loader = torch.utils.data.DataLoader(
        dataset=train_set,
        batch_size=100,
        shuffle=True)
    test_loader = torch.utils.data.DataLoader(
        dataset=test_set,
        batch_size=100,
        shuffle=False)

    images, labels = next(iter(train_loader))
    plt.imshow(images[0].view(28, 28), cmap="gray")
    plt.show()
</code>```

The full error I got when I execute this sample code above on Google Colab.

```<code>TypeError                                 Traceback (most recent call last)

<ipython-input-1-8409db422154> in <module>()
     24     shuffle=False)
     25
---> 26 images, labels = next(iter(train_loader))
     27 plt.imshow(images[0].view(28, 28), cmap="gray")
     28 plt.show()

10 frames

/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in __next__(self)
    343
    344     def __next__(self):
--> 345         data = self._next_data()
    346         self._num_yielded += 1
    347         if self._dataset_kind == _DatasetKind.Iterable and \

/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in _next_data(self)
    383     def _next_data(self):
    384         index = self._next_index()  # may raise StopIteration
--> 385         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    386         if self._pin_memory:
    387             data = _utils.pin_memory.pin_memory(data)

/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py in fetch(self, possibly_batched_index)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py in <listcomp>(.0)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

/usr/local/lib/python3.6/dist-packages/torchvision/datasets/mnist.py in __getitem__(self, index)
     95
     96         if self.transform is not None:
---> 97             img = self.transform(img)
     98
     99         if self.target_transform is not None:

/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py in __call__(self, img)
     68     def __call__(self, img):
     69         for t in self.transforms:
---> 70             img = t(img)
     71         return img
     72

/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py in __call__(self, img)    1001         angle = self.get_params(self.degrees)    1002
-> 1003         return F.rotate(img, angle, self.resample, self.expand, self.center, self.fill)    1004     1005     def
__repr__(self):

/usr/local/lib/python3.6/dist-packages/torchvision/transforms/functional.py in rotate(img, angle, resample, expand, center, fill)
    727         fill = tuple([fill] * 3)
    728
--> 729     return img.rotate(angle, resample, expand, center, fillcolor=fill)
    730
    731

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in rotate(self, angle, resample, expand, center, translate, fillcolor)    2003         w, h = nw, nh    2004
-> 2005         return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)    2006     2007     def save(self,    fp, format=None, **params):

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in transform(self, size, method, data, resample, fill, fillcolor)    2297             raise ValueError("missing method data")    2298
-> 2299         im = new(self.mode, size, fillcolor)    2300         if method == MESH:    2301             # list of quads

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in new(mode, size, color)    2503         im.palette = ImagePalette.ImagePalette()    2504         color = im.palette.getcolor(color)
-> 2505     return im._new(core.fill(mode, size, color))    2506     2507

TypeError: function takes exactly 1 argument (3 given)
</code>```

答:
You're absolutely correct. torchvision 0.5 has a bug in RandomRotation() in the fill argument probably due to incompatible Pillow version. This issue has now been fixed (PR#1760) and will be resolved in the next release.

Temporarily, you add fill=(0,) to RandomRotation transform to fix it.

```<code>transforms.RandomRotation(degrees=(90, -90), fill=(0,))
</code>```

Body:
Normally i was working on letter&digit recognition on my computer and I wanted to move my project to Colab but unfortunately there was an error (you can see the error below).
after some debugging i found which line is giving me error.

transforms.RandomRotation(degrees=(90, -90))

below i wrote simple abstract code to show this error.This code does not work on colab but it works fine at my own computer environment.Problem might be about the different versions of pytorch library i have version 1.3.1 on my computer and colab uses version 1.4.0.

import torch
import torchvision
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
    transformOpt = transforms.Compose([
            transforms.RandomRotation(degrees=(90, -90)),
            transforms.ToTensor()
        ])

    train_set = datasets.MNIST(
        root='', train=True, transform=transformOpt, download=True)
    test_set = datasets.MNIST(
        root='', train=False, transform=transformOpt, download=True)

    train_loader = torch.utils.data.DataLoader(
        dataset=train_set,
        batch_size=100,
        shuffle=True)
    test_loader = torch.utils.data.DataLoader(
        dataset=test_set,
        batch_size=100,
        shuffle=False)

    images, labels = next(iter(train_loader))
    plt.imshow(images[0].view(28, 28), cmap="gray")
    plt.show()

The full error I got when I execute this sample code above on Google Colab.

TypeError                                 Traceback (most recent call last)

<ipython-input-1-8409db422154> in <module>()
     24     shuffle=False)
     25
---> 26 images, labels = next(iter(train_loader))
     27 plt.imshow(images[0].view(28, 28), cmap="gray")
     28 plt.show()

10 frames

/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in __next__(self)
    343
    344     def __next__(self):
--> 345         data = self._next_data()
    346         self._num_yielded += 1
    347         if self._dataset_kind == _DatasetKind.Iterable and \

/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in _next_data(self)
    383     def _next_data(self):
    384         index = self._next_index()  # may raise StopIteration
--> 385         data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    386         if self._pin_memory:
    387             data = _utils.pin_memory.pin_memory(data)

/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py in fetch(self, possibly_batched_index)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py in <listcomp>(.0)
     42     def fetch(self, possibly_batched_index):
     43         if self.auto_collation:
---> 44             data = [self.dataset[idx] for idx in possibly_batched_index]
     45         else:
     46             data = self.dataset[possibly_batched_index]

/usr/local/lib/python3.6/dist-packages/torchvision/datasets/mnist.py in __getitem__(self, index)
     95
     96         if self.transform is not None:
---> 97             img = self.transform(img)
     98
     99         if self.target_transform is not None:

/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py in __call__(self, img)
     68     def __call__(self, img):
     69         for t in self.transforms:
---> 70             img = t(img)
     71         return img
     72

/usr/local/lib/python3.6/dist-packages/torchvision/transforms/transforms.py in __call__(self, img)    1001         angle = self.get_params(self.degrees)    1002
-> 1003         return F.rotate(img, angle, self.resample, self.expand, self.center, self.fill)    1004     1005     def
__repr__(self):

/usr/local/lib/python3.6/dist-packages/torchvision/transforms/functional.py in rotate(img, angle, resample, expand, center, fill)
    727         fill = tuple([fill] * 3)
    728
--> 729     return img.rotate(angle, resample, expand, center, fillcolor=fill)
    730
    731

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in rotate(self, angle, resample, expand, center, translate, fillcolor)    2003         w, h = nw, nh    2004
-> 2005         return self.transform((w, h), AFFINE, matrix, resample, fillcolor=fillcolor)    2006     2007     def save(self,    fp, format=None, **params):

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in transform(self, size, method, data, resample, fill, fillcolor)    2297             raise ValueError("missing method data")    2298
-> 2299         im = new(self.mode, size, fillcolor)    2300         if method == MESH:    2301             # list of quads

/usr/local/lib/python3.6/dist-packages/PIL/Image.py in new(mode, size, color)    2503         im.palette = ImagePalette.ImagePalette()    2504         color = im.palette.getcolor(color)
-> 2505     return im._new(core.fill(mode, size, color))    2506     2507

TypeError: function takes exactly 1 argument (3 given)

Body:
You're absolutely correct. torchvision 0.5 has a bug in RandomRotation() in the fill argument probably due to incompatible Pillow version. This issue has now been fixed (PR#1760) and will be resolved in the next release.

Temporarily, you add fill=(0,) to RandomRotation transform to fix it.

transforms.RandomRotation(degrees=(90, -90), fill=(0,))


问:
Objective-C NSString Question
I need to return a NSString from a function:

```<code>NSString myfunc ( int x )
{
    // do something with x
    NSString* myString = [NSString string];
    myString = @"MYDATA";
    // NSLog(myString);

    return *myString;
}
</code>```

So, I call this function and get *myString. Is that a pointer to the data? How can I get to the data "MYDATA"?

答:
I would rewrite this function the following way:

```<code>NSString* myfunc( int x )
{
   NSString *myString = @"MYDATA";

   // do something with myString
   return myString;
}
</code>```

In Objective-C it is more common to work with pointer to objects, not objects themselves, i.e., in your example with NSString*, not NSString.

Moreover, @"MYDATA" is already a string, so you don't need to allocate and initialize myString before the assignment.

OwnerDisplayName: Alan

ContentLicense: CC BY-SA 2.5

Title: Objective-C NSString Question

Body:
I need to return a NSString from a function:

NSString myfunc ( int x )
{
    // do something with x
    NSString* myString = [NSString string];
    myString = @"MYDATA";
    // NSLog(myString);

    return *myString;
}

So, I call this function and get *myString. Is that a pointer to the data? How can I get to the data "MYDATA"?

LastEditorDisplayName: gs

Body:
I would rewrite this function the following way:

NSString* myfunc( int x )
{
   NSString *myString = @"MYDATA";

   // do something with myString
   return myString;
}

In Objective-C it is more common to work with pointer to objects, not objects themselves, i.e., in your example with NSString*, not NSString.

Moreover, @"MYDATA" is already a string, so you don't need to allocate and initialize myString before the assignment.

OwnerDisplayName: mouviciel