问:
How to develop a client web application that execute Rest Ws Spring
In my application server Wildfly I have a war which contains code of a RESTful Web Service done with Apache CXF and Spring Framework, this war call an external ws.

With Postman I call API inside my war with success :-) , I ask what technology is better to develope my new client web application to emulate Postman.

Thanks in advance

答:
I prefer Spring RestTemplate. You can inject the RestTemplate in your beans and send GET and POST easily:</p>

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

public class Test {

   @Autowired
   RestTemplate restTemplate;

   public ResponseEntity<Response> test(String url, Request request){
        return restTemplate.postForEntity(url, request, Response.class);
   }
}
</code>```

Body:
I prefer Spring RestTemplate. You can inject the RestTemplate in your beans and send GET and POST easily:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

public class Test {

   @Autowired
   RestTemplate restTemplate;

   public ResponseEntity<Response> test(String url, Request request){
        return restTemplate.postForEntity(url, request, Response.class);
   }
}


来源: stackexchange

问:
extract 1st line from a text with special pattern using regexp
I have a string

```<code>set text {tools show stats
Resource Manager info at 023 h 06/01/20 09:14:16.105:

Hardware Resource Usage #1, abc iom-32-100g, Pipe #0:
                                 |   Total   | Allocated |    Free
  -------------------------------+-----------+-----------+------------
            stat vale abc/ghj(0) |        256|          0|        256
            stat vale abc/ghj(1) |        256|          0|        256

                   new Statistic |    Count
---------------------------------+-------------
                           first |         0
                          seconds|         0

                      third info |    Count
                           fourth|         0
                           fifth |       125

     Forwarding Table Statistics |   Used /  Free  /  Max  /  Reject
---------------------------------+-----------------------------------
              third stat Entries |      2 /  36856 /  36864
                      Important  |      1 /  13133 /  13136 / 0
                fifth entry < 56 |      1 /   5743 /   5744 / 0
                sixth entry > 5 |      0 /    112 /    112 / 0

Service manager resources
-------------------------
Total count:           2/  3072
Total info:            2/   401

ABC Group Statistics |   Used /  Free  / Max
---------------------------------+-----------------------
              Entries |      0 /    256 / 256
}
</code>```

I have to extract

```<code>1. Important  |      1 /  13133 /  13136 / 0
2. fifth entry < 56 |      1 /   5743 /   5744 / 0
</code>```

both can be done separetly
I'm using the following regex in tcl to extract the same

```<code>1. regexp -nocase -line -- {^Important.*} $text match
2. regexp -nocase -line -- {^fifth entry \< 56.*} $text match
</code>```

its not working, can someone help here ?

答:
regexp -nocase -line -- {^Important.*} $text match

You have spaces before Important, so you should add them to your expression like thus:

```<code>regexp -nocase -line -- {^ *Important.*} $text match
</code>```

regexp -nocase -line -- {^fifth entry \< 56.*} $text match

Same here (and < does not need to be escaped):

```<code>regexp -nocase -line -- {^ *fifth entry < 56.*} $text match
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a string

set text {tools show stats
Resource Manager info at 023 h 06/01/20 09:14:16.105:

Hardware Resource Usage #1, abc iom-32-100g, Pipe #0:
                                 |   Total   | Allocated |    Free
  -------------------------------+-----------+-----------+------------
            stat vale abc/ghj(0) |        256|          0|        256
            stat vale abc/ghj(1) |        256|          0|        256

                   new Statistic |    Count
---------------------------------+-------------
                           first |         0
                          seconds|         0

                      third info |    Count
                           fourth|         0
                           fifth |       125

     Forwarding Table Statistics |   Used /  Free  /  Max  /  Reject
---------------------------------+-----------------------------------
              third stat Entries |      2 /  36856 /  36864
                      Important  |      1 /  13133 /  13136 / 0
                fifth entry < 56 |      1 /   5743 /   5744 / 0
                sixth entry > 5 |      0 /    112 /    112 / 0

Service manager resources
-------------------------
Total count:           2/  3072
Total info:            2/   401

ABC Group Statistics |   Used /  Free  / Max
---------------------------------+-----------------------
              Entries |      0 /    256 / 256
}

I have to extract

1. Important  |      1 /  13133 /  13136 / 0
2. fifth entry < 56 |      1 /   5743 /   5744 / 0

both can be done separetly
I'm using the following regex in tcl to extract the same

1. regexp -nocase -line -- {^Important.*} $text match
2. regexp -nocase -line -- {^fifth entry \< 56.*} $text match

its not working, can someone help here ?

Body:
regexp -nocase -line -- {^Important.*} $text match

You have spaces before Important, so you should add them to your expression like thus:

regexp -nocase -line -- {^ *Important.*} $text match

regexp -nocase -line -- {^fifth entry \< 56.*} $text match

Same here (and < does not need to be escaped):

regexp -nocase -line -- {^ *fifth entry < 56.*} $text match


问:
Snowflake Credit Calculation during scale up when clusters running in parallel for overlapping period
How does credit consumed gets calculated during scale up and scale down when queries running on old size cluster as well new queries on new size cluster during the change over.
e.g.  There were 4 queries running on X-Small size taking 12 mins to execute. While these queries running in their 2nd minute, I scaled up warehouse to Small Size and new 2 queries running on Small size for 4 mins and I scale down warehouse again for X-Small size. I have setup 5 mins as auto suspend time. Will the idle time before Auto suspend, charged for X-Small size or Small size ?  How the idle time before auto suspend get charged ? </p>

答:
Before auto-suspend, your warehouse was X-Small, so you should be charged for X-Small.

1) For scale-up, the credits are charged when the servers are provisioned.
2) The credits are billed for minimum 60 seconds. So when you scale-down after 10 seconds, it will still consume credit for 1 minute.

https://docs.snowflake.com/en/user-guide/warehouses-considerations.html#how-are-credits-charged-for-warehouses


问:
UIDocumentPickerViewController is showing flipped content in arabic
this is how I open the document picker

```<code>func openDocuments(){
        let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.data"],in: .import)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = .fullScreen

        self.present(documentPicker, animated: true) {
        }

    }
</code>```

notice how the cells have flipped labels

PS:

I have

```<code>UIView.appearance().semanticContentAttribute = .forceRightToLeft
</code>```

because the app I'm developing is in arabic only

答:
```<code>let documentPicker = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .import)
documentPicker.delegate = self
documentPicker.view.semanticContentAttribute = .forceLeftToRight
documentPicker.allowsMultipleSelection = true
self.present(documentPicker, animated: true)
</code>```

Body:
this is how I open the document picker

func openDocuments(){
        let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.data"],in: .import)
        documentPicker.delegate = self
        documentPicker.modalPresentationStyle = .fullScreen

        self.present(documentPicker, animated: true) {
        }

    }

notice how the cells have flipped labels

PS:

I have

UIView.appearance().semanticContentAttribute = .forceRightToLeft

because the app I'm developing is in arabic only


问:
Stub private methods in class under test in junit 5, PowerMock not working with JUnit5
I want to stub a private method in the class under test. I am using junit 5. I have used before powermock to achieve this. Unfortunately junit 5 does not work with powermock.

I have simplified the example to better explain the problem. I have class that has has private helper method that is called inside public methods. Like below:

public class Service {
    private Repository repository;

    public Object findById(String id) {
        Object object = repository.findById(id);
        object = verify(object);
        return object;
    }

    private Object verify(Object object) {
        //removed for simplicity
        return object;
    }
}
```

<p>Now I want to unit test the method <code>findById</code> of <code>Service</code>.  I have used junit 5 with mockito to implement unit test for the Service class.</p>

<pre class="lang-java prettyprint-override"><code>public class ServiceUTest {
    @InjectMocks
    private Service service;
    @Mock
    private Repository repository;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFindById() {
        when(repository.findById(Mockito.any())).thenReturn(new Object());
        //how to stub verify method
    }
}
</code>```

I would appreciate any help and guide to solve this problem.

Regards,

答:
Generally, a unit test is supposed to verify the public interface of a unit.

Stubbing private methods - is a bad idea. In this case, your tests are tightly coupled to the implementation details. And usually, you want to test the behavior but not implementation.

My suggestion is to return from repository such object which will comply with verification logic in a way you wanted to stub it.

Another approach to address such issues is to move out interesting bits into a new class. So then you can inject it as a dependency into your service.
For example, you can use Specification pattern to extract verification logic.

Body:
I want to stub a private method in the class under test. I am using junit 5. I have used before powermock to achieve this. Unfortunately junit 5 does not work with powermock.

I have simplified the example to better explain the problem. I have class that has has private helper method that is called inside public methods. Like below:

public class Service {
    private Repository repository;

    public Object findById(String id) {
        Object object = repository.findById(id);
        object = verify(object);
        return object;
    }

    private Object verify(Object object) {
        //removed for simplicity
        return object;
    }
}

Now I want to unit test the method findById of Service.  I have used junit 5 with mockito to implement unit test for the Service class.

public class ServiceUTest {
    @InjectMocks
    private Service service;
    @Mock
    private Repository repository;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testFindById() {
        when(repository.findById(Mockito.any())).thenReturn(new Object());
        //how to stub verify method
    }
}

I would appreciate any help and guide to solve this problem.

Regards,


答:
You have whitespace before the matches, the lines are indented, so you need to match the whitespace, say with [[:space:]]* that matches both regular spaces and tabs.

Or, just remove ^ if you do not need to match at the start of the line. ^ matches a position at the start of  a line.

To "exclude" it from the match, capture the text you need without the initial whitespaces using a pair of round brackets.

You may use

```<code>regexp -nocase -line -- {^[[:space:]]*(Important.*)} $text - match1
regexp -nocase -line -- {^[[:space:]]*(fifth entry < 56.*)} $text - match2
</code>```

See the Tcl online demo

Note you do not have to escape < if you want to match a literal < char.

Details

^  - start of a  line (here, due to -line)

[[:space:]]* - any 0  or more whitespaces

(Important.*) - Capturing group 1: Important and any 0 or more chars other than line break chars.

Title: extract 1st line from a text with special pattern using regexp

Body:
You have whitespace before the matches, the lines are indented, so you need to match the whitespace, say with [[:space:]]* that matches both regular spaces and tabs.

Or, just remove ^ if you do not need to match at the start of the line. ^ matches a position at the start of  a line.

