问:
Issues with POST and PUT in table with comma separated numeric values
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

```<code>DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);
</code>```

It has a corresponding Model, which looks like this

```<code>public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}
</code>```

I am trying to insert numeric values into coordinate like so:

```<code>sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();
</code>```

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'
</code>```

And my backend throws the following error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}
</code>```

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

```<code>sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();
</code>```

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"
</code>```

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use
 near '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}
</code>```

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

答:
replace
"UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'
to
"UPDATE coordinate SET longitude = '55.6', latitude = '70.33', measurementId = '2' WHERE id = '2'

replace "," to "." (55,6 to 55.6)
sql not read and write number with ","

Body:
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);

It has a corresponding Model, which looks like this

public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}

I am trying to insert numeric values into coordinate like so:

sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'

And my backend throws the following error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use
 near '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.


来源: stackexchange

问:
Delay triggers wrong element to click
I have an example where button named both exclusively triggers a click of two separate elements (first and second buttons). Under normal circumstances each of the element listeners is triggered correctly, but when there is any kind of delay (for example an AJAX call) added to the listener function, the second element is triggered twice, even though there is an explicit trigger by id to call first and then second.

In the example click button named both and see that only second button is triggered twice.

$('#buttons').on('click', '.allow', function() {
  id = $(this).attr('id');
  setTimeout(function() {
    console.log(id);
  }, 2000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  first = $('#first');
  second = $('#second');

  first.addClass('allow');
  first.click();
  first.removeClass('allow');

  second.addClass('allow');
  second.click();
  second.removeClass('allow');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="buttons" style="display:inline-block;">
  <button id="first">FIRST</button>
  <button id="second">SECOND</button>
</div>
<button id="both">BOTH</button><br>
<div id="result"></div></code>```

JSFIDDLE: https://jsfiddle.net/126zkugo/8/

答:
With your current logic id is declared globally, hence it's set to first then immediately updated to second when you trigger the click on the second button. When the timeout fires 2 seconds later it prints the value of id twice, once for each button click event. At that point the value of id is now set to second.

To fix this you can declare id within the scope of the .allow click handler function:

$('#buttons').on('click', '.allow', function() {
  let id = $(this).attr('id'); // or var id, or const id...
  setTimeout(function() {
    console.log(id);
  }, 2000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  let $first = $('#first');
  let $second = $('#second');

  $first.addClass('allow');
  $first.click();
  $first.removeClass('allow');

  $second.addClass('allow');
  $second.click();
  $second.removeClass('allow');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="buttons" style="display:inline-block;">
  <button id="first">FIRST</button>
  <button id="second">SECOND</button>
</div>
<button id="both">BOTH</button><br>
<div id="result"></div></code>```

Note that the triggerBoth() function has the same problem; missing variable delcarative statements. The example fixed this.

ContentLicense: CC BY-SA 4.0

Title: Delay triggers wrong element to click

Body:
I have an example where button named both exclusively triggers a click of two separate elements (first and second buttons). Under normal circumstances each of the element listeners is triggered correctly, but when there is any kind of delay (for example an AJAX call) added to the listener function, the second element is triggered twice, even though there is an explicit trigger by id to call first and then second.

In the example click button named both and see that only second button is triggered twice.

$('#buttons').on('click', '.allow', function() {
  id = $(this).attr('id');
  setTimeout(function() {
    console.log(id);
  }, 2000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  first = $('#first');
  second = $('#second');

  first.addClass('allow');
  first.click();
  first.removeClass('allow');

  second.addClass('allow');
  second.click();
  second.removeClass('allow');
}

  <button id="first">FIRST</button>
  <button id="second">SECOND</button>

<button id="both">BOTH</button>

JSFIDDLE: https://jsfiddle.net/126zkugo/8/

Body:
With your current logic id is declared globally, hence it's set to first then immediately updated to second when you trigger the click on the second button. When the timeout fires 2 seconds later it prints the value of id twice, once for each button click event. At that point the value of id is now set to second.

To fix this you can declare id within the scope of the .allow click handler function:

$('#buttons').on('click', '.allow', function() {
  let id = $(this).attr('id'); // or var id, or const id...
  setTimeout(function() {
    console.log(id);
  }, 2000);
});

$('#both').on('click', function() {
  triggerBoth();
});

function triggerBoth() {
  let $first = $('#first');
  let $second = $('#second');

  $first.addClass('allow');
  $first.click();
  $first.removeClass('allow');

  $second.addClass('allow');
  $second.click();
  $second.removeClass('allow');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="buttons" style="display:inline-block;">
  <button id="first">FIRST</button>
  <button id="second">SECOND</button>
</div>
<button id="both">BOTH</button><br>
<div id="result"></div>

Note that the triggerBoth() function has the same problem; missing variable delcarative statements. The example fixed this.


问:
How to configure nginx.ingress.kubernetes.io/rewrite-target and spec.rules.http.paths.path to satisfy the following URI patterns
How can I configure nginx.ingress.kubernetes.io/rewrite-target and spec.rules.http.paths.path to satisfy the following URI patterns?

```<code>/aa/bb-aa/coolapp
/aa/bb-aa/coolapp/cc
</code>```

Legend:

a = Any letter between a-z. Lowercase. Exactly 2 letters - no more,
no less.

b = Any letter between a-z. Lowercase. Exactly 2 letters - no more, no less.

c = any valid URI character. Lowercase. Of variable length - think slug.

Example URI:s that should match the above pattern:

```<code>/us/en-us/coolapp
/us/en-us/coolapp/faq
/us/en-us/coolapp/privacy-policy
</code>```

Attention

Starting in Version 0.22.0, ingress definitions using the annotation nginx.ingress.kubernetes.io/rewrite-target are not backwards compatible with previous versions. In Version 0.22.0 and beyond, any substrings within the request URI that need to be passed to the rewritten path must explicitly be defined in a capture group.

Note

Captured groups are saved in numbered placeholders, chronologically, in the form $1, $2 ... $n. These placeholders can be used as parameters in the rewrite-target annotation.

References:

https://kubernetes.github.io/ingress-nginx/examples/rewrite/

https://github.com/kubernetes/ingress-nginx/pull/3174

答:
Came up with the following configuration - it is working for all of my test routes / requirements so far.

The regex is almost the same as the one posted by @Gilgames.

I based mine on the official docs rewrite example: https://kubernetes.github.io/ingress-nginx/examples/rewrite/#rewrite-target

Apart from that I took a quick course at https://www.regular-expressions.info/

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ing
  namespace: some-ns
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1/$2-$3/$5
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "INGRESSCOOKIE"
    nginx.ingress.kubernetes.io/session-cookie-path: /
    nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
    nginx.ingress.kubernetes.io/configuration-snippet: |
        if ($host = 'example.com')
        {
            rewrite ^ https://www.example.com$request_uri permanent;
        }
spec:
  tls:
  - hosts:
    - www.example.com
    - example.com
    secretName: tls-secret-test
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /([a-z]{2})/([a-z]{2})-([a-z]{2})/coolapp(/|$)(.*)
        backend:
          serviceName: coolapp-svc
          servicePort: 80
  - host: example.com
    http:
      paths:
      - path: /([a-z]{2})/([a-z]{2})-([a-z]{2})/coolapp(/|$)(.*)
        backend:
          serviceName: coolapp-svc
          servicePort: 80
</code>```

Body:
How can I configure nginx.ingress.kubernetes.io/rewrite-target and spec.rules.http.paths.path to satisfy the following URI patterns?

/aa/bb-aa/coolapp
/aa/bb-aa/coolapp/cc

Legend:

a = Any letter between a-z. Lowercase. Exactly 2 letters - no more,
no less.

b = Any letter between a-z. Lowercase. Exactly 2 letters - no more, no less.

c = any valid URI character. Lowercase. Of variable length - think slug.

Example URI:s that should match the above pattern:

/us/en-us/coolapp
/us/en-us/coolapp/faq
/us/en-us/coolapp/privacy-policy

Attention

Starting in Version 0.22.0, ingress definitions using the annotation nginx.ingress.kubernetes.io/rewrite-target are not backwards compatible with previous versions. In Version 0.22.0 and beyond, any substrings within the request URI that need to be passed to the rewritten path must explicitly be defined in a capture group.

Note

Captured groups are saved in numbered placeholders, chronologically, in the form $1, $2 ... $n. These placeholders can be used as parameters in the rewrite-target annotation.

References:

https://kubernetes.github.io/ingress-nginx/examples/rewrite/

https://github.com/kubernetes/ingress-nginx/pull/3174

Body:
Came up with the following configuration - it is working for all of my test routes / requirements so far.

The regex is almost the same as the one posted by @Gilgames.

I based mine on the official docs rewrite example: https://kubernetes.github.io/ingress-nginx/examples/rewrite/#rewrite-target

Apart from that I took a quick course at https://www.regular-expressions.info/

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ing
  namespace: some-ns
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /$1/$2-$3/$5
    certmanager.k8s.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "INGRESSCOOKIE"
    nginx.ingress.kubernetes.io/session-cookie-path: /
    nginx.ingress.kubernetes.io/from-to-www-redirect: "true"
    nginx.ingress.kubernetes.io/configuration-snippet: |
        if ($host = 'example.com')
        {
            rewrite ^ https://www.example.com$request_uri permanent;
        }
spec:
  tls:
  - hosts:
    - www.example.com
    - example.com
    secretName: tls-secret-test
  rules:
  - host: www.example.com
    http:
      paths:
      - path: /([a-z]{2})/([a-z]{2})-([a-z]{2})/coolapp(/|$)(.*)
        backend:
          serviceName: coolapp-svc
          servicePort: 80
  - host: example.com
    http:
      paths:
      - path: /([a-z]{2})/([a-z]{2})-([a-z]{2})/coolapp(/|$)(.*)
        backend:
          serviceName: coolapp-svc
          servicePort: 80


问:
How to dispatch multiple async actions that are based on the result of another async action?
Once my user login is successful and I have a Firebase User I want to check if there is already a Profile created on my server by dispatching an action which makes an async call to get a Profile.

If no Profile is returned I want to navigate the app to Profile creation page otherwise, load the Profile page.

I'm thinking dispatching the second action right in the login middleware, but it seems weird to be mixing profile and login code in the login middleware.

Is there a better way or more of a standard way to do what I'm trying to do?

I haven't tried anything, but I was thinking of dispatching the second action in the login middleware and navigating to the desired page from there.

ThunkAction<AppState> logIn = (Store<AppState> store) async {
  store.dispatch(UserLoginAction());

  try {
    final GoogleSignIn _googleSignIn = new GoogleSignIn();
    GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    GoogleSignInAuthentication googleAuth = await googleUser.authentication;

    final FirebaseAuth _auth = FirebaseAuth.instance;
    final FirebaseUser _fb = await _auth.signInWithGoogle(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    User user = new User(id: _fb.uid, name: _fb.displayName, email: _fb.email, photoUrl: _fb.photoUrl);
    store.dispatch(UserLoginSuccessAction(user: user));

    store.dispatch(GetProfileAction());

    Profile profile = await ProfileService.get().getProfile(_fb.uid);

    store.dispatch(GetProfileSuccessAction(profile: profile));

    if (profile) {
      // Navigate to Profile Page
    } else {
      // Navigate to Profile Creation Page
    }

  } catch(error) {
    store.dispatch(UserLoginFailAction(error: error));
  }
};
```

Edit:
I just thought of a way which seems better than my previous suggestion.

What if after successful login I just navigate them to the Profile page. On the init of the Profile page is where I would dispatch the action to get the Profile.  The Profile page would render differently based on whether the Profile was initialized in the AppState after the middleware and reducer have completed.

Does this seem okay to do or is there a different and better way?

答:
Dispatch GetProfileAction() on ProfilePage's onInit.

Your second suggested solution is more appropriate for these reasons:

Redux encourages a complete separation between features. Each different feature should be written as distinct as possible: you don't want to mix actions belong to login with those belong to profile. This what makes apps written in Redux architecture very maintainable, where shifting or replacing features could be done easily. Imagine if one day your app decided to remove the login feature. This code separation would significantly minimize the changes required.

Use the main trigger to dispatch an action. Before dispatching an action, you should ask yourself what is the primary reason to launch this action? In this case, would that be the successful login or the profile page initialization that primarily triggers to get the user profile? I personally think that we should always dispatch get the user's profile on the profile page load as this page is completely dependent on the data retrieved from this action. Think of this way, what happens if Profile page is initialized for some reasons other than login? Your app will end up forcing to build the Profile Page although the profile data is not available in the state.

Reusable as a Refresh action. I assume that user's profile data keeps changing and need constant update. This should be done at a minimum on reloading or reinitializing the Profile page. You don't expect users to logout, and to login back into the app to dispatch the get user's profile data, do you? Yes, you can dispatch the same action at multiple different places, but keeping it minimum would be ideal.

Body:
Once my user login is successful and I have a Firebase User I want to check if there is already a Profile created on my server by dispatching an action which makes an async call to get a Profile.

If no Profile is returned I want to navigate the app to Profile creation page otherwise, load the Profile page.

I'm thinking dispatching the second action right in the login middleware, but it seems weird to be mixing profile and login code in the login middleware.

Is there a better way or more of a standard way to do what I'm trying to do?

I haven't tried anything, but I was thinking of dispatching the second action in the login middleware and navigating to the desired page from there.

ThunkAction<AppState> logIn = (Store<AppState> store) async {
  store.dispatch(UserLoginAction());

  try {
    final GoogleSignIn _googleSignIn = new GoogleSignIn();
    GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    GoogleSignInAuthentication googleAuth = await googleUser.authentication;

    final FirebaseAuth _auth = FirebaseAuth.instance;
    final FirebaseUser _fb = await _auth.signInWithGoogle(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    User user = new User(id: _fb.uid, name: _fb.displayName, email: _fb.email, photoUrl: _fb.photoUrl);
    store.dispatch(UserLoginSuccessAction(user: user));

    store.dispatch(GetProfileAction());

    Profile profile = await ProfileService.get().getProfile(_fb.uid);

    store.dispatch(GetProfileSuccessAction(profile: profile));

    if (profile) {
      // Navigate to Profile Page
    } else {
      // Navigate to Profile Creation Page
    }

  } catch(error) {
    store.dispatch(UserLoginFailAction(error: error));
  }
};

Edit:
I just thought of a way which seems better than my previous suggestion.

What if after successful login I just navigate them to the Profile page. On the init of the Profile page is where I would dispatch the action to get the Profile.  The Profile page would render differently based on whether the Profile was initialized in the AppState after the middleware and reducer have completed.

Does this seem okay to do or is there a different and better way?


问:
how can I find last 7 days data using spring data JPA?
I want to find last 7 orders form order table, how am I supposed to do that?

Here's the order table

```<code>CREATE TABLE `orders` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `total` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `service_charge` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `vat` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `delivery_charge` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `subtotal` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `point_used` int(5) DEFAULT NULL,
  `discount_id` bigint(20) DEFAULT NULL,
  `user_id` bigint(20) NOT NULL,
  `address_id` bigint(20) NOT NULL,
  `payement_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `payment_status` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `message` mediumtext COLLATE utf8mb4_unicode_ci,
  `transaction_id` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `invoice` enum('yes','no') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
  `status` enum('pending','accepted','processed','on-way','delivered','cancelled') COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `address_id` (`address_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
</code>```

this is the service I'm using

```<code>public List<Order> getLastSevenDaysOrders(User user, String todayString, String sevenDaysBeforeString) {
        ArrayList<Order> orders = new ArrayList<>();
        orderRepository.findByUserAndCreatedAtBetween(user, todayString, sevenDaysBeforeString).forEach(orders::add);
        return orders;
    }
</code>```

This is the repository I've.

```<code>List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);
</code>```

This is my controller

```<code>@RequestMapping(value = "/order/recent", method = RequestMethod.POST)
    public JsonNode getRecentOrder(HttpServletRequest httpServletRequest, @RequestBody String userId) throws IOException {

        long startTime = System.currentTimeMillis();
        utility.printCallingUrl(httpServletRequest);

        JSONObject request = new JSONObject(userId);

        JSONArray response = new JSONArray();

        //Order order = new Order();
        List<Order> orders = new ArrayList<>();

        String auth = httpServletRequest.getHeader("Authorization");
        String authentication = utility.getBasicAuth();

        if (auth.equals(authentication)) {
            try {

                Calendar calendar = Calendar.getInstance();
                String pattern = "yyyy-MM-dd HH:mm:ss";
                DateFormat dateFormat = new SimpleDateFormat(pattern);
                Date today = calendar.getTime();
                String todayString = dateFormat.format(today);

                calendar.add(Calendar.DAY_OF_MONTH, -7);
                Date sevenDaysBefore = calendar.getTime();
                String sevenDaysBeforeString = dateFormat.format(sevenDaysBefore);

                User user = userService.getUser(request.getLong("user_id"));

                orders = orderService.getLastSevenDaysOrders(user, todayString, sevenDaysBeforeString);

                if (orders.size() > 0) {
                    for (Order order : orders) {
                        JSONObject response2 = new JSONObject();
                        response2.put("receiversName", order.getAddress().getReceiversName());
                        response2.put("address", order.getAddress().getAddress());
                        response2.put("nearbyLandmark", order.getAddress().getNearbyLandmark());
                        response2.put("receiversContact", order.getAddress().getReceiversContact());
                        response2.put("district", order.getAddress().getDistrict().getNameBn());
                        response2.put("division", order.getAddress().getDivision().getNameBn());
                        response2.put("village", order.getAddress().getVillage());
                        response2.put("name", order.getUser().getName());
                        response2.put("userId", order.getUser().getId());
                        response2.put("upazilla", order.getAddress().getUpazilla().getNameBn());
                        response2.put("vat", order.getVat());
                        response2.put("deliveryCharge", order.getDeliveryCharge());
                        response2.put("discountAmount", order.getDiscount().getAmount());
                        response2.put("discountCode", order.getDiscount().getCode());
                        response2.put("discountName", order.getDiscount().getName());
                        response2.put("discountId", order.getDiscount().getId());
                        response2.put("pointUsed", order.getPointUsed());
                        response2.put("message", order.getMessage());
                        response2.put("transactionId", order.getTransactionId());
                        response2.put("createdAt", order.getCreatedAt());
                        response2.put("total", order.getTotal());
                        response2.put("serviceCharge", order.getServiceCharge());
                        response2.put("subtotal", order.getSubtotal());
                        response2.put("orderId", order.getId());
                        response2.put("invoice", order.getInvoice());
                        response2.put("contact", order.getUser().getContact());
                        response2.put("payementType", order.getPayementType());
                        response2.put("paymentStatus", order.getPaymentStatus());
                        response2.put("status", order.getStatus());

                        response.put(response2);
                    }

                    Log log = utility.saveLog(KeyWord.GET_ORDERS, KeyWord.CMS, httpServletRequest, "200", request, new JSONObject().put("data", response), startTime);

                    if (log != null) {
                        utility.showMessage("Log inserted successfully with ID " + log.getId());
                    } else {
                        utility.showMessage("Log not inserted");
                    }
                } else {
                    response = new JSONArray();
                    Log log = utility.saveLog(KeyWord.GET_ORDERS, KeyWord.CMS, httpServletRequest, "500", request, new JSONObject().put("data", response), startTime);

                    if (log != null) {
                        utility.showMessage("Log inserted successfully with ID " + log.getId());
                    } else {
                        utility.showMessage("Log not inserted");
                    }
                }

            } catch (Exception e) {
                utility.showMessage(e.toString());
                return mapper.readTree(utility.createResponse(500, KeyWord.ERROR, e.toString()).toString());
            }

        } else {
            return mapper.readTree(utility.createResponse(500, KeyWord.ERROR, KeyWord.AUTHENTICATION).toString());
        }

        return mapper.readTree(response.toString());
    }
</code>```

Order model

```<code>@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @Expose
    private long id;
    @Column(name = "total")
    @Expose
    private String total;
    @Column(name = "service_charge")
    @Expose
    private String serviceCharge;
    @Column(name = "vat")
    @Expose
    private String vat;
    @Column(name = "delivery_charge")
    @Expose
    private String deliveryCharge;
    @Column(name = "subtotal")
    @Expose
    private String subtotal;
    @Column(name = "point_used")
    @Expose
    private int pointUsed;

    // @Column(name = "discount_id")
    // private long discountId;

    @ManyToOne
    @JoinColumn(name = "discount_id")
    @Expose
    Discount discount;
    @ManyToOne
    @Expose
    User user;
    @OneToOne
    @Expose
    Address address;

    @Column(name = "payement_type")
    @Expose
    private String payementType;
    @Column(name = "payment_status")
    @Expose
    private String paymentStatus;
    @Column(name = "message")
    @Expose
    private String message;
    @Column(name = "transaction_id")
    @Expose
    private String transactionId;
    @Column(name = "invoice")
    @Expose
    private String invoice;
    @Column(name = "status")
    @Expose
    private String status;
    @Column(name = "created_at")
    @Expose
    private String createdAt;
    @Column(name = "updated_at")
    @Expose
    private String updatedAt;

    public Order() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getVat() {
        return vat;
    }

    public void setVat(String vat) {
        this.vat = vat;
    }

    public String getServiceCharge() {
        return serviceCharge;
    }

    public void setServiceCharge(String serviceCharge) {
        this.serviceCharge = serviceCharge;
    }

    public String getDeliveryCharge() {
        return deliveryCharge;
    }

    public void setDeliveryCharge(String deliveryCharge) {
        this.deliveryCharge = deliveryCharge;
    }

    public String getSubtotal() {
        return subtotal;
    }

    public void setSubtotal(String subtotal) {
        this.subtotal = subtotal;
    }

    public int getPointUsed() {
        return pointUsed;
    }

    public void setPointUsed(int pointUsed) {
        this.pointUsed = pointUsed;
    }

    public Discount getDiscount() {
        return discount;
    }

    public void setDiscount(Discount discount) {
        this.discount = discount;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getPayementType() {
        return payementType;
    }

    public void setPayementType(String payementType) {
        this.payementType = payementType;
    }

    public String getPaymentStatus() {
        return paymentStatus;
    }

    public void setPaymentStatus(String paymentStatus) {
        this.paymentStatus = paymentStatus;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(String transactionId) {
        this.transactionId = transactionId;
    }

    public String getInvoice() {
        return invoice;
    }

    public void setInvoice(String invoice) {
        this.invoice = invoice;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

}
</code>```

Order Repository

```<code>@Repository
public interface OrderRepository extends PagingAndSortingRepository<Order, Long> {

    List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

}
</code>```

What am I doing wrong in service while writing method for repository?
I'm getting a blank array. I think I'm doing something wrong when writing findByUserAndCreatedAtBetween. would be great if could get any suggestion.

答:
Your contract

```<code>List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);
</code>```

gets date-parameters as a string. It's wrong. Spring JPA works fine with Date.

```<code>// Repository
List<Order> findByUserAndCreatedAtBetween(User user, Date today, String Date sevenDaysBefore);

// Service
public List<Order> getLastSevenDaysOrders(User user, Date today, Date sevenDaysBefore) {
        return orderRepository.findByUserAndCreatedAtBetween(user, today, sevenDaysBefore);
    }
</code>```

And then

```<code>Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();

calendar.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysBefore = calendar.getTime();

User user = userService.getUser(request.getLong("user_id"));

orders = orderService.getLastSevenDaysOrders(user, today, sevenDaysBefore);
</code>```

Body:
I want to find last 7 orders form order table, how am I supposed to do that?

Here's the order table

CREATE TABLE `orders` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `total` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `service_charge` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `vat` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `delivery_charge` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `subtotal` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `point_used` int(5) DEFAULT NULL,
  `discount_id` bigint(20) DEFAULT NULL,
  `user_id` bigint(20) NOT NULL,
  `address_id` bigint(20) NOT NULL,
  `payement_type` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `payment_status` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
  `message` mediumtext COLLATE utf8mb4_unicode_ci,
  `transaction_id` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `invoice` enum('yes','no') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'no',
  `status` enum('pending','accepted','processed','on-way','delivered','cancelled') COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `address_id` (`address_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

this is the service I'm using

public List<Order> getLastSevenDaysOrders(User user, String todayString, String sevenDaysBeforeString) {
        ArrayList<Order> orders = new ArrayList<>();
        orderRepository.findByUserAndCreatedAtBetween(user, todayString, sevenDaysBeforeString).forEach(orders::add);
        return orders;
    }

This is the repository I've.

List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

This is my controller

@RequestMapping(value = "/order/recent", method = RequestMethod.POST)
    public JsonNode getRecentOrder(HttpServletRequest httpServletRequest, @RequestBody String userId) throws IOException {

        long startTime = System.currentTimeMillis();
        utility.printCallingUrl(httpServletRequest);

        JSONObject request = new JSONObject(userId);

        JSONArray response = new JSONArray();

        //Order order = new Order();
        List<Order> orders = new ArrayList<>();

        String auth = httpServletRequest.getHeader("Authorization");
        String authentication = utility.getBasicAuth();

        if (auth.equals(authentication)) {
            try {

                Calendar calendar = Calendar.getInstance();
                String pattern = "yyyy-MM-dd HH:mm:ss";
                DateFormat dateFormat = new SimpleDateFormat(pattern);
                Date today = calendar.getTime();
                String todayString = dateFormat.format(today);

                calendar.add(Calendar.DAY_OF_MONTH, -7);
                Date sevenDaysBefore = calendar.getTime();
                String sevenDaysBeforeString = dateFormat.format(sevenDaysBefore);

                User user = userService.getUser(request.getLong("user_id"));

                orders = orderService.getLastSevenDaysOrders(user, todayString, sevenDaysBeforeString);

                if (orders.size() > 0) {
                    for (Order order : orders) {
                        JSONObject response2 = new JSONObject();
                        response2.put("receiversName", order.getAddress().getReceiversName());
                        response2.put("address", order.getAddress().getAddress());
                        response2.put("nearbyLandmark", order.getAddress().getNearbyLandmark());
                        response2.put("receiversContact", order.getAddress().getReceiversContact());
                        response2.put("district", order.getAddress().getDistrict().getNameBn());
                        response2.put("division", order.getAddress().getDivision().getNameBn());
                        response2.put("village", order.getAddress().getVillage());
                        response2.put("name", order.getUser().getName());
                        response2.put("userId", order.getUser().getId());
                        response2.put("upazilla", order.getAddress().getUpazilla().getNameBn());
                        response2.put("vat", order.getVat());
                        response2.put("deliveryCharge", order.getDeliveryCharge());
                        response2.put("discountAmount", order.getDiscount().getAmount());
                        response2.put("discountCode", order.getDiscount().getCode());
                        response2.put("discountName", order.getDiscount().getName());
                        response2.put("discountId", order.getDiscount().getId());
                        response2.put("pointUsed", order.getPointUsed());
                        response2.put("message", order.getMessage());
                        response2.put("transactionId", order.getTransactionId());
                        response2.put("createdAt", order.getCreatedAt());
                        response2.put("total", order.getTotal());
                        response2.put("serviceCharge", order.getServiceCharge());
                        response2.put("subtotal", order.getSubtotal());
                        response2.put("orderId", order.getId());
                        response2.put("invoice", order.getInvoice());
                        response2.put("contact", order.getUser().getContact());
                        response2.put("payementType", order.getPayementType());
                        response2.put("paymentStatus", order.getPaymentStatus());
                        response2.put("status", order.getStatus());

                        response.put(response2);
                    }

                    Log log = utility.saveLog(KeyWord.GET_ORDERS, KeyWord.CMS, httpServletRequest, "200", request, new JSONObject().put("data", response), startTime);

                    if (log != null) {
                        utility.showMessage("Log inserted successfully with ID " + log.getId());
                    } else {
                        utility.showMessage("Log not inserted");
                    }
                } else {
                    response = new JSONArray();
                    Log log = utility.saveLog(KeyWord.GET_ORDERS, KeyWord.CMS, httpServletRequest, "500", request, new JSONObject().put("data", response), startTime);

                    if (log != null) {
                        utility.showMessage("Log inserted successfully with ID " + log.getId());
                    } else {
                        utility.showMessage("Log not inserted");
                    }
                }

            } catch (Exception e) {
                utility.showMessage(e.toString());
                return mapper.readTree(utility.createResponse(500, KeyWord.ERROR, e.toString()).toString());
            }

        } else {
            return mapper.readTree(utility.createResponse(500, KeyWord.ERROR, KeyWord.AUTHENTICATION).toString());
        }

        return mapper.readTree(response.toString());
    }

Order model

@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    @Expose
    private long id;
    @Column(name = "total")
    @Expose
    private String total;
    @Column(name = "service_charge")
    @Expose
    private String serviceCharge;
    @Column(name = "vat")
    @Expose
    private String vat;
    @Column(name = "delivery_charge")
    @Expose
    private String deliveryCharge;
    @Column(name = "subtotal")
    @Expose
    private String subtotal;
    @Column(name = "point_used")
    @Expose
    private int pointUsed;

    // @Column(name = "discount_id")
    // private long discountId;

    @ManyToOne
    @JoinColumn(name = "discount_id")
    @Expose
    Discount discount;
    @ManyToOne
    @Expose
    User user;
    @OneToOne
    @Expose
    Address address;

    @Column(name = "payement_type")
    @Expose
    private String payementType;
    @Column(name = "payment_status")
    @Expose
    private String paymentStatus;
    @Column(name = "message")
    @Expose
    private String message;
    @Column(name = "transaction_id")
    @Expose
    private String transactionId;
    @Column(name = "invoice")
    @Expose
    private String invoice;
    @Column(name = "status")
    @Expose
    private String status;
    @Column(name = "created_at")
    @Expose
    private String createdAt;
    @Column(name = "updated_at")
    @Expose
    private String updatedAt;

    public Order() {
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getVat() {
        return vat;
    }

    public void setVat(String vat) {
        this.vat = vat;
    }

    public String getServiceCharge() {
        return serviceCharge;
    }

    public void setServiceCharge(String serviceCharge) {
        this.serviceCharge = serviceCharge;
    }

    public String getDeliveryCharge() {
        return deliveryCharge;
    }

    public void setDeliveryCharge(String deliveryCharge) {
        this.deliveryCharge = deliveryCharge;
    }

    public String getSubtotal() {
        return subtotal;
    }

    public void setSubtotal(String subtotal) {
        this.subtotal = subtotal;
    }

    public int getPointUsed() {
        return pointUsed;
    }

    public void setPointUsed(int pointUsed) {
        this.pointUsed = pointUsed;
    }

    public Discount getDiscount() {
        return discount;
    }

    public void setDiscount(Discount discount) {
        this.discount = discount;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getPayementType() {
        return payementType;
    }

    public void setPayementType(String payementType) {
        this.payementType = payementType;
    }

    public String getPaymentStatus() {
        return paymentStatus;
    }

    public void setPaymentStatus(String paymentStatus) {
        this.paymentStatus = paymentStatus;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getTransactionId() {
        return transactionId;
    }

    public void setTransactionId(String transactionId) {
        this.transactionId = transactionId;
    }

    public String getInvoice() {
        return invoice;
    }

    public void setInvoice(String invoice) {
        this.invoice = invoice;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

}

Order Repository

@Repository
public interface OrderRepository extends PagingAndSortingRepository<Order, Long> {

    List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

}

What am I doing wrong in service while writing method for repository?
I'm getting a blank array. I think I'm doing something wrong when writing findByUserAndCreatedAtBetween. would be great if could get any suggestion.

Body:
Your contract

List<Order> findByUserAndCreatedAtBetween(User user, String todayString, String sevenDaysBeforeString);

gets date-parameters as a string. It's wrong. Spring JPA works fine with Date.

// Repository
List<Order> findByUserAndCreatedAtBetween(User user, Date today, String Date sevenDaysBefore);

// Service
public List<Order> getLastSevenDaysOrders(User user, Date today, Date sevenDaysBefore) {
        return orderRepository.findByUserAndCreatedAtBetween(user, today, sevenDaysBefore);
    }

And then

Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();

calendar.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysBefore = calendar.getTime();

User user = userService.getUser(request.getLong("user_id"));

orders = orderService.getLastSevenDaysOrders(user, today, sevenDaysBefore);


问:
Unable to pull image from private GCR from Container Optimized Compute Engine
Can't get what I'm doing wrong...

Performed next steps on fresh compute engine instance based on Container Optimized OS:

docker-credential-gcr configure-docker

sudo docker run --detach --name=echo --net=esp_net gcr.io/around-dev/firebase-service-image:latest

And got the following:

Unable to find image 'gcr.io/around-dev/firebase-service-image:latest' locally
  Pulling repository gcr.io/around-dev/firebase-service-image
  docker: unauthorized: authentication required.
  See 'docker run --help'.

Then tried actually to login with docker-credential-gcr gcr-login and run, but still got the same error.
After all my .docker/.config.json looks like:

```<code> {
        "auths": {},
        "credHelpers": {
                "asia.gcr.io": "gcr",
                "eu.gcr.io": "gcr",
                "gcr.io": "gcr",
                "staging-k8s.gcr.io": "gcr",
                "us.gcr.io": "gcr"
        }
</code>```

Obviously no credentials stored. Can someone explain to me what I'm doing wrong?
Thanks in advance.

答:
Another option is to use gcloud-image in docker, which is a docker base image himself

Assuming that you have service account key file in $PWD/gcr-auth.json
Just need pass down docker-socks and your service json key in volume

```<code>docker run -exec \
-v $PWD:$PWD \
-v /var/run/docker.sock:/var/run/docker.sock \
google/cloud-sdk \
sh -c
 'gcloud auth activate-service-account --key-file=/somepath/gcr-auth.json && gcloud docker -- pull gcr.io/some-project/myimage:latest'
</code>```

After pulling done, the image is back on the host

Body:
Can't get what I'm doing wrong...

Performed next steps on fresh compute engine instance based on Container Optimized OS:

docker-credential-gcr configure-docker

sudo docker run --detach --name=echo --net=esp_net gcr.io/around-dev/firebase-service-image:latest

And got the following:

Unable to find image 'gcr.io/around-dev/firebase-service-image:latest' locally
  Pulling repository gcr.io/around-dev/firebase-service-image
  docker: unauthorized: authentication required.
  See 'docker run --help'.

Then tried actually to login with docker-credential-gcr gcr-login and run, but still got the same error.
After all my .docker/.config.json looks like:

 {
        "auths": {},
        "credHelpers": {
                "asia.gcr.io": "gcr",
                "eu.gcr.io": "gcr",
                "gcr.io": "gcr",
                "staging-k8s.gcr.io": "gcr",
                "us.gcr.io": "gcr"
        }

Obviously no credentials stored. Can someone explain to me what I'm doing wrong?
Thanks in advance.

Body:
Another option is to use gcloud-image in docker, which is a docker base image himself

Assuming that you have service account key file in $PWD/gcr-auth.json
Just need pass down docker-socks and your service json key in volume

docker run -exec \
-v $PWD:$PWD \
-v /var/run/docker.sock:/var/run/docker.sock \
google/cloud-sdk \
sh -c
 'gcloud auth activate-service-account --key-file=/somepath/gcr-auth.json && gcloud docker -- pull gcr.io/some-project/myimage:latest'

After pulling done, the image is back on the host


问:
How to implement pager change event in Tapestry's grid
How to implement pager change event in Tapestry's grid? I've read the documentation, but couldn't find the answer. So what I'm trying to do is, I want to reset the selectedItem to null everytime the selected page changing, and I noticed that actually setupRender() triggered, but I don't want to use it because it does a quite heavy process. There's no point to do this only for page changes. So is there any way to implement it specifically only for pager changes? Thank you. I'm using Tapestry 5.3.8 btw

答:
If I understand your question correctly, you should implement your own GridPager and, for example, emit the event when a page is changing (you can then handle this event within page class). For example:</p>

```<code>@Events({ PAGE_CHANGE_EVENT, InternalConstants.GRID_INPLACE_UPDATE + " (internal event)" })
public class CustomeGridPager
{

    ...
    void onAction(int newPage)
    {
       currentPage = newPage;
       this.resources.triggerEvent(PAGE_CHANGE_EVENT, new Object[] { newPage }, null);
    }
}
</code>```

Body:
If I understand your question correctly, you should implement your own GridPager and, for example, emit the event when a page is changing (you can then handle this event within page class). For example:

@Events({ PAGE_CHANGE_EVENT, InternalConstants.GRID_INPLACE_UPDATE + " (internal event)" })
public class CustomeGridPager
{

    ...
    void onAction(int newPage)
    {
       currentPage = newPage;
       this.resources.triggerEvent(PAGE_CHANGE_EVENT, new Object[] { newPage }, null);
    }
}


问:
Is it advisable to start new threads (Using programatic means) within a Kafka Streams Application?
We are developing a Kafka Streams application using the low level Processor API.

As per the documentation on Kafka, all threading and parallelism is handled by Stream threads and stream tasks. The parallelism is also scalable using partitions on the topics.

The current code looks like:

```<code>public class Processor implements Processor<K, V> {

@Override
  public void process(String key, V value) {

      //Do processing on the stream thread itself
      ...

      // Write back to output topic
      context.forward(key, updatedValue)
    });
  }
}
</code>```

However, is it recommended under any circumstances to create our own threads for doing the actual processing? This would mean utilising Kafka Streams API mainly for consuming the data from the topic and not for actual processing. The actual processing will happen in the new threads that are invoked after the initial data consumption in the Kafka stream thread.

Sample Processor in the topology:

```<code>public class Processor implements Processor<K, V> {

@Override
  public void process(String key, V value) {

  //Spawn new thread to do the processing
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
      String threadName = Thread.currentThread().getName();
      System.out.println("Hello " + threadName);

      //Do more processing
      ...

      // Write back to output topic
      context.forward(key, updatedValue)
    });
  }
}
</code>```

I have tried the most basic code for this but cannot be certain on whether it is intervening with automatic functionality provided by Kafka. For e.g. auto commit offsets, timeouts etc.

Or is it always better to stick to the default behaviour already provided by Kafka streams and utilise stream thread for quick processing of data?

答:
Kafka streams uses the kafka consumer API to consume the messages from a kafka topic. This means that even if you spawn multiple threads to consume messages, the extra threads will stay idle.

For instance, if your topic has 5 partitions, even if you spawn 10 threads to read from the topic, the kafka consumer api will only make use of 5 threads to read from the topic and the remaining threads will be idle.

You can define the number of threads to be spawned while defining your streams config.

```<code>Properties streamsConfig = new Properties();

streamsConfig.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1); //Here number of threads being spawned per kafka streams app node is 1
</code>```

So if your topic has 10 partitions and your kafka streams app is deployed on two nodes, the NUM_STREAM_THREADS_CONFIG would then be 5.

Let me know if you need more help!

Body:
We are developing a Kafka Streams application using the low level Processor API.

As per the documentation on Kafka, all threading and parallelism is handled by Stream threads and stream tasks. The parallelism is also scalable using partitions on the topics.

The current code looks like:

public class Processor implements Processor<K, V> {

@Override
  public void process(String key, V value) {

      //Do processing on the stream thread itself
      ...

      // Write back to output topic
      context.forward(key, updatedValue)
    });
  }
}

However, is it recommended under any circumstances to create our own threads for doing the actual processing? This would mean utilising Kafka Streams API mainly for consuming the data from the topic and not for actual processing. The actual processing will happen in the new threads that are invoked after the initial data consumption in the Kafka stream thread.

Sample Processor in the topology:

public class Processor implements Processor<K, V> {

@Override
  public void process(String key, V value) {

  //Spawn new thread to do the processing
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
      String threadName = Thread.currentThread().getName();
      System.out.println("Hello " + threadName);

      //Do more processing
      ...

      // Write back to output topic
      context.forward(key, updatedValue)
    });
  }
}

I have tried the most basic code for this but cannot be certain on whether it is intervening with automatic functionality provided by Kafka. For e.g. auto commit offsets, timeouts etc.

Or is it always better to stick to the default behaviour already provided by Kafka streams and utilise stream thread for quick processing of data?

Body:
Kafka streams uses the kafka consumer API to consume the messages from a kafka topic. This means that even if you spawn multiple threads to consume messages, the extra threads will stay idle.

For instance, if your topic has 5 partitions, even if you spawn 10 threads to read from the topic, the kafka consumer api will only make use of 5 threads to read from the topic and the remaining threads will be idle.

You can define the number of threads to be spawned while defining your streams config.

Properties streamsConfig = new Properties();

streamsConfig.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1); //Here number of threads being spawned per kafka streams app node is 1

So if your topic has 10 partitions and your kafka streams app is deployed on two nodes, the NUM_STREAM_THREADS_CONFIG would then be 5.

Let me know if you need more help!


问:
Inherited class object not showing base class method
I'd like to put in a base class a method in order not to repeat it in the inherited classes. There are interfaces for the base class and the inherited classes. Once I create a inherited class object I cannot use the base class method that I want to use. ¿What's wrong?

Thanks in advance.

```<code>public interface IRepository
{
    string GetError(string LogNumber);
}

public class Repository : IRepository
{
    public Repository()
    {
    }

    public string GetError(string LogNumber)
    {
        return "The error is " + LogNumber;
    }
}

public interface ICustomerRepository
{
    // READ
    List<Customer> ReadAll();

}

public class CustomerRepository : Repository, ICustomerRepository
{
    public CustomerRepository() : base()
    {
    }

    public List<Customer> ReadAll()
    {
        return fooFunction();
    }
}

CustomerRepository myRepository = new CustomerRepository()
myRepository.
</code>```

答:
Are you trying to put these statements outside the class? If yes, you should put them inside a method or preferably inside a main method.
Also, there is a semicolon missing at the end of the object initialization.

"CustomerRepository myRepository = new CustomerRepository();

myRepository."

Try correcting, you will be able to access the method from your base class.

Body:
I'd like to put in a base class a method in order not to repeat it in the inherited classes. There are interfaces for the base class and the inherited classes. Once I create a inherited class object I cannot use the base class method that I want to use. ¿What's wrong?

Thanks in advance.

public interface IRepository
{
    string GetError(string LogNumber);
}

public class Repository : IRepository
{
    public Repository()
    {
    }

    public string GetError(string LogNumber)
    {
        return "The error is " + LogNumber;
    }
}

public interface ICustomerRepository
{
    // READ
    List<Customer> ReadAll();

}

public class CustomerRepository : Repository, ICustomerRepository
{
    public CustomerRepository() : base()
    {
    }

    public List<Customer> ReadAll()
    {
        return fooFunction();
    }
}

CustomerRepository myRepository = new CustomerRepository()
myRepository.


问:
How to make a UITabBar with multi-line itemTitle in swift 4
currently I'm working in an iOS project in swift. In my project, I have UITabBarController, which contains five items. Now it is working fine no issue. But now I need to change the title to a bigger title. But after changing the title, the item title is not showing fully or in two lines. What I need is to list the title name in two lines. Is there any way to do that? I checked all the codes. Please help me.</p>

答:
As per my knowledge you can't achieve this with default tabor item. You must add custom view and design tabs by your own which explained below.

Write a method like addCustomTabbar() in your UITabBarController subclassed class and call addCustomTabbar() method in awakeFromNib().   - Hide default tab bar with self.tabBar.isHidden = true. This hides your default tab bar.

Create your own UIView with frame is equal to tab bar frame like let tabbarView = UIView(frame: tabBar.frame).

From here onwards create a UIButton object with respective frame and add to your custom view i.e tabbarView like below.

let btn = UIButton(frame: CGRect(x: 0, y: 0, width: individualWidth, height: Int(custom_tab_view.frame.height)))

As every UIButton had titleLabel , you can set number of lines property of the titleLabel is zero and text wrap is wordWrap. In this way, you can achieve title with multiple lines.


问:
How do I find the width & height of a terminal window?
As a simple example, I want to write a CLI script which can print = across the entire width of the terminal window.

```<code>#!/usr/bin/env php
<?php
echo str_repeat('=', ???);
</code>```

or

```<code>#!/usr/bin/env python
print '=' * ???
</code>```

or

```<code>#!/usr/bin/env bash
x=0
while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo
</code>```

答: In bash, the $LINES and $COLUMNS environmental variables should be able to do the trick. The will be set automatically upon any change in the terminal size. (i.e. the SIGWINCH signal)

OwnerDisplayName: Peter

Body:
As a simple example, I want to write a CLI script which can print = across the entire width of the terminal window.

#!/usr/bin/env php
<?php
echo str_repeat('=', ???);

or

#!/usr/bin/env python
print '=' * ???

or

#!/usr/bin/env bash
x=0
while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo

OwnerDisplayName: David Dean

ContentLicense: CC BY-SA 2.5


问:
HTML Input Time, where min is pm (late) and max is am (early)
I have an input box, with a type of "time". I want to have a late time (23:00pm) as a min value, and an early time (6:00am) as a max value - creating a range of 23pm - 6am. (ie. 11pm, 12pm, 1am, 2am, 3am, 4am, 5am, 6am).

I've tried using Javascript, although I want to use it as a last resort. I don't want the native component to show up with values that I don't want the user to select (for example, on mobile devices).

Setting the 'min' value to 00:00:00 and the 'max' value to "06:00:00" works as intended. It's when the min value is before midnight it becomes an issue.

I'd expect the min and max values to create a range, but that doesn't work as expected.

答:
As stated in MDN docs:

Unlike many data types, time values have a periodic domain, meaning
  that the values reach the highest possible value, then wrap back
  around to the beginning again. For example, specifying a min of 14:00
  and a max of 2:00 means that the permitted time values start at 2:00
  PM, run through midnight to the next day, ending at 2:00 AM.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#max

That said, it seems like this is not working properly in Chrome 76.0,
after a simple test with a min value greater than the max, all times fail the validation and the form just don't work.

I suggest https://timepicker.co/ since it will work cross browser.

input:invalid+.validity:after {
  content: '✖';
}

input:valid+.validity:after {
  content: '✓';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <label for="time1">3:00 to 6:00: </label>
  <input type="time" min="3:00" max="6:00" name="time1" required>
  <span class="validity"></span>
  <hr>
  <label for="time2">23:00 to 6:00: </label>
  <input type="time" min="23:00" max="6:00" name="time2" required>
  <span class="validity"></span>
</form></code>```

Body:
As stated in MDN docs:

Unlike many data types, time values have a periodic domain, meaning
  that the values reach the highest possible value, then wrap back
  around to the beginning again. For example, specifying a min of 14:00
  and a max of 2:00 means that the permitted time values start at 2:00
  PM, run through midnight to the next day, ending at 2:00 AM.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time#max

That said, it seems like this is not working properly in Chrome 76.0,
after a simple test with a min value greater than the max, all times fail the validation and the form just don't work.

I suggest https://timepicker.co/ since it will work cross browser.

input:invalid+.validity:after {
  content: '✖';
}

input:valid+.validity:after {
  content: '✓';
}

<form>
  <label for="time1">3:00 to 6:00: </label>
  <input type="time" min="3:00" max="6:00" name="time1" required>
  <span class="validity"></span>
  <hr>
  <label for="time2">23:00 to 6:00: </label>
  <input type="time" min="23:00" max="6:00" name="time2" required>
  <span class="validity"></span>
</form>


问:
Primes in Haskell
I'm learning Haskell, and I've tried to generate an infinite list of primes, but I can't understand what my function is doing wrong.

The function:

```<code>prime = 2:3:filter (\x -> all (\y -> (mod x y) > 0) (init prime)) [5..]
</code>```

I think it's the init prime, but the strange thing is that even if I set an upper bound to the range (5..10 for example), the function loops forever and never gets any result for prime !! 2

Can you please tell me what I'm doing wrong?

答:
If the code in the other answer is restructured under the identity

```<code>[take n primes | n <- [0..]]  ==  inits primes
</code>```

eventually we get

```<code>import Data.List
              -- [ ([], 2), ([2], 3), ([2,3], 5), ... ]
primes = 2 : [ c | (ps, p) <- zip (inits primes) primes,
                   c <- take 1 [c | c <- [p+1..],
                                    and [mod c p > 0 | p <- ps]]]
</code>```

Further improving it algorithmically, it becomes

```<code>primes = 2 : [ c | (ps, r:q:_) <- zip (inits primes)                  -- [] [3,4,...]
                                      (tails $ 3 : map (^2) primes),  -- [2] [4,9,...]
                   c <- [r..q-1], and [mod c p > 0 | p <- ps]]        -- [2,3] [9,25,...]
</code>```

Title: Primes in Haskell

Body:
I'm learning Haskell, and I've tried to generate an infinite list of primes, but I can't understand what my function is doing wrong.

The function:

prime = 2:3:filter (\x -> all (\y -> (mod x y) > 0) (init prime)) [5..]

I think it's the init prime, but the strange thing is that even if I set an upper bound to the range (5..10 for example), the function loops forever and never gets any result for prime !! 2

Can you please tell me what I'm doing wrong?

Body:
If the code in the other answer is restructured under the identity

[take n primes | n <- [0..]]  ==  inits primes

eventually we get

import Data.List
              -- [ ([], 2), ([2], 3), ([2,3], 5), ... ]
primes = 2 : [ c | (ps, p) <- zip (inits primes) primes,
                   c <- take 1 [c | c <- [p+1..],
                                    and [mod c p > 0 | p <- ps]]]

Further improving it algorithmically, it becomes

primes = 2 : [ c | (ps, r:q:_) <- zip (inits primes)                  -- [] [3,4,...]
                                      (tails $ 3 : map (^2) primes),  -- [2] [4,9,...]
                   c <- [r..q-1], and [mod c p > 0 | p <- ps]]        -- [2,3] [9,25,...]


问:
How does docker container access Internet
I have docker installed (Docker for Mac).
I start a new container with

```<code>docker run -it ubuntu
</code>```

I can see that my newly created container has internet access by simply invoking

```<code>ping google.com
</code>```

I see:

```<code>root@b06e1a46cc40:/# ping google.com
PING google.com (216.58.209.14) 56(84) bytes of data.
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=1 ttl=37 time=63.0 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=2 ttl=37 time=63.7 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=3 ttl=37 time=64.8 ms
</code>```

Next, I checked the networks that my container is connected to:

```<code>root@b06e1a46cc40:/# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1
    link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1
    link/tunnel6 :: brd ::
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
root@b06e1a46cc40:/#
</code>```

As I understand, eth0 is used to access internet - it is a network 172.17.0.0/16.

When I look at network list of my host, I'm not connected to this network.

How does my container access internet then?

As I understand it, my container should access internet through my host, because, after all, my host is connected to internet, so this is the only way to access.

答:
Use host network at startup
docker run -it --network host ubuntu

Body:
I have docker installed (Docker for Mac).
I start a new container with

docker run -it ubuntu

I can see that my newly created container has internet access by simply invoking

ping google.com

I see:

root@b06e1a46cc40:/# ping google.com
PING google.com (216.58.209.14) 56(84) bytes of data.
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=1 ttl=37 time=63.0 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=2 ttl=37 time=63.7 ms
64 bytes from sof01s12-in-f14.1e100.net (216.58.209.14): icmp_seq=3 ttl=37 time=64.8 ms

Next, I checked the networks that my container is connected to:

root@b06e1a46cc40:/# ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1
    link/ipip 0.0.0.0 brd 0.0.0.0
3: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1
    link/tunnel6 :: brd ::
6: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0
       valid_lft forever preferred_lft forever
root@b06e1a46cc40:/#

As I understand, eth0 is used to access internet - it is a network 172.17.0.0/16.

When I look at network list of my host, I'm not connected to this network.

How does my container access internet then?

As I understand it, my container should access internet through my host, because, after all, my host is connected to internet, so this is the only way to access.


问:
Using secret from Azure KeyVault in Azure ARM Template
I have a template of container instance with container in azurecr.io
Is it possible to use an Azure Key Vault secret in an ARM Template?
The following examples do not work:

```<code>            "imageRegistryCredentials": [
                {
                    "server": "***.azurecr.io",
                    "username": "***",
                    "password": {
                        "reference": {
                            "keyVault": {
                                "id": "[resourceId(parameters('vaultSubscription'), parameters('vaultResourceGroupName'), 'Microsoft.KeyVault/vaults', parameters('vaultName'))]"
                            },
                            "secretName": "[parameters('secretName')]"
                        }
                    }
                }
            ],
</code>```

I have tried it with:

```<code>"resources": [
        {
            ...
            "properties": {
                "parameters":{
                    "secretPassword": {
                        "type": "securestring",
                        "reference": {
                            "keyVault": {
                                "id": "[resourceId(parameters('vaultSubscription'), parameters('vaultResourceGroupName'), 'Microsoft.KeyVault/vaults', parameters('vaultName'))]"
                            },
                            "secretName": "[parameters('secretName')]"
                        }
                    }
                },
</code>```

And:

```<code>        "imageRegistryCredentials": [
            {
                "server": "**.azurecr.io",
                "username": "**",
                "password": "[parameters('secretPassword')]"
            }
        ],
</code>```

Result:

```<code>  "error": {
    "code": "InvalidTemplate",
    "message": "Unable to process template language expressions for resource '/subscriptions/**/resourceGroups/**/providers/Microsoft.ContainerInstance/containerGroups/**' at line '28' and co
lumn '9'. 'The template parameter 'secretPassword' is not found. Please see https://aka.ms/arm-template/#parameters for
 usage details.'"
  }
}'
</code>```

答:
So, I've created a workaround, which enables you to relatively simply use any keyvault secret in your template by using a publicly available template on github. See https://github.com/bobvandevijver/azure-arm-keyvault-secret-output for the example.

It would obviously be better if Microsoft just fixed this implementation, but it's something!

Body:
I have a template of container instance with container in azurecr.io
Is it possible to use an Azure Key Vault secret in an ARM Template?
The following examples do not work:

            "imageRegistryCredentials": [
                {
                    "server": "***.azurecr.io",
                    "username": "***",
                    "password": {
                        "reference": {
                            "keyVault": {
                                "id": "[resourceId(parameters('vaultSubscription'), parameters('vaultResourceGroupName'), 'Microsoft.KeyVault/vaults', parameters('vaultName'))]"
                            },
                            "secretName": "[parameters('secretName')]"
                        }
                    }
                }
            ],

I have tried it with:

"resources": [
        {
            ...
            "properties": {
                "parameters":{
                    "secretPassword": {
                        "type": "securestring",
                        "reference": {
                            "keyVault": {
                                "id": "[resourceId(parameters('vaultSubscription'), parameters('vaultResourceGroupName'), 'Microsoft.KeyVault/vaults', parameters('vaultName'))]"
                            },
                            "secretName": "[parameters('secretName')]"
                        }
                    }
                },

And:

        "imageRegistryCredentials": [
            {
                "server": "**.azurecr.io",
                "username": "**",
                "password": "[parameters('secretPassword')]"
            }
        ],

Result:

  "error": {
    "code": "InvalidTemplate",
    "message": "Unable to process template language expressions for resource '/subscriptions/**/resourceGroups/**/providers/Microsoft.ContainerInstance/containerGroups/**' at line '28' and co
lumn '9'. 'The template parameter 'secretPassword' is not found. Please see https://aka.ms/arm-template/#parameters for
 usage details.'"
  }
}'


问:
Ignore scrollbar on mousedown event
I'm trying to build a code which will exit a modal when user clicks outside of the modal. The problem is when i click on vertical scrollbar it triggers the event for some reason.
Here's my code

```<code>  $(document).mouseup(function(e) {
      var popup = $(".ui-dialog");

      if (!$('.ui-dialog').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
        popup.fadeOut(100);
        $('#remove').fadeOut(100, function() {
          $('#remove').remove();
        });
        $('#csbox').fadeOut(100, function() {
          $('#csbox').remove;
        });
        $('body').removeClass('custombox-lock');
      }
    });
</code>```

Is there a way to not trigger the event when scrollbar is clicked or being used?

Here's the HTML, the entire content is stripped because its too long. I am on drupal 8

```<code><div id="remove" class="js-modal-window custombox-content custombox-x-center custombox-y-center custombox-fadein custombox-open">
<div id="remove" class="js-modal-window custombox-content custombox-x-center custombox-y-center custombox-fadein custombox-open">
<div style="position: relative; height: auto; width: 700px; display: block; z-index: 601;" tabindex="-1" role="dialog" class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front js-signup-modal u-modal-window p-5" aria-describedby="drupal-modal" aria-labelledby="ui-id-2">
<div class="ui-dialog-titlebar ui-corner-all ui-widget-header ui-helper-clearfix">
<span id="ui-id-2" class="ui-dialog-title">Modal Title</span>
<button type="button" class="ui-dialog-titlebar-close btn btn-sm btn-icon btn-text-secondary u-modal-window__close" id="close">
<span class="fas fa-times"></span>
</button></div>
<div id="drupal-modal" class="ui-front ui-dialog-content ui-widget-content" style="width: auto; min-height: 50px; max-height: 249px; height: auto;"></article></div></div></div></div>
<div class="custombox-overlay custombox-fadein custombox-open" style="z-index: 600;" id="csbox"></div>
</code>```

答:
You may probably use this hack.

You could try hijacking the mousedown and mouseup events and avoiding them when click on a scrollbar with your custom powered function.

```<code>$.fn.mousedown = function(data, fn) {
    if ( fn == null ) {
        fn = data;
        data = null;
    }
    var o = fn;
    fn = function(e){
        if(!inScrollRange(e)) {
            return o.apply(this, arguments);
        }
        return;
    };
    if ( arguments.length > 0 ) {
        return this.bind( "mousedown", data, fn );
    }
    return this.trigger( "mousedown" );
};
</code>```

And the inverse for mousedownScroll and mouseupScroll events.

```<code>$.fn.mousedownScroll = function(data, fn) {
    if ( fn == null ) {
        fn = data;
        data = null;
    }
    var o = fn;
    fn = function(e){
        if(inScrollRange(e)) {
            e.type = "mousedownscroll";
            return o.apply(this, arguments);
        }
        return;
    };
    if ( arguments.length > 0 ) {
        return this.bind( "mousedown", data, fn );
    }
    return this.trigger( "mousedown" );
};
</code>```

By the way, I think the scrollbar width is an OS setting.

Title: Ignore scrollbar on mousedown event

Body:
I'm trying to build a code which will exit a modal when user clicks outside of the modal. The problem is when i click on vertical scrollbar it triggers the event for some reason.
Here's my code

  $(document).mouseup(function(e) {
      var popup = $(".ui-dialog");

      if (!$('.ui-dialog').is(e.target) && !popup.is(e.target) && popup.has(e.target).length == 0) {
        popup.fadeOut(100);
        $('#remove').fadeOut(100, function() {
          $('#remove').remove();
        });
        $('#csbox').fadeOut(100, function() {
          $('#csbox').remove;
        });
        $('body').removeClass('custombox-lock');
      }
    });

Is there a way to not trigger the event when scrollbar is clicked or being used?

Here's the HTML, the entire content is stripped because its too long. I am on drupal 8

Modal Title
<button type="button" class="ui-dialog-titlebar-close btn btn-sm btn-icon btn-text-secondary u-modal-window__close" id="close">

</button>

Body:
You may probably use this hack.

You could try hijacking the mousedown and mouseup events and avoiding them when click on a scrollbar with your custom powered function.

$.fn.mousedown = function(data, fn) {
    if ( fn == null ) {
        fn = data;
        data = null;
    }
    var o = fn;
    fn = function(e){
        if(!inScrollRange(e)) {
            return o.apply(this, arguments);
        }
        return;
    };
    if ( arguments.length > 0 ) {
        return this.bind( "mousedown", data, fn );
    }
    return this.trigger( "mousedown" );
};

And the inverse for mousedownScroll and mouseupScroll events.

$.fn.mousedownScroll = function(data, fn) {
    if ( fn == null ) {
        fn = data;
        data = null;
    }
    var o = fn;
    fn = function(e){
        if(inScrollRange(e)) {
            e.type = "mousedownscroll";
            return o.apply(this, arguments);
        }
        return;
    };
    if ( arguments.length > 0 ) {
        return this.bind( "mousedown", data, fn );
    }
    return this.trigger( "mousedown" );
};

By the way, I think the scrollbar width is an OS setting.


问:
Jupyter Notebook not saving: '_xsrf' argument missing from post
I've been running a script on jupyter notebooks for about 26 hour; I haven't really been using my computer for anything else, but it needs to run this program that will take ~30 hours to complete. At about 21 hours in, it stopped saving and my terminal had this:

```<code>403 PUT /api/contents/[file.ipynb] (::1): '_xsrf' argument missing from POST
</code>```

where [file.ipynb] is the location of my jupyter notebook. It also says:

```<code>'_xsrf' argument missing from post
</code>```

in the top right part of the notebook again. The program is still running and I don't want to restart jupyter notebook and have to run the program again, as I have a deadline, is there anything else I can do?

I'm using google chrome, but I don't have the LastPass extension or any '%' characters in my code, as another post suggested.

Thanks for any help!

答:
When I click 'save' button, it has this error. Based on the answers in this post and other websites, I just found the solution.
My jupyter notebook is installed from pip. So I access it by typing 'jupyter notebook' in the windows command line.

(1) open a new command window, then open a new jupyter notebook.
try to save again in the old notebook, this time ,the error is 'fail: forbidden'

(2) Then in the old notebook, click 'download as', it will pop out a new windows ask you the token.

(3) open another command window, then open another jupyter notebook, type 'jupyter notebook list'
copy the code after 'token=' and before ::  to the box you just saw. You can save this time. If it fails, you can try another token in the list

Body:
I've been running a script on jupyter notebooks for about 26 hour; I haven't really been using my computer for anything else, but it needs to run this program that will take ~30 hours to complete. At about 21 hours in, it stopped saving and my terminal had this:

403 PUT /api/contents/[file.ipynb] (::1): '_xsrf' argument missing from POST

where [file.ipynb] is the location of my jupyter notebook. It also says:

'_xsrf' argument missing from post

in the top right part of the notebook again. The program is still running and I don't want to restart jupyter notebook and have to run the program again, as I have a deadline, is there anything else I can do?

I'm using google chrome, but I don't have the LastPass extension or any '%' characters in my code, as another post suggested.

Thanks for any help!


问:
nested_form and Single table inheritance
I'm having trouble using it with STI and wondered if you can give me some pointers.
I want to add attachments to discussion as well.
I tried several attempts to make it work but always got exceptions.

do i need to add accepts_nested_attributes_for in discussion.rb ?
do i need to add a column in the attachments table ?

```<code>class Post < ActiveRecord::Base
  has_many :attachments, :dependent => :destroy
  accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:url].blank? }, :allow_destroy => true
end

class Discussion  < Post
end

class Attachment < ActiveRecord::Base
belongs_to :post
end
</code>```

答:
do i need to add accepts_nested_attributes_for in discussion.rb ?

If there is now any differences with parent class - No

do i need to add a column in the attachments table ?

Only post_id or any other key

ContentLicense: CC BY-SA 3.0

Body:
I'm having trouble using it with STI and wondered if you can give me some pointers.
I want to add attachments to discussion as well.
I tried several attempts to make it work but always got exceptions.

do i need to add accepts_nested_attributes_for in discussion.rb ?
do i need to add a column in the attachments table ?

class Post < ActiveRecord::Base
  has_many :attachments, :dependent => :destroy
  accepts_nested_attributes_for :attachments, :reject_if => lambda { |a| a[:url].blank? }, :allow_destroy => true
end

class Discussion  < Post
end

class Attachment < ActiveRecord::Base
belongs_to :post
end


问:
How do I populate entry fields with previously entered data currently saved in the database?
I'm creating an Android app which will allow the user to create CVs. I want the user to add all the details initially, but then have the option to return and edit if necessary. I want to repopulate the entry fields with the user's details which were entered previously (and saved to the database using SQLite).

I have a SAVE button which sends the data to the DB however I wasn't sure whether to add a LOAD button or whether the data will load automatically when the page is opened. Please advise.

I haven't pasted any code as I'm not sure if it will benefit my question right now.

ListView seems to be the most common method for displaying data however this doesn't help me as I require population of previously entered data to the original entry field.

答:
There shouldn't be any load button in this case. The data should be fetched and populated automatically when the user navigates to the fragment or activity.

ListView can be used to display previously populated data.


问:
How to toggle mat-sidenav in another component?
I want to toggle side-nav(in the drawer component)by clicking menu icon (in the header component). I've tried using service; but the service state didn't share between these two components.

The demo is here https://stackblitz.com/edit/angular-11pdkj

答:
You should use the @Input and @Output decorators and the EventEmitter to send event from one to another component.
I've fixed your code,
Please check it out:
stackblitz


问:
Do we need to pass only int values for the 'INT' type data in MYSQL select query?
Actually following values are not there in the 'status' column(i.e 1ooo,1ee)" but result is comming. status column is containing only one record that is with the 1.

```<code>QRY-1:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status=1;

QRY-2:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1";

QRY-3:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ooo";

QRY-4:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ee";
</code>```

QRY-1:OK

For the above QRY-2,QRY-3,QRY-4 also I'm getting same result?Why?

答: This occurs because the implicit conversion that happens when an operator is used with operands of different types. In your case, comparing an int with a string. You can see more Type Conversion in Expression Evaluation.</p>

Body:
Actually following values are not there in the 'status' column(i.e 1ooo,1ee)" but result is comming. status column is containing only one record that is with the 1.

QRY-1:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status=1;

QRY-2:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1";

QRY-3:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ooo";

QRY-4:select * from User_Table where key ='xxxxxxxxxxxxxxxxxxxxxxxxx' and status="1ee";

QRY-1:OK

For the above QRY-2,QRY-3,QRY-4 also I'm getting same result?Why?


问:
How do I replace all occurrences of a string in JavaScript?
Given a string:

```<code>s = "Test abc test test abc test test test abc test test abc";
</code>```

This seems to only remove the first occurrence of abc in the string above:

```<code>s = s.replace('abc', '');
</code>```

How do I replace all occurrences of it?

答:
For replacing a single time, use:

```<code>var res = str.replace('abc', "");
</code>```

For replacing multiple times, use:

```<code>var res = str.replace(/abc/g, "");
</code>```

Body:
Given a string:

s = "Test abc test test abc test test test abc test test abc";

This seems to only remove the first occurrence of abc in the string above:

s = s.replace('abc', '');

How do I replace all occurrences of it?

Body:
For replacing a single time, use:

var res = str.replace('abc', "");

For replacing multiple times, use:

var res = str.replace(/abc/g, "");