To "exclude" it from the match, capture the text you need without the initial whitespaces using a pair of round brackets.

You may use

regexp -nocase -line -- {^[[:space:]]*(Important.*)} $text - match1
regexp -nocase -line -- {^[[:space:]]*(fifth entry < 56.*)} $text - match2

See the Tcl online demo

Note you do not have to escape < if you want to match a literal < char.

Details

^  - start of a  line (here, due to -line)

[[:space:]]* - any 0  or more whitespaces

(Important.*) - Capturing group 1: Important and any 0 or more chars other than line break chars.


问:
Python regex function to arrange key:value in descending order. Wherein the key is alphanumeric and the value is digits
Say I have a column which has values like:

```<code>**Input**

A12:67, A18:24, B11:89
A12:78, A19:100
B12:100, A20:19, A01:91
</code>```

I would like the piece of code that I am working on to return:

```<code>**Expected Output**

B11:89, A12:67, A18:24
A19:100, A12:78
B12:100, A01:91, A20:19
</code>```

I'm trying to get the code to sort this key-value pair based on the value of the item in descending order
This is the code I have written as of now, but it's sorting based on the digits in the Key and not the value.

```<code>def sortitem(df):
    sorteddf = df.apply(lambda x :",".join(sorted(x.split(", "), key=lambda y: int(re.search(r"(\d+)", y).group(1)), reverse=True)))
    return sorteddf
</code>```

The code outputs:

```<code>**Output received**

A18:24, A12:67, B11:89
A19:100, A12:78
A20:19, B12:100, A01:91
</code>```

Which is not the expected output. Please help with the corrections in the code required to achieve the desired output.
Thank you.

答:
How about this?

```<code>import pandas as pd

df = pd.DataFrame({
    'Input': [
        ['A12:67', 'A18:24', 'B11:89'],
        ['A12:78', 'A19:100'],
        ['B12:100', 'A20:19', 'A01:91']]
})

df['Results'] = df.Input.apply(
    lambda lst: sorted(lst, key=lambda s: int(s.split(':')[1]), reverse=True))

print(df)

                       Input                    Results
0   [A12:67, A18:24, B11:89]   [B11:89, A12:67, A18:24]
1          [A12:78, A19:100]          [A19:100, A12:78]
2  [B12:100, A20:19, A01:91]  [B12:100, A01:91, A20:19]
</code>```

It is not clear from your code whether your data is already formatted as lists of strings (like ['A12:67', 'A18:24', 'B11:89']) or just strings that have comma+space seperated values (like 'A12:67, A18:24, B11:89'). If the latter is the case, you can do

```<code>df.Input = df.Input.str.split(', ')
</code>```

before applying the previous function.

Body:
Say I have a column which has values like:

**Input**

A12:67, A18:24, B11:89
A12:78, A19:100
B12:100, A20:19, A01:91

I would like the piece of code that I am working on to return:

**Expected Output**

B11:89, A12:67, A18:24
A19:100, A12:78
B12:100, A01:91, A20:19

I'm trying to get the code to sort this key-value pair based on the value of the item in descending order
This is the code I have written as of now, but it's sorting based on the digits in the Key and not the value.

def sortitem(df):
    sorteddf = df.apply(lambda x :",".join(sorted(x.split(", "), key=lambda y: int(re.search(r"(\d+)", y).group(1)), reverse=True)))
    return sorteddf

The code outputs:

**Output received**

A18:24, A12:67, B11:89
A19:100, A12:78
A20:19, B12:100, A01:91

Which is not the expected output. Please help with the corrections in the code required to achieve the desired output.
Thank you.

Body:
How about this?

import pandas as pd

df = pd.DataFrame({
    'Input': [
        ['A12:67', 'A18:24', 'B11:89'],
        ['A12:78', 'A19:100'],
        ['B12:100', 'A20:19', 'A01:91']]
})

df['Results'] = df.Input.apply(
    lambda lst: sorted(lst, key=lambda s: int(s.split(':')[1]), reverse=True))

print(df)

                       Input                    Results
0   [A12:67, A18:24, B11:89]   [B11:89, A12:67, A18:24]
1          [A12:78, A19:100]          [A19:100, A12:78]
2  [B12:100, A20:19, A01:91]  [B12:100, A01:91, A20:19]

It is not clear from your code whether your data is already formatted as lists of strings (like ['A12:67', 'A18:24', 'B11:89']) or just strings that have comma+space seperated values (like 'A12:67, A18:24, B11:89'). If the latter is the case, you can do

df.Input = df.Input.str.split(', ')

before applying the previous function.


问:
Getting image on UIImageView
I'm currently making an app where the user takes a photo or select it from an album, then an overlay is placed over the image. The user can then scale, rotate and save the image.

For now, I have 2 xib files. The first one has thumbnails for overlay pictures to choose from.  Clicking on one of them goes to another xib file where I have 2 UIImageViews. One for the overlay and one for the camera. Previously I just used interface builder to set an image at the attributes. But if have 20 overlays, it means I have to use 20 xibs. So I thought the best way is to add pictures through code so I can use this 2nd xib as a template for the overlays. Here's when I'm stuck. When I click on a thumbnail in the 1st xib file, how do tell the 2nd xib file to store an overlay in the UIImageView?

For the camera, I'm using

```<code>imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
</code>```

and it works fine. I can even save it to the album. I thought I could use the code below for the overlays but that didn't work.

```<code>UIImage *image = [UIImage imageNamed: @"char1.png"];
</code>```

Hope someone can help. Thanks very much.

Hakimo

答: I think you can have two controllers.As you said first one will be static. You can declare the second controller as a class with outlets and ivars. Then you can create instances of that class whenever you you click either of the two controls on the first controller with the appropriate IMageviews (or Images).This is just the concept. I assume you can code this easily.</p>

ContentLicense: CC BY-SA 3.0

Title: Getting image on UIImageView

Body:
I'm currently making an app where the user takes a photo or select it from an album, then an overlay is placed over the image. The user can then scale, rotate and save the image.

For now, I have 2 xib files. The first one has thumbnails for overlay pictures to choose from.  Clicking on one of them goes to another xib file where I have 2 UIImageViews. One for the overlay and one for the camera. Previously I just used interface builder to set an image at the attributes. But if have 20 overlays, it means I have to use 20 xibs. So I thought the best way is to add pictures through code so I can use this 2nd xib as a template for the overlays. Here's when I'm stuck. When I click on a thumbnail in the 1st xib file, how do tell the 2nd xib file to store an overlay in the UIImageView?

For the camera, I'm using

imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

and it works fine. I can even save it to the album. I thought I could use the code below for the overlays but that didn't work.

UIImage *image = [UIImage imageNamed: @"char1.png"];

Hope someone can help. Thanks very much.

Hakimo


问:
Vuejs: Event on route change
On my main page I have dropdowns that show v-show=show by clicking on the link @click = "show=!show" and I want to set show=false when I change the route. Please advise me on how to realize this thing.

答:
Another solution for typescript user: </p>

```<code>import Vue from "vue";
import Component from "vue-class-component";

@Component({
  beforeRouteLeave(to, from, next) {
    // incase if you want to access `this`
    // const self = this as any;
    next();
  }
})

export default class ComponentName extends Vue {}
</code>```

Title: Vuejs: Event on route change

Body:
Another solution for typescript user:

import Vue from "vue";
import Component from "vue-class-component";

@Component({
  beforeRouteLeave(to, from, next) {
    // incase if you want to access `this`
    // const self = this as any;
    next();
  }
})

export default class ComponentName extends Vue {}


问:
Why does my Flutter app crash at startup on iOS?
I'm trying to build a simple app using Flutter for iOS and Android, but the app crashes on startup when I try to run it on an iPhone (Android runs fine).  I don't have a mac, so I'm using Codemagic to compile a release build and deploy to TestFlight, then installing on an iPhone from there.  Apple only shows their crash logs in Xcode as far as I can tell (nothing in App Store Connect online?), and since I don't have a mac, I can't see those.  Any thoughts as to what I might be running into, or what information I can gather to debug the problem?

Thanks!

Edit:  I've been digging around some more and it looks like the crash is related to the Firebase dependencies.  If I create the Flutter demo project (flutter create ), it runs fine on iOS.  However if I then add Firebase packages to pubspec.yaml, and manually add GoogleServices-info.plist, the app crashes on startup. (I'm not adding any code that uses Firebase yet.) GoogleServices-info.plist is supposed to be added with Xcode, but since I don't have Xcode or a mac, that makes it tough.  The second answer to this question gives a suggestion: Where to save GoogleService-Info.plist in Flutter without Xcode?
I tried making those changes but got the same result. Anybody have any recommendations for adding Firebase without a mac?

答: i had the same issue and i have fixed it as i was new to ios deployment i forgot to add capabilities which indeed crashed my app in testflight ...so please be sure you have added required capabilities in signing and capability tab in xcode</p>


问:
Dynamic Keys and value type checking in typescript
I have started learning typescript. I am sure there might be a similar ticket as this but wanted a quick view into this.

```<code>i have keys
type keys = 'a' | 'e' | 'i' | 'o' | 'u';
I want these to restrict the possible a keys in an object
</code>```

```<code>{
numbers : number;
symbols : string;
[key : keys] : string | number | boolean;
}
</code>```

However i get this error An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
so i tried

```<code>{
numbers : number;
symbols : string;
[key in keys] : string | number | boolean;
}
</code>```

but I got another error from TSLint.
I hope if somebody can help me out with these with examples why and how do they vary? and solution Please.

The result I want is

```<code>key with only values of a, e, i, o, u and these Keys can have any of the string, number, boolean types of values.
</code>```

答:
```<code>
    type keys =  'a' | 'e' | 'i' | 'o' | 'u'

    type Dynamic = {
      [index in  keys]: string | number | boolean
    }&{
      numbers : number;
      symbols : string;
    }

</code>```

Body:
I have started learning typescript. I am sure there might be a similar ticket as this but wanted a quick view into this.

i have keys
type keys = 'a' | 'e' | 'i' | 'o' | 'u';
I want these to restrict the possible a keys in an object

{
numbers : number;
symbols : string;
[key : keys] : string | number | boolean;
}

However i get this error An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
so i tried

{
numbers : number;
symbols : string;
[key in keys] : string | number | boolean;
}

but I got another error from TSLint.
I hope if somebody can help me out with these with examples why and how do they vary? and solution Please.

The result I want is

key with only values of a, e, i, o, u and these Keys can have any of the string, number, boolean types of values.


问:
How to clear the interval in React
I am building a stopwatch by using useState hooks in react.js but while implementing pause functionality I have noticed that I am not able to clear the interval. I am new and I have tried many things but still it doesn't work. If anyone can help me fix the code or suggest me other way.

Here is my code:

```<code>function App() {
  const [stopwatch, setStopwatch] = useState({
    hour: 0,
    min: 0,
    sec: 0,
    secElapsed: 0,
    minElapsed: 0,
  });

  const [buttonState, setButtonState] = useState({
    start: true,
    stop: false,
    pause: false,
    resume: false,
  });

  var interval = null;

  function onStart() {
    // i want to clear this interval when the onPause function is called
    var clrInt = setInterval(() => {
      setStopwatch(prevValue => {
        prevValue.secElapsed++;
        return {
          hour: Math.floor(prevValue.secElapsed / 3600),
          minElapsed: Math.floor((prevValue.secElapsed + 1) / 60),
          min: prevValue.minElapsed % 60,
          sec: prevValue.secElapsed % 60,
          secElapsed: prevValue.secElapsed,
        };
      });
    }, 1000);

    setButtonState(prevValue => {
      return {
        ...prevValue,
        start: false,
        pause: true,
        stop: true,
      };
    });
    interval = clrInt;
  }

  function onPause() {
    setButtonState(prevValue => {
      return {
        ...prevValue,
        pause: false,
        resume: true,
      };
    });

    // i want to clear the interval in onStart function here
    clearInterval(interval);
  }

  return (
    <div>
      <h1>
        {stopwatch.hour < 10 ? '0' + stopwatch.hour : stopwatch.hour}:
        {stopwatch.min < 10 ? '0' + stopwatch.min : stopwatch.min}:
        {stopwatch.sec < 10 ? '0' + stopwatch.sec : stopwatch.sec}
      </h1>
      {buttonState.start ? <button onClick={onStart}>Start</button> : null}
      {buttonState.pause ? <button onClick={onPause}>Pause</button> : null}
      {buttonState.stop ? <button>Stop</button> : null}
      {buttonState.resume ? <button>Resume</button> : null}
    </div>
  );
}

</code>```

答:
Declaring a variable inside the function component will run every time the component is rendered. You need to capture the interval in a useState like

```<code>var [intervalState, setIntervalState] = useState(null)

...

function onStart() {
   var clearInterval = setInterval(() => {
      ...
   })

   setIntervalState(clearInterval)
}
</code>```

This will make sure your clearInterval value will persist across rerenders

Title: How to clear the interval in React

Body:
I am building a stopwatch by using useState hooks in react.js but while implementing pause functionality I have noticed that I am not able to clear the interval. I am new and I have tried many things but still it doesn't work. If anyone can help me fix the code or suggest me other way.

Here is my code:

function App() {
  const [stopwatch, setStopwatch] = useState({
    hour: 0,
    min: 0,
    sec: 0,
    secElapsed: 0,
    minElapsed: 0,
  });

  const [buttonState, setButtonState] = useState({
    start: true,
    stop: false,
    pause: false,
    resume: false,
  });

  var interval = null;

  function onStart() {
    // i want to clear this interval when the onPause function is called
    var clrInt = setInterval(() => {
      setStopwatch(prevValue => {
        prevValue.secElapsed++;
        return {
          hour: Math.floor(prevValue.secElapsed / 3600),
          minElapsed: Math.floor((prevValue.secElapsed + 1) / 60),
          min: prevValue.minElapsed % 60,
          sec: prevValue.secElapsed % 60,
          secElapsed: prevValue.secElapsed,
        };
      });
    }, 1000);

    setButtonState(prevValue => {
      return {
        ...prevValue,
        start: false,
        pause: true,
        stop: true,
      };
    });
    interval = clrInt;
  }

  function onPause() {
    setButtonState(prevValue => {
      return {
        ...prevValue,
        pause: false,
        resume: true,
      };
    });

    // i want to clear the interval in onStart function here
    clearInterval(interval);
  }

  return (

        {stopwatch.hour < 10 ? '0' + stopwatch.hour : stopwatch.hour}:
        {stopwatch.min < 10 ? '0' + stopwatch.min : stopwatch.min}:
        {stopwatch.sec < 10 ? '0' + stopwatch.sec : stopwatch.sec}

      {buttonState.start ? <button onClick={onStart}>Start</button> : null}
      {buttonState.pause ? <button onClick={onPause}>Pause</button> : null}
      {buttonState.stop ? <button>Stop</button> : null}
      {buttonState.resume ? <button>Resume</button> : null}

  );
}

Body:
Declaring a variable inside the function component will run every time the component is rendered. You need to capture the interval in a useState like

var [intervalState, setIntervalState] = useState(null)

...

function onStart() {
   var clearInterval = setInterval(() => {
      ...
   })

   setIntervalState(clearInterval)
}

This will make sure your clearInterval value will persist across rerenders


问:
Keras: How to one-hot encode logits to match labels for loss function
I'm trying to implement a perplexity loss function for my LSTM language model. However I get the following error:

```<code>InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [32,3345] and labels shape [107040]
     [[{{node loss_9/dense_10_loss/perplexity/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]]
</code>```

Now, I think the way to solve this is by one-hot encoding my logits, but I'm not sure how to do this, i.e. I don't know how to access my logits, and I dont know what depth I should encode them with.

My loss function looks as follows:

```<code>import keras.losses
from keras import backend as K
def perplexity(y_true, y_pred):
    """
    The perplexity metric. Why isn't this part of Keras yet?!
    https://stackoverflow.com/questions/41881308/how-to-calculate-perplexity-of-rnn-in-tensorflow
    https://github.com/keras-team/keras/issues/8267
    """
    cross_entropy = K.sparse_categorical_crossentropy(y_true, y_pred)
    perplexity = K.exp(cross_entropy)
    return perplexity
</code>```

And I define my LSTM model as follows:

```<code># define model
model = Sequential()
model.add(Embedding(vocab_size, 500, input_length=max_length-1))
model.add(LSTM(750))
model.add(Dense(vocab_size, activation='softmax'))
print(model.summary())
# compile network
model.compile(loss=perplexity, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=150, verbose=2)
</code>```

答:
if you use sparse_categorical_crossentropy your output must be simply integer encoded

```<code>def perplexity(y_true, y_pred):
    cross_entropy = K.sparse_categorical_crossentropy(y_true, y_pred)
    perplexity = K.exp(cross_entropy)
    return perplexity

vocab_size = 10
X = np.random.uniform(0,1, (1000,10))
y = np.random.randint(0,vocab_size, 1000)

model = Sequential()
model.add(Dense(64, activation='relu', input_dim=(10)))
model.add(Dense(vocab_size, activation='softmax'))
# compile network
model.compile(loss=perplexity, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=10, verbose=2)
</code>```

if you have one-hot encoded target, take care to change K.sparse_categorical_crossentropy in K.categorical_crossentropy

```<code>def perplexity(y_true, y_pred):
    cross_entropy = K.categorical_crossentropy(y_true, y_pred)
    perplexity = K.exp(cross_entropy)
    return perplexity

vocab_size = 10
X = np.random.uniform(0,1, (1000,10))
y = pd.get_dummies(np.random.randint(0,vocab_size, 1000)).values # one-hot

model = Sequential()
model.add(Dense(64, activation='relu', input_dim=(10)))
model.add(Dense(vocab_size, activation='softmax'))
# compile network
model.compile(loss=perplexity, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=10, verbose=2)
</code>```

Body:
I'm trying to implement a perplexity loss function for my LSTM language model. However I get the following error:

InvalidArgumentError: logits and labels must have the same first dimension, got logits shape [32,3345] and labels shape [107040]
     [[{{node loss_9/dense_10_loss/perplexity/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]]

Now, I think the way to solve this is by one-hot encoding my logits, but I'm not sure how to do this, i.e. I don't know how to access my logits, and I dont know what depth I should encode them with.

My loss function looks as follows:

import keras.losses
from keras import backend as K
def perplexity(y_true, y_pred):
    """
    The perplexity metric. Why isn't this part of Keras yet?!
    https://stackoverflow.com/questions/41881308/how-to-calculate-perplexity-of-rnn-in-tensorflow
    https://github.com/keras-team/keras/issues/8267
    """
    cross_entropy = K.sparse_categorical_crossentropy(y_true, y_pred)
    perplexity = K.exp(cross_entropy)
    return perplexity

And I define my LSTM model as follows:

# define model
model = Sequential()
model.add(Embedding(vocab_size, 500, input_length=max_length-1))
model.add(LSTM(750))
model.add(Dense(vocab_size, activation='softmax'))
print(model.summary())
# compile network
model.compile(loss=perplexity, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=150, verbose=2)

Body:
if you use sparse_categorical_crossentropy your output must be simply integer encoded

def perplexity(y_true, y_pred):
    cross_entropy = K.sparse_categorical_crossentropy(y_true, y_pred)
    perplexity = K.exp(cross_entropy)
    return perplexity

vocab_size = 10
X = np.random.uniform(0,1, (1000,10))
y = np.random.randint(0,vocab_size, 1000)

model = Sequential()
model.add(Dense(64, activation='relu', input_dim=(10)))
model.add(Dense(vocab_size, activation='softmax'))
# compile network
model.compile(loss=perplexity, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=10, verbose=2)

if you have one-hot encoded target, take care to change K.sparse_categorical_crossentropy in K.categorical_crossentropy

def perplexity(y_true, y_pred):
    cross_entropy = K.categorical_crossentropy(y_true, y_pred)
    perplexity = K.exp(cross_entropy)
    return perplexity

vocab_size = 10
X = np.random.uniform(0,1, (1000,10))
y = pd.get_dummies(np.random.randint(0,vocab_size, 1000)).values # one-hot

model = Sequential()
model.add(Dense(64, activation='relu', input_dim=(10)))
model.add(Dense(vocab_size, activation='softmax'))
# compile network
model.compile(loss=perplexity, optimizer='adam', metrics=['accuracy'])
# fit network
model.fit(X, y, epochs=10, verbose=2)


问:
Unable to scrape product title from Amazon
I am using Scrapy to get the price and title of produts on this Amazon website. No issues to extract the price, but I have issues with the title. The difference is I see "aria-hidded=true" in the class attribute. Here is the example.

Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine…
```
</div>
</div>
</p>

<p>Here is the css selector command:</p>

```title = response.css('.p13n-sc-truncated').css('::text').extract()
```

May I know what the CSS selector should be to extract the text. Thanks

答:
Your code is fine:

>>> from parsel import Selector
>>> selector = Selector(text='
Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine…
')
>>> selector.css('.p13n-sc-truncated').css('::text').extract()
['Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine…']
```

My guess is that the response does not contain the expected HTML. If this is Amazon, that is extremely likely. They have quite some antibot measures in place.

Body:
I am using Scrapy to get the price and title of produts on this Amazon website. No issues to extract the price, but I have issues with the title. The difference is I see "aria-hidded=true" in the class attribute. Here is the example.

Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine…

Here is the css selector command:

title = response.css('.p13n-sc-truncated').css('::text').extract()

May I know what the CSS selector should be to extract the text. Thanks

Body:
Your code is fine:

>>> from parsel import Selector
>>> selector = Selector(text='<div class="p13n-sc-truncated" aria-hidden="true" data-rows="2" title="Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine With Handle, 26 Pounds in 24 Hours, 9 Ice Cubes Ready in 7 minutes, With Ice Scoop and Basket">Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine…</div>')
>>> selector.css('.p13n-sc-truncated').css('::text').extract()
['Igloo ICEB26HNAQ Automatic Self-Cleaning Portable Electric Countertop Ice Maker Machine…']

My guess is that the response does not contain the expected HTML. If this is Amazon, that is extremely likely. They have quite some antibot measures in place.


问:
RxAndroid 3 main thread
I am trying to find the main thread for subscribeOn in Rx3

```<code>Single.just(getHeavyData())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<Data>() {
                                    @Override
                                    public void accept(Data d) throws Throwable {
                                        setAdapters(d);
                                    }
                                });
</code>```

AndroidSchedulers.mainThread() - is not compatible with the brand new RX3

Gradle import:  implementation "io.reactivex.rxjava3:rxjava:3.0.0-RC3"

How can we find the main thread in order to do changes to the UI?

答:
Had a similar problem and the compatibility issue was from an import of the Single. Even though I was using RxJava3 library and RxAndroid3, I was still using:

```<code>import io.reactivex.Single
</code>```

But was resolved when pointing the Single to:

```<code>import io.reactivex.rxjava3.core.Single
</code>```

Title: RxAndroid 3 main thread

Body:
I am trying to find the main thread for subscribeOn in Rx3

Single.just(getHeavyData())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<Data>() {
                                    @Override
                                    public void accept(Data d) throws Throwable {
                                        setAdapters(d);
                                    }
                                });

AndroidSchedulers.mainThread() - is not compatible with the brand new RX3

Gradle import:  implementation "io.reactivex.rxjava3:rxjava:3.0.0-RC3"

How can we find the main thread in order to do changes to the UI?

Body:
Had a similar problem and the compatibility issue was from an import of the Single. Even though I was using RxJava3 library and RxAndroid3, I was still using:

import io.reactivex.Single

But was resolved when pointing the Single to:

import io.reactivex.rxjava3.core.Single


问:
C# & SQL Server : how to Insert DBNull.Value in command parameter if string value is empty?
I've been searching for a couple of hours now and cannot find a solution.

I am inserting some strings into SQL, however on on occasions, the method I use to do this may contain strings that are empty, i.e ""

I therefore want to insert a null value into SQL Server instead.

Firstly I test my method to make sure I am able to insert a DBNull.Value manually by using the following:

```<code>cmd.Parameters.AddWithValue("@surname", DBNull.Value);  // THIS WORKS OK
</code>```

HOWEVER when I try the following below, the method runs without any error exception BUT the SQL Server column does not show a null value, it's just empty with nothing in it:

```<code>cmd.Parameters.AddWithValue("@surname", (object)surname ?? DBNull.Value);
</code>```

I just want an efficient solution without messing about with any more common class extensions and writing lots of extra code. Every answer I see on the forums is just over complicated for what should be such a simple task.

Any ideas? Thanks in advance...

Here is the full method:

```<code>public static void AddUserToUserTable(string username,
        string forename,
        string surname,
        string emailAddress,
        string password,
        string accountActive,
        string userGroup)
{
    string cmdText1 = "INSERT INTO Users (Username, Forename, Surname, EmailAddress, Password, AccountActive, UserGroup) VALUES (@username, @forename, @surname, @emailAddress, @password, @userGroup, @accountActive)";

    try
    {
        // The using statement will take care of the disposing of the reader and the command object.
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand(cmdText1, connection);

            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@forename", forename);
            cmd.Parameters.AddWithValue("@surname", surname, null);
            cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
            cmd.Parameters.AddWithValue("@password", password);
            cmd.Parameters.AddWithValue("@userGroup", accountActive);
            cmd.Parameters.AddWithValue("@accountActive", userGroup);

            connection.Open();
            cmd.ExecuteNonQuery();

            log.Info("NEW User [" + username + "] Created");
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
}
</code>```

答:
Just check from microsoft doc

```<code>public System.Data.SqlClient.SqlParameter AddWithValue (string parameterName, object value);
</code>```

DBNull and string class both Inherited from Object so you can cast them and pass an object type in the second parameter.

One simple suggestion to add DBNull.Value to SQL server if string is empty is the following

Try the following in your code (it works): you also need to know the ?? operator

```<code>string sql = "INSERT INTO [table] (columnName) VALUES (?);";
cmd.Parameters.AddWithValue("@columnName", (object)model.value ?? DBNull.Value);
</code>```

Body:
I've been searching for a couple of hours now and cannot find a solution.

I am inserting some strings into SQL, however on on occasions, the method I use to do this may contain strings that are empty, i.e ""

I therefore want to insert a null value into SQL Server instead.

Firstly I test my method to make sure I am able to insert a DBNull.Value manually by using the following:

cmd.Parameters.AddWithValue("@surname", DBNull.Value);  // THIS WORKS OK

HOWEVER when I try the following below, the method runs without any error exception BUT the SQL Server column does not show a null value, it's just empty with nothing in it:

cmd.Parameters.AddWithValue("@surname", (object)surname ?? DBNull.Value);

I just want an efficient solution without messing about with any more common class extensions and writing lots of extra code. Every answer I see on the forums is just over complicated for what should be such a simple task.

Any ideas? Thanks in advance...

Here is the full method:

public static void AddUserToUserTable(string username,
        string forename,
        string surname,
        string emailAddress,
        string password,
        string accountActive,
        string userGroup)
{
    string cmdText1 = "INSERT INTO Users (Username, Forename, Surname, EmailAddress, Password, AccountActive, UserGroup) VALUES (@username, @forename, @surname, @emailAddress, @password, @userGroup, @accountActive)";

    try
    {
        // The using statement will take care of the disposing of the reader and the command object.
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand(cmdText1, connection);

            cmd.Parameters.AddWithValue("@username", username);
            cmd.Parameters.AddWithValue("@forename", forename);
            cmd.Parameters.AddWithValue("@surname", surname, null);
            cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
            cmd.Parameters.AddWithValue("@password", password);
            cmd.Parameters.AddWithValue("@userGroup", accountActive);
            cmd.Parameters.AddWithValue("@accountActive", userGroup);

            connection.Open();
            cmd.ExecuteNonQuery();

            log.Info("NEW User [" + username + "] Created");
        }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
}

Body:
Just check from microsoft doc

public System.Data.SqlClient.SqlParameter AddWithValue (string parameterName, object value);

DBNull and string class both Inherited from Object so you can cast them and pass an object type in the second parameter.

One simple suggestion to add DBNull.Value to SQL server if string is empty is the following

Try the following in your code (it works): you also need to know the ?? operator

string sql = "INSERT INTO [table] (columnName) VALUES (?);";
cmd.Parameters.AddWithValue("@columnName", (object)model.value ?? DBNull.Value);


问:
PHP Split and sort data in new array
Restructuring PHP array data.
Testing the "data block 1" works fine and the data is correctly exploded in $newArray_1 and finally sorted in $newArray_2. I do not really use the explode but choosed to kept it in the code since it will be used later to extract the needed name of key within new arrays.

Question: Is it possible to use the same code base in order to solve with the same handling of "data block 2" ?

My code:

```<code>// Unsorted array -------------------------------------

$frontendData = [
  'datasheet' => [
    'Name_1_balance0'    => 1, // Data block 1
    'Name_1_balance2'    => 3, // Data block 1
    'Name_1_balance3'    => 4, // Data block 1
    'Name_1_balance1'    => 2, // Data block 1
    // 'Name_2_balance0'    => 5, // Data block 2
    // 'Name_2_balance2'    => 7, // Data block 2
    // 'Name_2_balance3'    => 8, // Data block 2
    // 'Name_2_balance1'    => 6, // Data block 2
  ]
];

ksort($frontendData['datasheet']);
print_r($frontendData);

// Explode array -------------------------------------

$newArray_1 = [];

foreach ( $frontendData as $mainKey => $elements )  {
    foreach ( $elements as $subKey => $value ){
        $newData = explode("_", $subKey);
        $newData[] = $value;
        $newArray_1[$mainKey][] = $newData;
    }
}

print_r($newArray_1);

// Restructure array -------------------------------------

$newArray_2['datasheet'] = ['Name_1'];

for ($i=0; $i <=3 ; $i++) {

  $newArray_2['datasheet'][1]['balance'][$i] =
    $newArray_1['datasheet'][$i][3];

}

print_r($newArray_2);
</code>```

Result (Processing "Data block 1"):

```<code>Array
(
    [datasheet] => Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        )

)
</code>```

Wanted result (Processing "Data block 1" & "Data block 2"):

```<code>Array
(
    [datasheet] =>
        Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        ),
        Array
        (
            [0] => Name_2
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 5
                            [1] => 6
                            [2] => 7
                            [3] => 8
                        )

                )

        )

)
</code>```

答:
You can iterate over your $frontendData array, using preg_match to extract the name and balance number (thus avoiding the need to sort the array), and building a result array using those values indexed by the name. We then use array_values to re-index the array numerically and assign it to a datasheet key in the output:

```<code>$result = array();

foreach ($frontendData['datasheet'] as $key => $balance) {
    preg_match('/^(\w+)_balance(\d+)$/', $key, $match);
    $result[$match[1]][0] = $match[1];
    $result[$match[1]][1]['balance'][$match[2]] = $balance;
}
$result = array('datasheet' => array_values($result));
print_r($result);
</code>```

Output (for your sample data):

```<code>Array
(
    [datasheet] => Array
        (
            [0] => Array
                (
                    [0] => Name_1
                    [1] => Array
                        (
                            [balance] => Array
                                (
                                    [0] => 1
                                    [2] => 3
                                    [3] => 4
                                    [1] => 2
                                )
                        )
                )
            [1] => Array
                (
                    [0] => Name_2
                    [1] => Array
                        (
                            [balance] => Array
                                (
                                    [0] => 5
                                    [2] => 7
                                    [3] => 8
                                    [1] => 6
                                )
                        )
                )
        )
)
</code>```

Demo on 3v4l.org

Note that entries in the balance array occur in the same order as they are in the original datasheet array so indexes may not be in numeric order. If that is a concern (for example, if you wanted to iterate the values using foreach rather than a for loop over the indexes), you should sort $frontendData['datasheet'] by its keys, using uksort with a callback of strnatcmp to ensure that balance10 sorts after balance2 to balance9:

```<code>uksort($frontendData['datasheet'], 'strnatcmp');
</code>```

Demo on 3v4l.org

Title: PHP Split and sort data in new array

Body:
Restructuring PHP array data.
Testing the "data block 1" works fine and the data is correctly exploded in $newArray_1 and finally sorted in $newArray_2. I do not really use the explode but choosed to kept it in the code since it will be used later to extract the needed name of key within new arrays.

Question: Is it possible to use the same code base in order to solve with the same handling of "data block 2" ?

My code:

// Unsorted array -------------------------------------

$frontendData = [
  'datasheet' => [
    'Name_1_balance0'    => 1, // Data block 1
    'Name_1_balance2'    => 3, // Data block 1
    'Name_1_balance3'    => 4, // Data block 1
    'Name_1_balance1'    => 2, // Data block 1
    // 'Name_2_balance0'    => 5, // Data block 2
    // 'Name_2_balance2'    => 7, // Data block 2
    // 'Name_2_balance3'    => 8, // Data block 2
    // 'Name_2_balance1'    => 6, // Data block 2
  ]
];

ksort($frontendData['datasheet']);
print_r($frontendData);

// Explode array -------------------------------------

$newArray_1 = [];

foreach ( $frontendData as $mainKey => $elements )  {
    foreach ( $elements as $subKey => $value ){
        $newData = explode("_", $subKey);
        $newData[] = $value;
        $newArray_1[$mainKey][] = $newData;
    }
}

print_r($newArray_1);

// Restructure array -------------------------------------

$newArray_2['datasheet'] = ['Name_1'];

for ($i=0; $i <=3 ; $i++) {

  $newArray_2['datasheet'][1]['balance'][$i] =
    $newArray_1['datasheet'][$i][3];

}

print_r($newArray_2);

Result (Processing "Data block 1"):

Array
(
    [datasheet] => Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        )

)

Wanted result (Processing "Data block 1" & "Data block 2"):

Array
(
    [datasheet] =>
        Array
        (
            [0] => Name_1
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                            [3] => 4
                        )

                )

        ),
        Array
        (
            [0] => Name_2
            [1] => Array
                (
                    [balance] => Array
                        (
                            [0] => 5
                            [1] => 6
                            [2] => 7
                            [3] => 8
                        )

                )

        )

)

Body:
You can iterate over your $frontendData array, using preg_match to extract the name and balance number (thus avoiding the need to sort the array), and building a result array using those values indexed by the name. We then use array_values to re-index the array numerically and assign it to a datasheet key in the output:

$result = array();

foreach ($frontendData['datasheet'] as $key => $balance) {
    preg_match('/^(\w+)_balance(\d+)$/', $key, $match);
    $result[$match[1]][0] = $match[1];
    $result[$match[1]][1]['balance'][$match[2]] = $balance;
}
$result = array('datasheet' => array_values($result));
print_r($result);

Output (for your sample data):

Array
(
    [datasheet] => Array
        (
            [0] => Array
                (
                    [0] => Name_1
                    [1] => Array
                        (
                            [balance] => Array
                                (
                                    [0] => 1
                                    [2] => 3
                                    [3] => 4
                                    [1] => 2
                                )
                        )
                )
            [1] => Array
                (
                    [0] => Name_2
                    [1] => Array
                        (
                            [balance] => Array
                                (
                                    [0] => 5
                                    [2] => 7
                                    [3] => 8
                                    [1] => 6
                                )
                        )
                )
        )
)

Demo on 3v4l.org

Note that entries in the balance array occur in the same order as they are in the original datasheet array so indexes may not be in numeric order. If that is a concern (for example, if you wanted to iterate the values using foreach rather than a for loop over the indexes), you should sort $frontendData['datasheet'] by its keys, using uksort with a callback of strnatcmp to ensure that balance10 sorts after balance2 to balance9:

uksort($frontendData['datasheet'], 'strnatcmp');

Demo on 3v4l.org


问:
E-mail Notifications
In a .net system I'm building, there is a need for automated e-mail notifications. These should be editable by an admin. What's the easiest way to do this? SQL table and WYSIWIG for editing?

The queue is a great idea. I've been throwing around that type of process for awhile with my old company.

答:
From a high level, yes.  :D  The main thing is some place to store the templates.  A database is a great option unless you're not already using one, then file systems work fine.

WSIWIG editors (such as fckeditor) work well and give you some good options regarding the features that you allow.

Some sort of token replacement system is also a good idea if you need it.  For example, if someone puts %FIRSTNAME% in the email template, the code that generates the email can do some simple pattern matching to replace known tokens with other known values that may be dynamic based on user or other circumstances.

Title: E-mail Notifications

LastEditorDisplayName: Jeff Atwood

ContentLicense: CC BY-SA 2.5


问:
Is there a way to loop through a table variable in TSQL without using a cursor?
Let's say I have the following simple table variable:

```<code>declare @databases table
(
    DatabaseID    int,
    Name        varchar(15),
    Server      varchar(15)
)
-- insert a bunch rows into @databases
</code>```

Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?

答:
First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code.

Depending on your data it may be possible to loop using just SELECT statements as shown below:

```<code>Declare @Id int

While (Select Count(*) From ATable Where Processed = 0) > 0
Begin
    Select Top 1 @Id = Id From ATable Where Processed = 0

    --Do some processing here

    Update ATable Set Processed = 1 Where Id = @Id

End
</code>```

Another alternative is to use a temporary table:

```<code>Select *
Into   #Temp
From   ATable

Declare @Id int

While (Select Count(*) From #Temp) > 0
Begin

    Select Top 1 @Id = Id From #Temp

    --Do some processing here

    Delete #Temp Where Id = @Id

End
</code>```

The option you should choose really depends on the structure and volume of your data.

Note: If you are using SQL Server you would be better served using:

```<code>WHILE EXISTS(SELECT * FROM #Temp)
</code>```

Using COUNT will have to touch every single row in the table, the EXISTS only needs to touch the first one (see Josef's answer below).

OwnerDisplayName: Ray Vega

Body:
Let's say I have the following simple table variable:

declare @databases table
(
    DatabaseID    int,
    Name        varchar(15),
    Server      varchar(15)
)
-- insert a bunch rows into @databases

Is declaring and using a cursor my only option if I wanted to iterate through the rows? Is there another way?

Body:
First of all you should be absolutely sure you need to iterate through each row — set based operations will perform faster in every case I can think of and will normally use simpler code.

Depending on your data it may be possible to loop using just SELECT statements as shown below:

Declare @Id int

While (Select Count(*) From ATable Where Processed = 0) > 0
Begin
    Select Top 1 @Id = Id From ATable Where Processed = 0

    --Do some processing here

    Update ATable Set Processed = 1 Where Id = @Id

End

Another alternative is to use a temporary table:

Select *
Into   #Temp
From   ATable

Declare @Id int

While (Select Count(*) From #Temp) > 0
Begin

    Select Top 1 @Id = Id From #Temp

    --Do some processing here

    Delete #Temp Where Id = @Id

End

The option you should choose really depends on the structure and volume of your data.

Note: If you are using SQL Server you would be better served using:

WHILE EXISTS(SELECT * FROM #Temp)

Using COUNT will have to touch every single row in the table, the EXISTS only needs to touch the first one (see Josef's answer below).

OwnerDisplayName: BelowNinety


问:
Rails: Is it bad to have an irreversible migration?
When is it acceptable to raise an ActiveRecord::IrreversibleMigration exception in the self.down method of a migration?  When should you take the effort to actually implement the reverse of the migration?</p>

答:
Feeling like you need an irreversible migration is probably a sign you've got bigger problems looming. Maybe some specifics would help?

As for your second question: I always take the 'effort' to write the reverse of migrations. Of course, I don't actually write the .down, TextMate inserts it automatically when creating the .up.

OwnerDisplayName: Readonly

OwnerDisplayName: thenduks


问:
Calling a JSON API using Python
The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
API End Points

To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:

http://py4e-data.dr-chuck.net/json?
This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get "No address..." response.

I have worked on this assignment, but the codes are not running. I am JSONDecodeError whenever I run the program.

```<code>import urllib.request, urllib.parse, urllib.error
import json
adr= 'http://py4e-data.dr-chuck.net/json?'
while True:
    loca= input('Enter Location: ')
    if len(loca)<1:break

    url=adr + urllib.parse.urlencode({"address": loca})
    print('Retrieving', url)
    fha=urllib.request.urlopen(url)
    data=fha.read().decode()
    print('Retrieved', len(data))

    jsdata=json.loads(str(data))
    placeid= jsdata['results'][0]['place_id']
    print('The Place ID is: ', placeid)
</code>```

答:
This is the most updated code for the query</p>
```<code>import json,ssl
import urllib.request,urllib.parse, urllib.error

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "South Federal University"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)
</code>```

Title: Calling a JSON API using Python

Body:
The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
API End Points

To complete this assignment, you should use this API endpoint that has a static subset of the Google Data:

http://py4e-data.dr-chuck.net/json?
This API uses the same parameter (address) as the Google API. This API also has no rate limit so you can test as often as you like. If you visit the URL with no parameters, you get "No address..." response.

I have worked on this assignment, but the codes are not running. I am JSONDecodeError whenever I run the program.

import urllib.request, urllib.parse, urllib.error
import json
adr= 'http://py4e-data.dr-chuck.net/json?'
while True:
    loca= input('Enter Location: ')
    if len(loca)<1:break

    url=adr + urllib.parse.urlencode({"address": loca})
    print('Retrieving', url)
    fha=urllib.request.urlopen(url)
    data=fha.read().decode()
    print('Retrieved', len(data))

    jsdata=json.loads(str(data))
    placeid= jsdata['results'][0]['place_id']
    print('The Place ID is: ', placeid)

Body:
This is the most updated code for the query

import json,ssl
import urllib.request,urllib.parse, urllib.error

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

#Stroring the given parameters
api_key = 42
serviceurl = "http://py4e-data.dr-chuck.net/json?"
# sample_address = "South Federal University"
data_address = "South Federal University"
address_wanted = data_address

#Setting the GET parameters on the URL
parameters = {"address": address_wanted, "key":api_key}
paramsurl = urllib.parse.urlencode(parameters)

#Generating the complete URL. Printing it in order to check if it's correct.
queryurl = serviceurl.strip() + paramsurl.strip()
print("DATA URL: ", queryurl)

#Obtaining and reading the data
try :
    data_read = urllib.request.urlopen(queryurl , context=ctx).read()
    data = data_read.decode()
    # Parsing the data and looking for the field we want.
    jsondata = json.loads(data)
    print(jsondata)
    place_id = jsondata["results"][0]["place_id"]
    print("PLACE ID: ", place_id)
except:
    print("Error.....")
    print("-"*50)
    print(data)


问:
Python: data argument can't be an iterator
I'm trying to replicate the code that is provided here:
https://github.com/IdoZehori/Credit-Score/blob/master/Credit%20score.ipynb

The function given below fails to run and give error. Can someone help me resolving it

```<code>def replaceOutlier(data, method = outlierVote, replace='median'):
'''replace: median (auto)
            'minUpper' which is the upper bound of the outlier detection'''
vote = outlierVote(data)
x = pd.DataFrame(zip(data, vote), columns=['annual_income', 'outlier'])
if replace == 'median':
    replace = x.debt.median()
elif replace == 'minUpper':
    replace = min([val for (val, vote) in list(zip(data, vote)) if vote == True])
    if replace < data.mean():
        return 'There are outliers lower than the sample mean'
debtNew = []
for i in range(x.shape[0]):
    if x.iloc[i][1] == True:
        debtNew.append(replace)
    else:
        debtNew.append(x.iloc[i][0])

return debtNew
</code>```

Function Call:

```<code>incomeNew = replaceOutlier(df.annual_income, replace='minUpper')
</code>```

Error:
  x = pd.DataFrame(zip(data, vote), columns=['annual_income', 'outlier'])
  TypeError: data argument can't be an iterator

PS: I understand this has been asked before, but I tried using the techniques however the error still remains

答: This happens because of data type issue, you can first convert it to list and then that list to dataframe. Ex. pd.DataFrame(list(data)) should work.</p>

Body:
I'm trying to replicate the code that is provided here:
https://github.com/IdoZehori/Credit-Score/blob/master/Credit%20score.ipynb

The function given below fails to run and give error. Can someone help me resolving it

def replaceOutlier(data, method = outlierVote, replace='median'):
'''replace: median (auto)
            'minUpper' which is the upper bound of the outlier detection'''
vote = outlierVote(data)
x = pd.DataFrame(zip(data, vote), columns=['annual_income', 'outlier'])
if replace == 'median':
    replace = x.debt.median()
elif replace == 'minUpper':
    replace = min([val for (val, vote) in list(zip(data, vote)) if vote == True])
    if replace < data.mean():
        return 'There are outliers lower than the sample mean'
debtNew = []
for i in range(x.shape[0]):
    if x.iloc[i][1] == True:
        debtNew.append(replace)
    else:
        debtNew.append(x.iloc[i][0])

return debtNew

Function Call:

incomeNew = replaceOutlier(df.annual_income, replace='minUpper')

Error:
  x = pd.DataFrame(zip(data, vote), columns=['annual_income', 'outlier'])
  TypeError: data argument can't be an iterator

PS: I understand this has been asked before, but I tried using the techniques however the error still remains


问:
How to loop text of an element in JLabel?
I'm having a problem with loops. How does this loop, loop through different values and display all values on the label, rather than displaying the last value of the array on the label?

Image of code for loop.

答:
This below code is just copied(written) from your screenshot. which has the minor bug.

sinhvien sv = new sinhvien();
sv.setdata("CC",12);
  sv.setdata("CL",14);
   sv.setdata("CCCL",16);

     s1.add(sv);

```

<p>As you have only created one instance of sv and setting the value 3 times.  Value CCCL override all other two previous values.</p>

```sv.setdata("CCCL",16);
```

<p>So, at line </p>

```s1.add(sv);
```

<p>you are actually adding only one instance of sinhvien into the array list.</p>

<p>Debugging: Check the array list size that will give you some clue why you are getting this behaviour. Use the below code after the loop.</p>

<pre class="lang-java prettyprint-override"><code>//Code to get ArrayList size
System.out.println(sv1.size());
</code>```

Whenever adding items into ArrayList make sure each item has a new instance of the sinhvien.

Please try the below code,

```<code>sinhvien sv = new sinhvien();
sv.setdata("CC",12);
sv1.add(sv);

sv = new sinhvien();
sv.setdata("CL",14);
sv1.add(sv);

sv = new sinhvien();
sv.setdata("CCCL",16);
sv1.add(sv);
</code>```

Note: Replace above code inside the jButton1ActionPerormed method and before the for a loop. This is nowhere loop issue. It is assignment issue.

Body:
This below code is just copied(written) from your screenshot. which has the minor bug.

sinhvien sv = new sinhvien();
sv.setdata("CC",12);
  sv.setdata("CL",14);
   sv.setdata("CCCL",16);

     s1.add(sv);

As you have only created one instance of sv and setting the value 3 times.  Value CCCL override all other two previous values.

sv.setdata("CCCL",16);

So, at line

s1.add(sv);

you are actually adding only one instance of sinhvien into the array list.

Debugging: Check the array list size that will give you some clue why you are getting this behaviour. Use the below code after the loop.

//Code to get ArrayList size
System.out.println(sv1.size());

Whenever adding items into ArrayList make sure each item has a new instance of the sinhvien.

Please try the below code,

sinhvien sv = new sinhvien();
sv.setdata("CC",12);
sv1.add(sv);

sv = new sinhvien();
sv.setdata("CL",14);
sv1.add(sv);

sv = new sinhvien();
sv.setdata("CCCL",16);
sv1.add(sv);

Note: Replace above code inside the jButton1ActionPerormed method and before the for a loop. This is nowhere loop issue. It is assignment issue.


问:
How to avoid memory leaks with complex RxJS pipes in Angular 9?
I have this little bit complex pipe structure in my Angular + RxJS app:

remote-data.service.ts:

getAll(url): Observable<any[]> {
  return this.http.get(url, this.options)
    .pipe(map((result: any[]) => result));
}
```

<p><strong>proxy.service.ts:</strong></p>

<pre class="lang-js prettyprint-override"><code>// localDataService use my LocalDataService
// remoteDataService use my RemoteDataService

getAll(model): Observable<any[]> {
  if (model.use_localstorage) {
    return this.localDataService.getAll(model)
      .pipe(map((result: any[]) => result));
  } else {
    return this.remoteDataService.getAll(model.url)
      .pipe(map((result: any[]) => result));
  }
}
</code>```

helper.service.ts:

getAll(model): Observable<any[]> {
  // do some general fancy things...
  return this.proxyService.getAll(model)
      .pipe(map((result: any) => result));
  }
}
```

<p>Then in my <strong>component</strong>:</p>

<pre class="lang-js prettyprint-override"><code>export class MyComponent {
  helperService = new HelperService();
  model = new MyModel();

  getAll() {
    this.helperService.getAll().subscribe((result: any[]) => {
      // parse result
    });
  }
}
</code>```

As you see I build a pipeline from remote data service, proxy service, helper servcice and the component. Of course the reason is to separate each functions from eachother and make my services more reuseable.

My goal is to avoid the memory leaks.

And the question is: if I want to put a take(1) RxJS operator into my pipeline it's enough to put it into the end of pipeline, before the .subscribe() or need to put it every services and component too?

What is the best practice in this case to avoid memory leaks?

答:
There's a common pattern - takeUntil(this.destroy$) should be the latest operator in any pipe before .subscribe call.

class MyClass {
  destroy$ = new Subject();

  ngOnInit() {
    this.stream$.pipe(
      takeUntil(this.destroy$),
    ).subscribe(data => {
      // some logic.
    });
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
```

There's a very nice explanation of all issues and how to solve them to avoid memory leaks: https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f

Body:
I have this little bit complex pipe structure in my Angular + RxJS app:

remote-data.service.ts:

getAll(url): Observable<any[]> {
  return this.http.get(url, this.options)
    .pipe(map((result: any[]) => result));
}

proxy.service.ts:

// localDataService use my LocalDataService
// remoteDataService use my RemoteDataService

getAll(model): Observable<any[]> {
  if (model.use_localstorage) {
    return this.localDataService.getAll(model)
      .pipe(map((result: any[]) => result));
  } else {
    return this.remoteDataService.getAll(model.url)
      .pipe(map((result: any[]) => result));
  }
}

helper.service.ts:

getAll(model): Observable<any[]> {
  // do some general fancy things...
  return this.proxyService.getAll(model)
      .pipe(map((result: any) => result));
  }
}

Then in my component:

export class MyComponent {
  helperService = new HelperService();
  model = new MyModel();

  getAll() {
    this.helperService.getAll().subscribe((result: any[]) => {
      // parse result
    });
  }
}

As you see I build a pipeline from remote data service, proxy service, helper servcice and the component. Of course the reason is to separate each functions from eachother and make my services more reuseable.

My goal is to avoid the memory leaks.

And the question is: if I want to put a take(1) RxJS operator into my pipeline it's enough to put it into the end of pipeline, before the .subscribe() or need to put it every services and component too?

What is the best practice in this case to avoid memory leaks?

Body:
There's a common pattern - takeUntil(this.destroy$) should be the latest operator in any pipe before .subscribe call.

class MyClass {
  destroy$ = new Subject();

  ngOnInit() {
    this.stream$.pipe(
      takeUntil(this.destroy$),
    ).subscribe(data => {
      // some logic.
    });
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

There's a very nice explanation of all issues and how to solve them to avoid memory leaks: https://blog.bitsrc.io/6-ways-to-unsubscribe-from-observables-in-angular-ab912819a78f


问:
Preg_match a string, must containing Letters and numbers
The sentence maybe:
BenQ G2420HDBL 23.6" Wide LCD Monitor

Need to grab the "G2420HDBL" part. The letters and numbers may be in a different order but still remains a string with both letters and numbers present.

答:
```<code>$number = substr($name, 6, strlen($name) - 28);
</code>```


问:
Laravel - file_get_contents() is creating unnecessary uploading file in public folder
```<code>$json_data = file_get_contents(base_path('app/database/fixtures/xyz.json'));
</code>```

Above code is unnecessary copying xyz.json in public folder.

How Can I fix this?????

答:
try it in laravel</p>

```<code>$json_data =File::get(storage_path('app/database/fixtures/xyz.json'));
</code>```

Body:
$json_data = file_get_contents(base_path('app/database/fixtures/xyz.json'));

Above code is unnecessary copying xyz.json in public folder.

How Can I fix this?????

Body:
try it in laravel

$json_data =File::get(storage_path('app/database/fixtures/xyz.json'));


问:
How do I show the name of a page I am on in a Rails application
I have a header as follows

          Home

But I want the name of the current page to be dynamic. For example when I visit the articles page the title should say articles, and The locations pages should say locations.

I am new to Ruby and Rails so this is probably very easy but I don't know how. Thanks in advance!

James

答:
In Your project folder open app/views/layouts/application.html.erb.
This file contains head tag of every page in standard namespace of Your application.
Name of page is inside of title tag. You can change it dynamicly by using <%= %> tag.</p>


问:
Understanding The Modulus Operator %
I understand the Modulus operator in terms of the following expression:

```<code>7 % 5
</code>```

This would return 2 due to the fact that 5 goes into 7 once and then gives the 2 that is left over, however my confusion comes when you reverse this statement to read:

```<code>5 % 7
</code>```

This gives me the value of 5 which confuses me slightly. Although the whole of 7 doesn't go into 5, part of it does so why is there either no remainder or a remainder of positive or negative 2?

If it is calculating the value of 5 based on the fact that 7 doesn't go into 5 at all why is the remainder then not 7 instead of 5?

I feel like there is something I'm missing here in my understanding of the modulus operator.

答:
As you say, the % sign is used to take the modulus (division remainder).

In w3schools' JavaScript Arithmetic page we can read in the Remainder section what I think to be a great explanation

In arithmetic, the division of two integers produces a quotient and a
  remainder.

In mathematics, the result of a modulo operation is the
  remainder of an arithmetic division.

So, in your specific case, when you try to divide 7 bananas into a group of 5 bananas, you're able to create 1 group of 5 (quotient) and you'll be left with 2 bananas (remainder).

If 5 bananas into a group of 7, you won't be able to and so you're left with again the 5 bananas (remainder).

Title: Understanding The Modulus Operator %

Body:
I understand the Modulus operator in terms of the following expression:

7 % 5

This would return 2 due to the fact that 5 goes into 7 once and then gives the 2 that is left over, however my confusion comes when you reverse this statement to read:

5 % 7

This gives me the value of 5 which confuses me slightly. Although the whole of 7 doesn't go into 5, part of it does so why is there either no remainder or a remainder of positive or negative 2?

If it is calculating the value of 5 based on the fact that 7 doesn't go into 5 at all why is the remainder then not 7 instead of 5?

I feel like there is something I'm missing here in my understanding of the modulus operator.


答:
You can use ctype_alnum but there is probably a better way using regexes:

```<code>$str = "BenQ G2420HDBL 23.6";
$pieces = split(' ', $str);
$theStr = '';
foreach($pieces as $piece) {
    if(ctype_alnum($piece)) {
        $theStr = $piece;
        break;
    }
}
</code>```

Title: Preg_match a string, must containing Letters and numbers

Body:
The sentence maybe:
BenQ G2420HDBL 23.6" Wide LCD Monitor

Need to grab the "G2420HDBL" part. The letters and numbers may be in a different order but still remains a string with both letters and numbers present.

Body:
You can use ctype_alnum but there is probably a better way using regexes:

$str = "BenQ G2420HDBL 23.6";
$pieces = split(' ', $str);
$theStr = '';
foreach($pieces as $piece) {
    if(ctype_alnum($piece)) {
        $theStr = $piece;
        break;
    }
}


问:
Promisify a function which returns null
This function returns null and I need to promisify it. but I don't understand this code. Can anyone help with this.</p>

```<code>return iyzipay.payment.create(req, function (err, result) {
    return('result:'+ result + 'error:'+ err);
})
</code>```

答:
Wrap your code in a Promise and call either resolve or reject once the operation is completed.

```<code>return new Promise(function(resolve, reject) {
    iyzipay.payment.create(req, function (err, result) {
        if (err) {
            reject(err)
        } else {
            resolve(result)
        }
    })
})
</code>```

Title: Promisify a function which returns null

Body:
This function returns null and I need to promisify it. but I don't understand this code. Can anyone help with this.

return iyzipay.payment.create(req, function (err, result) {
    return('result:'+ result + 'error:'+ err);
})

Body:
Wrap your code in a Promise and call either resolve or reject once the operation is completed.

return new Promise(function(resolve, reject) {
    iyzipay.payment.create(req, function (err, result) {
        if (err) {
            reject(err)
        } else {
            resolve(result)
        }
    })
})


问:
PayPal sandbox works, production does not work. Can anybody provide a solution?
I've integrated paypal payment in my online store.

When in sandbox mode and using a sandbox paypal account to make a payment, everything works.

When in production mode and using a REAL paypal account to make a payment, the user receives this error on paypal checkout page:

When I try to pay with the same real paypal account on another online store that uses the same paypal method for receiving payments, everything works.

I redirect users to paypal checkout with this code:

```<code><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="here I insert our business email" />
<input type="hidden" name="amount" value="0.1" />
<input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="item_name" value="test" />
<input type="hidden" name="invoice" value="8514" />
<input type="hidden" name="email" value="here I insert customer email" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="charset" value="utf-8" />
<input type="hidden" name="return" value="https://www.ourdomain.com/success.php?orderid=210141&h=03e2f8258d" />
<input type="hidden" name="cancel_return" value="https://www.ourdomain.com/cancel.php?orderid=210141&h=03e2f8258d" />
<input type="hidden" name="notify_url" value="https://www.ourdomain.com/update_paypal.php?orderid=210141&h=03e2f8258d" />
<button class="btn rightSignBig black" type="submit"><span><em>Pay with paypal</em></span></button>
</form>
</code>```

What should I do to be able to receive payments on my business account in production?

答:
The LIVE transactions are being declined by PayPal, for business reasons. For certain types of businesses, credit card companies need certain agreements on file in order to process transactions.

So, the owner of the LIVE PayPal business account needs to contact PayPal's general business support via https://www.paypal.com/smarthelp/contact-us and explain that all customer credit card transactions are being declined due to the type of business, and ask what they can do to resolve the issue.

Body:
I've integrated paypal payment in my online store.

When in sandbox mode and using a sandbox paypal account to make a payment, everything works.

When in production mode and using a REAL paypal account to make a payment, the user receives this error on paypal checkout page:

When I try to pay with the same real paypal account on another online store that uses the same paypal method for receiving payments, everything works.

I redirect users to paypal checkout with this code:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="here I insert our business email" />
<input type="hidden" name="amount" value="0.1" />
<input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="item_name" value="test" />
<input type="hidden" name="invoice" value="8514" />
<input type="hidden" name="email" value="here I insert customer email" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="charset" value="utf-8" />
<input type="hidden" name="return" value="https://www.ourdomain.com/success.php?orderid=210141&h=03e2f8258d" />
<input type="hidden" name="cancel_return" value="https://www.ourdomain.com/cancel.php?orderid=210141&h=03e2f8258d" />
<input type="hidden" name="notify_url" value="https://www.ourdomain.com/update_paypal.php?orderid=210141&h=03e2f8258d" />
<button class="btn rightSignBig black" type="submit">Pay with paypal</button>
</form>

What should I do to be able to receive payments on my business account in production?


问:
Hi to everyone, I'm stuck with this problem in SQL: mysql gives me always syntax error at line 4 but I don't really know what it may be
Here it's the code:

```<code>CREATE TRIGGER inserisci_richiesta_noID AFTER INSERT ON Richiesta
FOR EACH ROW
BEGIN
    IF (NEW.ID_Cliente == NULL AND (NEW.Email NOT IN (SELECT Email FROM Utente))) THEN
        INSERT INTO Utente(ID, Nome, Cognome, Email, Telefono, ID_Livello_accesso)
        VALUES (NULL, 'Generato', 'Automaticamnete', NEW.Email, NEW.Telefono, 1);
        UPDATE Richiesta
        SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = :NEW.Email);
    ELSE NEW.ID_Cliente == NULL AND NEW.Email IN (SELECT Email FROM Utente;) THEN
        UPDATE Richiesta
        SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = NEW.Email);
    END IF;
END;
</code>```

it gives me this error:

1064 - 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 '== NULL AND (NEW.Email NOT IN (SELECT Email FROM Utente))) THEN
          INSERT INTO U' at line 4

答:
This is the code</p>

```<code>DELIMITER $$

CREATE TRIGGER inserisci_richiesta_noID AFTER INSERT ON Richiesta
FOR EACH ROW
BEGIN
 IF (NEW.ID_Cliente IS NULL AND (NEW.Email NOT IN (SELECT Email FROM Utente))) THEN
    INSERT INTO Utente(ID, Nome, Cognome, Email, Telefono, ID_Livello_accesso)
    VALUES (NULL, 'Generato', 'Automaticamnete', NEW.Email, NEW.Telefono, 1)
    UPDATE Richiesta
    SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = NEW.Email);
ELSE IF (NEW.ID_Cliente IS NULL AND NEW.Email IN (SELECT Email FROM Utente)) THEN
    UPDATE Richiesta
    SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = NEW.Email);
END IF;
END$$

 DELIMITER ;
</code>```

Body:
Here it's the code:

CREATE TRIGGER inserisci_richiesta_noID AFTER INSERT ON Richiesta
FOR EACH ROW
BEGIN
    IF (NEW.ID_Cliente == NULL AND (NEW.Email NOT IN (SELECT Email FROM Utente))) THEN
        INSERT INTO Utente(ID, Nome, Cognome, Email, Telefono, ID_Livello_accesso)
        VALUES (NULL, 'Generato', 'Automaticamnete', NEW.Email, NEW.Telefono, 1);
        UPDATE Richiesta
        SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = :NEW.Email);
    ELSE NEW.ID_Cliente == NULL AND NEW.Email IN (SELECT Email FROM Utente;) THEN
        UPDATE Richiesta
        SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = NEW.Email);
    END IF;
END;

it gives me this error:

1064 - 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 '== NULL AND (NEW.Email NOT IN (SELECT Email FROM Utente))) THEN
          INSERT INTO U' at line 4

Body:
This is the code

DELIMITER $$

CREATE TRIGGER inserisci_richiesta_noID AFTER INSERT ON Richiesta
FOR EACH ROW
BEGIN
 IF (NEW.ID_Cliente IS NULL AND (NEW.Email NOT IN (SELECT Email FROM Utente))) THEN
    INSERT INTO Utente(ID, Nome, Cognome, Email, Telefono, ID_Livello_accesso)
    VALUES (NULL, 'Generato', 'Automaticamnete', NEW.Email, NEW.Telefono, 1)
    UPDATE Richiesta
    SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = NEW.Email);
ELSE IF (NEW.ID_Cliente IS NULL AND NEW.Email IN (SELECT Email FROM Utente)) THEN
    UPDATE Richiesta
    SET ID_Cliente = (SELECT ID FROM Cliente WHERE Email = NEW.Email);
END IF;
END$$

 DELIMITER ;


问:
Stylelint rule to value-keyword-case to ignore camelCase variables
I am using stylelint and I have a custom color variables used in several properties such as border, background, color.

Example:

```<code>border: 1px solid t(lightGray);
background-color: t(lightBlue);
background-color: var(--lightBlue);
</code>```

When I run stylelint I get the error, Expected "lightBlue" value-keyword-case to be "lightblue".

How do I create a regex to ignore any variable inside t() or var(--) or ignore camelCasing in values?

https://stylelint.io/user-guide/rules/value-keyword-case#ignorekeywords-regex-regex-non-regex

Current rules:

```<code>{
    "extends": "stylelint-config-standard",
    "rules": {
        "indentation": "tab",
        "string-quotes": "double",
        "no-duplicate-selectors": true,
        "color-hex-case": "upper",
        "color-named": "always-where-possible",
        "selector-combinator-space-after": "always",
        "selector-attribute-operator-space-before": "always",
        "selector-attribute-operator-space-after": "always",
        "declaration-block-trailing-semicolon": "always",
        "declaration-colon-space-before": "never",
        "declaration-colon-space-after": "always",
        "number-leading-zero": "always",
        "comment-empty-line-before": "always",
        "rule-empty-line-before": "always-multi-line",
        "selector-pseudo-element-colon-notation": "double",
        "media-feature-parentheses-space-inside": "always",
        "value-keyword-case": "lower"
    }
}
</code>```

TIA

答:
I just stumbled across the same problem. You might try something like this:

```<code>{
  "rules": {
    "value-keyword-case": ["lower", {
      ignoreFunctions: ["t", "var"]
    }]
  }
}
</code>```

It seems like they updated their docs recently :)

https://stylelint.io/user-guide/rules/value-keyword-case#ignorekeywords-regex-regex-non-regex

Body:
I am using stylelint and I have a custom color variables used in several properties such as border, background, color.

Example:

border: 1px solid t(lightGray);
background-color: t(lightBlue);
background-color: var(--lightBlue);

When I run stylelint I get the error, Expected "lightBlue" value-keyword-case to be "lightblue".

How do I create a regex to ignore any variable inside t() or var(--) or ignore camelCasing in values?

https://stylelint.io/user-guide/rules/value-keyword-case#ignorekeywords-regex-regex-non-regex

Current rules:

{
    "extends": "stylelint-config-standard",
    "rules": {
        "indentation": "tab",
        "string-quotes": "double",
        "no-duplicate-selectors": true,
        "color-hex-case": "upper",
        "color-named": "always-where-possible",
        "selector-combinator-space-after": "always",
        "selector-attribute-operator-space-before": "always",
        "selector-attribute-operator-space-after": "always",
        "declaration-block-trailing-semicolon": "always",
        "declaration-colon-space-before": "never",
        "declaration-colon-space-after": "always",
        "number-leading-zero": "always",
        "comment-empty-line-before": "always",
        "rule-empty-line-before": "always-multi-line",
        "selector-pseudo-element-colon-notation": "double",
        "media-feature-parentheses-space-inside": "always",
        "value-keyword-case": "lower"
    }
}

TIA

Body:
I just stumbled across the same problem. You might try something like this:

{
  "rules": {
    "value-keyword-case": ["lower", {
      ignoreFunctions: ["t", "var"]
    }]
  }
}

It seems like they updated their docs recently :)

https://stylelint.io/user-guide/rules/value-keyword-case#ignorekeywords-regex-regex-non-regex


问:
Replacing an old LOCAL notification with a new one
The application sends notifications to the user. I need a new notification to delete the old one. Not that the old notifications were deleted when you log into the application. Namely, so that a new notification replaces the old one. For example, the application sent notification_1, and after an hour notification_2. Thus, you only need the user to see notifications_2.

now i do so

```<code>var dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
     dateComponents.second! += 20
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 0", notificationId: "1")
    for i in 1...2 {
        dateComponents.second! += 1
        createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test \(i)", notificationId: "2")
    }
    dateComponents.minute! += 2
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 00", notificationId: "2")
</code>```

and function

```<code>    func createLocalPush(dateMatching: DateComponents, alertTitle: String, alertBody: String, notificationId: String) {

    let content = UNMutableNotificationContent()
    content.body = alertBody
    content.badge = 1
    content.sound = .default

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateMatching, repeats: false)

    let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)
    notificationCenter.add(request) { (error) in
        if let error = error {
            print(#function, "error add notification", error.localizedDescription)
        } else {
            print(#function, "add request ok")
        }
    }
}
</code>```

but the application only gives pushes "test_0" and "test_00". Why does the application skip push "test_1" and "test_2", and not replace them with each other? And how to make the following remove the coming?

答:
```<code>var dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
     dateComponents.second! += 20
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 0", notificationId: "1")
    for i in 1...2 {
        dateComponents.second! += 1
        createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test \(i)", notificationId: "2")
    }
    dateComponents.minute! += 2
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 00", notificationId: "2")
</code>```

In the for loop above you create notifications with ID 2. So each one you create will overwrite the previous one.

Then you have

```<code>createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 00", notificationId: "2")
</code>```

Which replaces the last one you created in your for loop.

Looking at your code I would only expect to receive 2 notifications... 1 & 2.

If you change your for loop to something like

```<code>for i in 1...2 {
   dateComponents.second! += 1
   createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test \(i)", notificationId: "test_\(i)")
}
</code>```

Then all of them would show

Body:
The application sends notifications to the user. I need a new notification to delete the old one. Not that the old notifications were deleted when you log into the application. Namely, so that a new notification replaces the old one. For example, the application sent notification_1, and after an hour notification_2. Thus, you only need the user to see notifications_2.

now i do so

var dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
     dateComponents.second! += 20
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 0", notificationId: "1")
    for i in 1...2 {
        dateComponents.second! += 1
        createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test \(i)", notificationId: "2")
    }
    dateComponents.minute! += 2
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 00", notificationId: "2")

and function

    func createLocalPush(dateMatching: DateComponents, alertTitle: String, alertBody: String, notificationId: String) {

    let content = UNMutableNotificationContent()
    content.body = alertBody
    content.badge = 1
    content.sound = .default

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateMatching, repeats: false)

    let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)
    notificationCenter.add(request) { (error) in
        if let error = error {
            print(#function, "error add notification", error.localizedDescription)
        } else {
            print(#function, "add request ok")
        }
    }
}

but the application only gives pushes "test_0" and "test_00". Why does the application skip push "test_1" and "test_2", and not replace them with each other? And how to make the following remove the coming?

Body:
var dateComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
     dateComponents.second! += 20
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 0", notificationId: "1")
    for i in 1...2 {
        dateComponents.second! += 1
        createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test \(i)", notificationId: "2")
    }
    dateComponents.minute! += 2
    createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 00", notificationId: "2")

In the for loop above you create notifications with ID 2. So each one you create will overwrite the previous one.

Then you have

createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test 00", notificationId: "2")

Which replaces the last one you created in your for loop.

Looking at your code I would only expect to receive 2 notifications... 1 & 2.

If you change your for loop to something like

for i in 1...2 {
   dateComponents.second! += 1
   createLocalPush(dateMatching: dateComponents, alertTitle: "test", alertBody: "test \(i)", notificationId: "test_\(i)")
}

Then all of them would show


问:
Is there a Matlab equivalent to Python's xarray?
I've been flicking back and forth between Python and Matlab for various geoscience projects and generally find the structure of Matlab easier for modelling purposes, however, Python has some really neat packages that I can't seem to find equivalents of in Matlab.

Does anyone know if there is a Matlab equivalent to xarray (xarray.pydata.org)? This would be super helpful for organising and indexing my full data set in 3-dimensional space.

I'm looking for something that allows Matlab arrays to be indexed and stacked together into one object.

Cheers

答:
Have you checked cell in MatLab?
It is a collection of matrices where you can access them with index.

```<code>num = 5;
your_cell = cell(num,1);
your_cell{i} = your_mat
</code>```

Body:
Have you checked cell in MatLab?
It is a collection of matrices where you can access them with index.

num = 5;
your_cell = cell(num,1);
your_cell{i} = your_mat