问:
Multiple select tag under one id
I am appending multiple select element inside an id called append like the following.

```<code><div id="append">
    <select name="color[]" id="colorsData1" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>

    <select name="color[]" id="colorsData2" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>
    <select name="color[]" id="colorsData3" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>
</div>
</code>```

Now, to prevent the data duplication, I want to use condition if the user selects color red and as the color red has already been selected before either in colorsData1 or colorsData2, I want to alert user. How do I check if the any of the selected options before matches the current selected option?

The reason for using multiple select rather than checkboxes is because I am making an e-commerce website, actually. And for the stock management I am cloning div  where vendor can upload images according to the colors they select. I am also appending upload field if there is no color duplication. If the selected option is not duplicate my whole div would look like this.

And, the reason for me to check the colour duplication is not to alert the vendor but for myself. Right after the vendor makes a color selection, if the colour has already been selected before I want to divert my code to else condition where there is not code to append the fileupload field. See, vendor can have shoes of Nike of different sizes with same colors. Sizes does not matter on online shopping as they cannot tell them if it fits to them by looking at the image. So, I am allowing vendor to upload products with same color but different sizes for stock management.
There is a button with id addnew and following is my jquery code after clicking on that button:

```<code>$('#addnew').on('click', function(){
        num = num+1;
        let html = '';
        html = '<div class="form-group row div"><div class="col-md-2 col-lg-2"><select name="color[]" id="colorsData'+num+'" class="form-control selectebox"><option>--Select any One--</option></select></div><div class="col-md-3 col-lg-3"><select class="select2 form-control" name="size[]" multiple="multiple" id="sizesData'+num+'"></select></div><div class="col-md-2 col-lg-2"><input type="number" placeholder="availability" name="stock" class="form-control h-100"></div><div class="col-md-2 col-lg-2"><input class="form-control h-100" value="" type="text" name="price[]" placeholder="price"></div><div class="col-md-3 col-lg-3"><input class="form-control h-100" value="" type="text" name="discount[]" placeholder="discount"></div></div>';
        $('#append').append(html);
        if(num == 1){
            html = '<div class="form-group row image"><div class="col-md-12 col-lg-12" style="display:inherit"><a href="/vendor/filemanager/dialog.php?type=4&field_id=thumbnail'+num+'&descending=1&sort_by=date&lang=undefined&akey=061e0de5b8d667cbb7548b551420eb821075e7a6" class="btn iframe-btn btn-primary" type="button"><i class="fa fa-picture-o"></i> Choose</a><input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]"></div></div>';
            $('#append').append(html);
            responsive_filemanager_callback('thumbnail'+num);
        } else {
            var selected_color = [];
                $(".selectebox").on('change',function(){  console.log(selected_color)
                if(jQuery.inArray( this.value, selected_color)){
                    alert('duplicate color')
                } else {
                    html = '<div class="form-group row image"><div class="col-md-12 col-lg-12" style="display:inherit"><a href="/vendor/filemanager/dialog.php?type=4&field_id=thumbnail'+num+'&descending=1&sort_by=date&lang=undefined&akey=061e0de5b8d667cbb7548b551420eb821075e7a6" class="btn iframe-btn btn-primary" type="button"><i class="fa fa-picture-o"></i> Choose</a><input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]"></div></div>';
                    $('#append').append(html);
                    responsive_filemanager_callback('thumbnail'+num);
                }
                selected_color.push($(this).val());
            });
        }

    })
</code>```

and following is my code on HTML

```<code><div class="page-body">
<form action="{{ route('products.store') }}" method="POST">
    @csrf
    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>What you're selling</h5>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="name" class="block">Product Name *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <input name="name" type="text" class="required form-control" id="name">
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="slug" class="block">Product Slug *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <input name="slug" type="text" class="required form-control" id="slug">
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="category-2" class="block">Category *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <select name="category_id" id="category_id" class="requires form-control">
                                        <option selected disabled>--Product Category--</option>
                                        <option value="">Hair</option>
                                        <option value="">Perfumes</option>
                                        <option value="">Shoes</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="brand-2" class="block">Brand *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <select name="brand_id" id="brand_id" class="requires form-control">
                                        <option selected disabled>--Product Brand--</option>
                                        <option value="">Nike</option>
                                        <option value="">Zivah</option>
                                        <option value="">Caliber</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>General Information</h5>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="description-2" class="block">Product description *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <textarea name="description" id="description" rows="10" class="form-control editor"></textarea>
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="description-2" class="block">Video URL </label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <input type="url" name="video" placeholder="video url" class="form-control">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>SKU Information</h5>
                    <br>
                    <span class="hint">Click on the plus button to add the SKU of the product.</span>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="col-12">
                            <div id="append"></div>
                            <div class="form-group text-center">
                                <button type="button" class="btn btn-primary" id="addnew"><span class="icofont icofont-ui-add"></span></button>
                                <button type="button" class="btn btn-danger" id="delete"><span class="icofont icofont-ui-delete"></span></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <input type="submit" name="submit" value="Save Changes" class="btn btn-success pull-right" id="submit">
        </div>
    </div>

</form>
</code>```

答:
Add CSS class colour to every dropdown class="form-control color"

Add unique value for each option in the dropdown <option value="1" >Red</option>

Add on change event listener all the dropdown - selectcolor(this).

"selectcolor" function will check the duplication.

<!DOCTYPE html>

  <select name="color[]" onchange="selectcolor(this);" id="colorsData1" class="form-control color">
   <option value="" >--Select any One--</option>
   <option value="1" >Red</option>
   <option value="2" >Yellow</option>
   <option value="3">Blue</option>
   <option value="4">Black</option>
  </select>

  <select name="color[]" id="colorsData2" class="form-control color"  onchange="selectcolor(this);" >

    <option  value="" >--Select any One--</option>
   <option value="1" >Red</option>
   <option value="2" >Yellow</option>
   <option value="3">Blue</option>
   <option value="4">Black</option>
  </select>
  <select name="color[]" id="colorsData3" class="form-control color"  onchange="selectcolor(this);" >

   <option  value=""  >--Select any One--</option>
   <option value="1" >Red</option>
   <option value="2" >Yellow</option>
   <option value="3">Blue</option>
   <option value="4">Black</option>
  </select>

```

Title: Multiple select tag under one id

Body:
I am appending multiple select element inside an id called append like the following.

    <select name="color[]" id="colorsData1" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>

    <select name="color[]" id="colorsData2" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>
    <select name="color[]" id="colorsData3" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>

Now, to prevent the data duplication, I want to use condition if the user selects color red and as the color red has already been selected before either in colorsData1 or colorsData2, I want to alert user. How do I check if the any of the selected options before matches the current selected option?

The reason for using multiple select rather than checkboxes is because I am making an e-commerce website, actually. And for the stock management I am cloning div  where vendor can upload images according to the colors they select. I am also appending upload field if there is no color duplication. If the selected option is not duplicate my whole div would look like this.

And, the reason for me to check the colour duplication is not to alert the vendor but for myself. Right after the vendor makes a color selection, if the colour has already been selected before I want to divert my code to else condition where there is not code to append the fileupload field. See, vendor can have shoes of Nike of different sizes with same colors. Sizes does not matter on online shopping as they cannot tell them if it fits to them by looking at the image. So, I am allowing vendor to upload products with same color but different sizes for stock management.
There is a button with id addnew and following is my jquery code after clicking on that button:

$('#addnew').on('click', function(){
        num = num+1;
        let html = '';
        html = '

<select name="color[]" id="colorsData'+num+'" class="form-control selectebox"><option>--Select any One--</option></select>

<select class="select2 form-control" name="size[]" multiple="multiple" id="sizesData'+num+'"></select>

<input type="number" placeholder="availability" name="stock" class="form-control h-100">

<input class="form-control h-100" value="" type="text" name="price[]" placeholder="price">

<input class="form-control h-100" value="" type="text" name="discount[]" placeholder="discount">

';
        $('#append').append(html);
        if(num == 1){
            html = '

 Choose<input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]">

';
            $('#append').append(html);
            responsive_filemanager_callback('thumbnail'+num);
        } else {
            var selected_color = [];
                $(".selectebox").on('change',function(){  console.log(selected_color)
                if(jQuery.inArray( this.value, selected_color)){
                    alert('duplicate color')
                } else {
                    html = '

 Choose<input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]">

';
                    $('#append').append(html);
                    responsive_filemanager_callback('thumbnail'+num);
                }
                selected_color.push($(this).val());
            });
        }

    })

and following is my code on HTML

<form action="{{ route('products.store') }}" method="POST">
    @csrf

What you're selling

                                    Product Name *

                                    <input name="name" type="text" class="required form-control" id="name">

                                    Product Slug *

                                    <input name="slug" type="text" class="required form-control" id="slug">

                                    Category *

                                    <select name="category_id" id="category_id" class="requires form-control">
                                        <option selected disabled>--Product Category--</option>
                                        <option value="">Hair</option>
                                        <option value="">Perfumes</option>
                                        <option value="">Shoes</option>
                                    </select>

                                    Brand *

                                    <select name="brand_id" id="brand_id" class="requires form-control">
                                        <option selected disabled>--Product Brand--</option>
                                        <option value="">Nike</option>
                                        <option value="">Zivah</option>
                                        <option value="">Caliber</option>
                                    </select>

General Information

                                    Product description *

                                    <textarea name="description" id="description" rows="10" class="form-control editor"></textarea>

                                    Video URL

                                    <input type="url" name="video" placeholder="video url" class="form-control">

SKU Information

                    Click on the plus button to add the SKU of the product.

                                <button type="button" class="btn btn-primary" id="addnew"></button>
                                <button type="button" class="btn btn-danger" id="delete"></button>

            <input type="submit" name="submit" value="Save Changes" class="btn btn-success pull-right" id="submit">

</form>

Body:
Add CSS class colour to every dropdown class="form-control color"

Add unique value for each option in the dropdown <option value="1" >Red</option>

Add on change event listener all the dropdown - selectcolor(this).

"selectcolor" function will check the duplication.

<!DOCTYPE html>
<html>
<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script>
  function selectcolor(a) {
   console.log(a);
   var data_list = new Set();
   $(".color").each(function(i,e){
    let val = $(e).val();
    if(val != ""){
     if(data_list.has(val)){ // checking is already selected
      alert("Already exist");
      $(e).val(""); // resetting the drop down
     }else{
      data_list.add(val)
     }
    }

   });
  }
   onchange="selectcolor(this);"
 </script>
 <div id="append">
  <select name="color[]" onchange="selectcolor(this);" id="colorsData1" class="form-control color">
   <option value="" >--Select any One--</option>
   <option value="1" >Red</option>
   <option value="2" >Yellow</option>
   <option value="3">Blue</option>
   <option value="4">Black</option>
  </select>

  <select name="color[]" id="colorsData2" class="form-control color"  onchange="selectcolor(this);" >

    <option  value="" >--Select any One--</option>
   <option value="1" >Red</option>
   <option value="2" >Yellow</option>
   <option value="3">Blue</option>
   <option value="4">Black</option>
  </select>
  <select name="color[]" id="colorsData3" class="form-control color"  onchange="selectcolor(this);" >

   <option  value=""  >--Select any One--</option>
   <option value="1" >Red</option>
   <option value="2" >Yellow</option>
   <option value="3">Blue</option>
   <option value="4">Black</option>
  </select>
 </div>
</body>
</html>


来源: stackexchange

问:
Redux Toolkit and Axios
I'm using Redux Toolkit to connect to an API with Axios.
I'm using the following code:

```<code>const products = createSlice({
    name: "products",
    initialState: {
        products[]
    },
    reducers: {
        reducer2: state => {
            axios
                .get('myurl')
                .then(response => {
                    //console.log(response.data.products);
                    state.products.concat(response.data.products);
            })

        }
    }
});
</code>```

axios is connecting to the API because the commented line to print to the console is showing me the data. However, the  state.products.concat(response.data.products); is throwing the following error:

TypeError: Cannot perform 'get' on a proxy that has been revoked

Is there any way to fix this problem?

答:
It is happening because your reducer function is not a pure function, it should not be having any asynchronous calls.

something like this should work. it will fix the error you are getting

```<code>const products = createSlice({
    name: "products",
    initialState: {
        products: []
    },
    reducers: {
        reducer2: (state, { payload }) => {
                return { products: [...state.products, ...payload]}
         })

      }
    }
});
</code>```

and api should be called outside

```<code>const fetchProducts = () => {

   axios.get('myurl')
     .then(response => {
        //console.log(response.data.products);
        store.dispatch(products.actions.reducer2(response.data.products))
   })
};
</code>```

PS: haven't tried running above code, you may have to make modifications as per your need.

ContentLicense: CC BY-SA 4.0

Title: Redux Toolkit and Axios

Body:
I'm using Redux Toolkit to connect to an API with Axios.
I'm using the following code:

const products = createSlice({
    name: "products",
    initialState: {
        products[]
    },
    reducers: {
        reducer2: state => {
            axios
                .get('myurl')
                .then(response => {
                    //console.log(response.data.products);
                    state.products.concat(response.data.products);
            })

        }
    }
});

axios is connecting to the API because the commented line to print to the console is showing me the data. However, the  state.products.concat(response.data.products); is throwing the following error:

TypeError: Cannot perform 'get' on a proxy that has been revoked

Is there any way to fix this problem?

Body:
It is happening because your reducer function is not a pure function, it should not be having any asynchronous calls.

something like this should work. it will fix the error you are getting

const products = createSlice({
    name: "products",
    initialState: {
        products: []
    },
    reducers: {
        reducer2: (state, { payload }) => {
                return { products: [...state.products, ...payload]}
         })

      }
    }
});

and api should be called outside

const fetchProducts = () => {

   axios.get('myurl')
     .then(response => {
        //console.log(response.data.products);
        store.dispatch(products.actions.reducer2(response.data.products))
   })
};

PS: haven't tried running above code, you may have to make modifications as per your need.


问:
Explicit line joining in Python
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

```<code>file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))
</code>```

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

答:
Use string addition</p>

```<code>>>> s = 'a'
>>> s += 'b'
>>> s
'ab'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Explicit line joining in Python

Body:
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:

file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''

 for line in scanlines:
    if line.startswith('>from'):
         continue
    if line.startswith('*'):
        continue
    string.join(line.rstrip('\n'))

The output of this code is as follows:

abc

def

ghi

Is there a way to join these physical lines into one logical line, e.g:

abcdefghi

Basically, how can I concatenate multiple strings into one large string?

If I was reading from a file with very long strings is there the risk of an overflow by concatenating multiple physical lines into one logical line?

Body:
Use string addition

>>> s = 'a'
>>> s += 'b'
>>> s
'ab'


问:
Windows Process Activation Service Error 2:The system cannot find the file specified
IIS on my development computer stopped working.  I just installed the latest update to windows 10 (1803) and now when I try to start the "Windows Process Activation Service" I get an "Windows could not start the Windows Process Activation Service on Local computer.  Error 2: The System cannot find the file specified" error.  Things I have already tried:

Reinstalled IIS and Windows Process Activation Service, several times

I verified that I do have a "C:\inetpub\temp\appPools" folder

Not sure what to do next.

答:
I had this same problem after installing the Windows 10 1909 update and the nanosetup variable was NOT in the registry. I ended up doing a variation of Sascha's fix.

I took ownership and gave administrators full control of the MachineKeys folder in C:\ProgramData\Microsoft\Crypto\RSA. Then I removed the 3 files in Machinekeys that begin with:

d6d986f09a1ee04e24c949879fdb506c_*

76944fb33636aeddb9590521c2e8815a_*

6de9cb26d2b98c01ec4e9e8b34824aa2_*

The Windows Process Activation Service (WAS) started as expected.


问:
How do I store Firestore data in a variable that I can manipulate in Swift/Xcode?
Let's say I have a variable for integers called currentShells

```<code>        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")

                let data = document.data()

                currentShells = data!["Shells"]! as! Int
            }
        }
        print(currentShells)
</code>```

When I print out the variable, I am unable to. Swift is forcing me to add "self.currentShells" in front of the query but it does not update the variable as a result. How do I query data from my Firestore database and use it in swift?

EDIT: For more context, I want to take the current value in currentShells (which I want to query from my Firestore) and add a fixed integer to that amount and update it into my database

答:
As Doug Stevenson said, getDocument is executed asynchronously. That means

```<code>print(currentShells)
</code>```

can (and mostly will) be executed before

```<code>currentShells = data...
</code>```

is.
Changing your code to

```<code>docRef.getDocument { (document, error) in
   if let document = document, document.exists {
      let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
      print("Document data: \(dataDescription)")

      let data = document.data()

      currentShells = data!["Shells"]! as! Int
      print("after update: \(currentShells)")
   }
}
print("probably before update: \(currentShells)")
</code>```

should print your updated data.

Advice

If you aren’t 100% sure that an optional is set and of a certain type, you should not use implicit unwrapping. This can easily lead to crashes!
It is safer to use guard or if let:

```<code>if let data = data, let shells = data["Shells"] as? Int {
    currentShells = shells
}
</code>```

Edit

To execute other functions with new value of currentShells:

- if you need to execute same function every time currentShells is updated, update your var:

```<code>var currentShells: Int {
   didSet {
      yourFunc(currentShells)
   }
}
</code>```

- otherwise, pass a completion block when calling the function to update currentShells:

```<code>func getShells(completion: @escaping ((Int) -> ())) {
   ...
   docRef.getDocument { ...
      if let document ... {
         ...
         currentShells = ...
         completion(currentShells)
      }
   }
}
</code>```

Body:
Let's say I have a variable for integers called currentShells

        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")

                let data = document.data()

                currentShells = data!["Shells"]! as! Int
            }
        }
        print(currentShells)

When I print out the variable, I am unable to. Swift is forcing me to add "self.currentShells" in front of the query but it does not update the variable as a result. How do I query data from my Firestore database and use it in swift?

EDIT: For more context, I want to take the current value in currentShells (which I want to query from my Firestore) and add a fixed integer to that amount and update it into my database

Body:
As Doug Stevenson said, getDocument is executed asynchronously. That means

print(currentShells)

can (and mostly will) be executed before

currentShells = data...

is.
Changing your code to

docRef.getDocument { (document, error) in
   if let document = document, document.exists {
      let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
      print("Document data: \(dataDescription)")

      let data = document.data()

      currentShells = data!["Shells"]! as! Int
      print("after update: \(currentShells)")
   }
}
print("probably before update: \(currentShells)")

should print your updated data.

Advice

If you aren’t 100% sure that an optional is set and of a certain type, you should not use implicit unwrapping. This can easily lead to crashes!
It is safer to use guard or if let:

if let data = data, let shells = data["Shells"] as? Int {
    currentShells = shells
}

Edit

To execute other functions with new value of currentShells:

- if you need to execute same function every time currentShells is updated, update your var:

var currentShells: Int {
   didSet {
      yourFunc(currentShells)
   }
}

- otherwise, pass a completion block when calling the function to update currentShells:

func getShells(completion: @escaping ((Int) -> ())) {
   ...
   docRef.getDocument { ...
      if let document ... {
         ...
         currentShells = ...
         completion(currentShells)
      }
   }
}


问:
Request Body of IBM Watson Assistant for webhook
I'm creating a bot using IBM Watson Assistant. I am trying to use a webhook, but don't know the format of the POST request JSON/HTML which is sent to the webhook.

My case study is a shop where user can pre-order. I want to send the order details to my back-end server and give the user a reference number for the pre-order. I found nothing in the documentation about what POST request format is sent from IBM Watson Assistant and in what format response should be returned.

I know IBM Watson Assistant does not require a particular response format. It allows the developer to manipulate the response as the developer wants.

答:
IBM Watson Assistant has a documented API. There are the recommended V2 Assistant API which can be used to create session and then send messages. The older V1 Assistant API has more functions and is deeper into the system. Both APIs can be used to write chatbots.

If you mean a Webhook as the Watson Assistant feature to reach out from a dialog node to an external service, the process is the following:

in the global configuration, you define the URL and the header

for a dialog node, you enable webhooks, then define the key / value pairs that are sent as payload. They can differ by dialog node.

Typically, the expected result is JSON data because it is the easiest to process.

This IBM Cloud Solution tutorial on building a Slack bot with Watson Assistant uses webhooks to call out to a Db2 database. The code is available in a GitHub repo.


问:
How to recycle an app pool on a remote machine using the command line
I have the following in a vbs file that i am trying to run from the command line:

```<code>strServerName = "ServerName"
strAppPoolName = "DefaultAppPool"
set objAppPools = GetObject("IIS://" & strServerName
                                  & "/w3svc/AppPools/" & strAppPoolName & "")
objAppPools.Recycle()
</code>```

And yet when I run the vbs from cmd line i get the following error:

Microsoft VBScript runtime error: ActiveX component can't create object: 'Get Object'_

I am running XP on my local machine, and the remote machine has IIS 7.

How can I get this to work?

答:
Following commands worked for me after trying everything !

cd %windir%\system32\inetsrv

appcmd.exe stop site /site.name:"test1.com"

appcmd.exe start site /site.name:"test1.com"

Obviously before these, you will run some ssh remote command as well

Body:
I have the following in a vbs file that i am trying to run from the command line:

strServerName = "ServerName"
strAppPoolName = "DefaultAppPool"
set objAppPools = GetObject("IIS://" & strServerName
                                  & "/w3svc/AppPools/" & strAppPoolName & "")
objAppPools.Recycle()

And yet when I run the vbs from cmd line i get the following error:

Microsoft VBScript runtime error: ActiveX component can't create object: 'Get Object'_

I am running XP on my local machine, and the remote machine has IIS 7.

How can I get this to work?


问:
python unable to extract protocol from ethernet frame 'struct.error: unpack requires a buffer of 20 bytes'
I m using python to extract a procol(udp,tcp) from an ip datagram.
But my problem is to unpack the data I get from ethernet frame.
I use this function for that

```<code>def ipv4_head(data):
 version_h = data[0]
 version = version_h >> 4
 header_length = (version_h & 15) * 4
 ttl, proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])
 data = raw_data[header_length:]
 return version, header_length, ttl, proto, src, target, data
</code>```

My problem is this line '''

struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])

I have an error

struct.error: unpack requires a buffer of 20 bytes

I tried a many thinks, this one too give the same result

struct.unpack("!BBHHHBBH4s4s", raw_data)

with an other function but is still the same

```<code>def ipv4_head(raw_data):
  store=struct.unpack("!BBHHHBBH4s4s", raw_data)
  src_ip=socket.inet_ntoa(store[8])
  dst_ip=socket.inet_ntoa(store[9])
  protocol=store[6]

  return src_ip,dst_ip, protocol
</code>```

But it's the same, I use python 3.

I'm interested too, to bypass the struct.unpack by using another method.
A many days I'm strugling with this error but I found nothing in internet.

Thanks in advance guys

答:
The error is telling you that your buffer (the second argument) is not 20 bytes in length.

Can you try print(len(raw_data[:20]))?  If raw_data is shorter than 20 bytes, your expression won't be long enough.

Body:
I m using python to extract a procol(udp,tcp) from an ip datagram.
But my problem is to unpack the data I get from ethernet frame.
I use this function for that

def ipv4_head(data):
 version_h = data[0]
 version = version_h >> 4
 header_length = (version_h & 15) * 4
 ttl, proto, src, target = struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])
 data = raw_data[header_length:]
 return version, header_length, ttl, proto, src, target, data

My problem is this line '''

struct.unpack('! 8x B B 2x 4s 4s', raw_data[:20])

I have an error

struct.error: unpack requires a buffer of 20 bytes

I tried a many thinks, this one too give the same result

struct.unpack("!BBHHHBBH4s4s", raw_data)

with an other function but is still the same

def ipv4_head(raw_data):
  store=struct.unpack("!BBHHHBBH4s4s", raw_data)
  src_ip=socket.inet_ntoa(store[8])
  dst_ip=socket.inet_ntoa(store[9])
  protocol=store[6]

  return src_ip,dst_ip, protocol

But it's the same, I use python 3.

I'm interested too, to bypass the struct.unpack by using another method.
A many days I'm strugling with this error but I found nothing in internet.

Thanks in advance guys


问:
How to convert the graph to list of all path using adjacency matrix via networkx?
I'm trying to use the networkx library from python to find all paths from my data set in the form of dataframe as I have attached the captured screen from what I have done.

according to the network graph, i would like to list all paths from this network then i have tried it with this code but it's not working.

```<code>from functools import partial
all_paths = partial(nx.all_simple_paths, graph)
all_paths
for x in partial(nx.all_simple_paths, graph):
    print(x)
</code>```

the example of the expected result will be something like this

```<code>[[1, 2, 5], [1, 2, 5, 16]]
</code>```

any suggestion?

答:
According to the doc, all_simple_paths find all paths between two given nodes, which are missing in your code. And I think you may misunderstand what partial does. From my understanding, partial repeats executing the function (1st argument) multiple times (2nd argument).

One way to find all paths in the network is to find all possible node pairs and then the paths connecting the pairs.

Example:

```<code>from itertools import combinations
import numpy as np
import networkx as nx

a = np.array([
    [0, 1, 0, 1, 0, 0],
    [1, 0, 1, 0, 0 ,0],
    [0, 1, 0, 1, 0, 0],
    [1, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0 ,1, 0]
])
g = nx.from_numpy_array(a)

for x, y in combinations(g.nodes, 2):
    for p in nx.all_simple_paths(g, x, y):
        print(p)

# Output
# [0, 1]
# [0, 3, 2, 1]
# [0, 1, 2]
# [0, 3, 2]
# [0, 1, 2, 3]
# [0, 3]
# [1, 0, 3, 2]
# [1, 2]
# [1, 0, 3]
# [1, 2, 3]
# [2, 1, 0, 3]
# [2, 3]
# [4, 5]
</code>```

Body:
I'm trying to use the networkx library from python to find all paths from my data set in the form of dataframe as I have attached the captured screen from what I have done.

according to the network graph, i would like to list all paths from this network then i have tried it with this code but it's not working.

from functools import partial
all_paths = partial(nx.all_simple_paths, graph)
all_paths
for x in partial(nx.all_simple_paths, graph):
    print(x)

the example of the expected result will be something like this

[[1, 2, 5], [1, 2, 5, 16]]

any suggestion?

Body:
According to the doc, all_simple_paths find all paths between two given nodes, which are missing in your code. And I think you may misunderstand what partial does. From my understanding, partial repeats executing the function (1st argument) multiple times (2nd argument).

One way to find all paths in the network is to find all possible node pairs and then the paths connecting the pairs.

Example:

from itertools import combinations
import numpy as np
import networkx as nx

a = np.array([
    [0, 1, 0, 1, 0, 0],
    [1, 0, 1, 0, 0 ,0],
    [0, 1, 0, 1, 0, 0],
    [1, 0, 1, 0, 0, 0],
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0 ,1, 0]
])
g = nx.from_numpy_array(a)

for x, y in combinations(g.nodes, 2):
    for p in nx.all_simple_paths(g, x, y):
        print(p)

# Output
# [0, 1]
# [0, 3, 2, 1]
# [0, 1, 2]
# [0, 3, 2]
# [0, 1, 2, 3]
# [0, 3]
# [1, 0, 3, 2]
# [1, 2]
# [1, 0, 3]
# [1, 2, 3]
# [2, 1, 0, 3]
# [2, 3]
# [4, 5]


问:
Sorting dictionary having list in python
I have a python dictionary, my code is below

```<code>d = {
 'r_18': {'text': u'INCOMET', 'center': [195.24393963813782, 521.3750743865967]},
'r_19': {'text': u'759R', 'center': [620.7350377559662, 1517.1044731140137]}
}

sorted_x = sorted(d.items(),key=lambda kv: kv[1], reverse=False)
sorted_dict = collections.OrderedDict(sorted_x)
print(sorted_dict)
</code>```

I need a dict having ordered based on first and second value of list that should be ordered. ie, both the value containing list should be ordered like

the text value is in order based on ordered value of first y then x of list

The error i got is TypeError: '<' not supported between instances of
  'dict' and 'dict'

答:
Each element of d.items() is a pair (key, dict) so if you want to use the list to sort you need to access and index it in the dict.

For instance, if you want to sort by (y,x) then the code becomes:

```<code>>>> sorted_x = sorted(d.items(),key=lambda kv: (kv[1]['center'][1],kv[1]['center'][0]) , reverse=False)
>>> sorted_dict = collections.OrderedDict(sorted_x)
OrderedDict([('r_18', {'text': 'INCOMET', 'center': [195.24393963813782, 521.3750743865967]}), ('r_19', {'text': '759R', 'center': [620.7350377559662, 1517.1044731140137]})])
</code>```

Body:
I have a python dictionary, my code is below

d = {
 'r_18': {'text': u'INCOMET', 'center': [195.24393963813782, 521.3750743865967]},
'r_19': {'text': u'759R', 'center': [620.7350377559662, 1517.1044731140137]}
}

sorted_x = sorted(d.items(),key=lambda kv: kv[1], reverse=False)
sorted_dict = collections.OrderedDict(sorted_x)
print(sorted_dict)

I need a dict having ordered based on first and second value of list that should be ordered. ie, both the value containing list should be ordered like

the text value is in order based on ordered value of first y then x of list

The error i got is TypeError: '<' not supported between instances of
  'dict' and 'dict'

Body:
Each element of d.items() is a pair (key, dict) so if you want to use the list to sort you need to access and index it in the dict.

For instance, if you want to sort by (y,x) then the code becomes:

>>> sorted_x = sorted(d.items(),key=lambda kv: (kv[1]['center'][1],kv[1]['center'][0]) , reverse=False)
>>> sorted_dict = collections.OrderedDict(sorted_x)
OrderedDict([('r_18', {'text': 'INCOMET', 'center': [195.24393963813782, 521.3750743865967]}), ('r_19', {'text': '759R', 'center': [620.7350377559662, 1517.1044731140137]})])


问:
How to fetch data from multiple urls at once?
I have a function that fetches from a url in React

```<code>const DataContextProvider = (props) => {
  const [isLoading, setLoading] = useState(false);
  const [cocktails, setCocktails] = useState([]);

  useEffect(() => {
    const fetchCocktailList = async () => {
      const baseUrl = 'https://www.thecocktaildb.com/api/json/v1/1/';
      setLoading(true);
      try {
        const res = await fetch(`${baseUrl}search.php?s=margarita`);
        const data = await res.json();
        console.log(data);
        setCocktails(data.drinks);
        setLoading(false);
      } catch (err) {
        console.log('Error fetching data');

        setLoading(false);
      }
    };

    fetchCocktailList();
  }, []);

</code>```

How I'm mapping data so far.

```<code>const DrinkList = () => {
  const { cocktails } = useContext(DataContext);
  return (
    <div className='drink-list-wrapper'>
      {cocktails.length > 0 &&
        cocktails.map((drink) => {
          return <DrinkItem drink={drink} key={drink.idDrink} />;
        })}
    </div>
  );
};
</code>```

However I want to fetch from this url also ${baseUrl}search.php?s=martini

I would like a good clean way to do this and set my state to both of the returned data.

答:
var promises = [
  fetchCocktail(api1),
  fetchCocktail(api2)
];
var results = await Promise.allSettled(promises);

Body:
I have a function that fetches from a url in React

const DataContextProvider = (props) => {
  const [isLoading, setLoading] = useState(false);
  const [cocktails, setCocktails] = useState([]);

  useEffect(() => {
    const fetchCocktailList = async () => {
      const baseUrl = 'https://www.thecocktaildb.com/api/json/v1/1/';
      setLoading(true);
      try {
        const res = await fetch(`${baseUrl}search.php?s=margarita`);
        const data = await res.json();
        console.log(data);
        setCocktails(data.drinks);
        setLoading(false);
      } catch (err) {
        console.log('Error fetching data');

        setLoading(false);
      }
    };

    fetchCocktailList();
  }, []);

How I'm mapping data so far.

const DrinkList = () => {
  const { cocktails } = useContext(DataContext);
  return (

      {cocktails.length > 0 &&
        cocktails.map((drink) => {
          return <DrinkItem drink={drink} key={drink.idDrink} />;
        })}

  );
};

However I want to fetch from this url also ${baseUrl}search.php?s=martini

I would like a good clean way to do this and set my state to both of the returned data.


问:
Problem while extracting prices from booking.com with scrapy css
I'm trying to extract hotel names alongside their prices from the booking.com website. I managed to extract the hotel names and store them in item containers, however I'm struggling to extract the belonging prices from the webpage.
My code is below:

```<code>import scrapy

from ..items import KonkurrenzanalyseItem

class Konkurrenzanalyse(scrapy.Spider):
    name = 'Booking'
    start_urls = [
    'https://www.booking.com/searchresults.de.html?aid=304142&label=gen173nr-1DCAEoggI46AdIM1gEaDuIAQGYAQe4AQfIAQ3YAQPoAQGIAgGoAgO4AuadkPIFwAIB&sid=f5f5396810ee33128397135370be94ba&tmpl=searchresults&checkin_month=2&checkin_monthday=18&checkin_year=2020&checkout_month=2&checkout_monthday=19&checkout_year=2020&class_interval=1&dest_id=-1821233&dest_type=city&dtdisc=0&from_sf=1&group_adults=2&group_children=0&inac=0&index_postcard=0&label_click=undef&no_rooms=1&order=price&postcard=0&raw_dest_type=city&room1=A%2CA&sb_price_type=total&shw_aparth=1&slp_r_match=0&src_elem=sb&srpvid=704b677afe570188&ss=Lübeck&ss_all=0&ssb=empty&sshis=0&ssne=Lübeck&ssne_untouched=Lübeck&top_ufis=1&rows=25&offset=25'
    ]

    def parse(self, response):
        items = KonkurrenzanalyseItem()

        hotel_name = response.css('.sr-hotel__name::text').extract()
        hotel_price = response.css('.bui-price-display__value::text').extract()

        items['hotel_name'] = hotel_name
        items['hotel_price'] = hotel_price

        yield items
</code>```

The next image represents the price that I want to extract from the html code:

By now, the code outputs the following values in which the prices are not being listed yet:

Since I am quite a newbie in this environment, please excuse me if my question is not 100% accurately formulated.

答:
Seems to me like your css selector is just a little bit off, try:

```<code>hotel_price = response.css('div.bui-price-display__value.prco-inline-block-maker-helper::text').extract_first()
</code>```

Have a look at this helpful css slector resource here

Body:
I'm trying to extract hotel names alongside their prices from the booking.com website. I managed to extract the hotel names and store them in item containers, however I'm struggling to extract the belonging prices from the webpage.
My code is below:

import scrapy

from ..items import KonkurrenzanalyseItem

class Konkurrenzanalyse(scrapy.Spider):
    name = 'Booking'
    start_urls = [
    'https://www.booking.com/searchresults.de.html?aid=304142&label=gen173nr-1DCAEoggI46AdIM1gEaDuIAQGYAQe4AQfIAQ3YAQPoAQGIAgGoAgO4AuadkPIFwAIB&sid=f5f5396810ee33128397135370be94ba&tmpl=searchresults&checkin_month=2&checkin_monthday=18&checkin_year=2020&checkout_month=2&checkout_monthday=19&checkout_year=2020&class_interval=1&dest_id=-1821233&dest_type=city&dtdisc=0&from_sf=1&group_adults=2&group_children=0&inac=0&index_postcard=0&label_click=undef&no_rooms=1&order=price&postcard=0&raw_dest_type=city&room1=A%2CA&sb_price_type=total&shw_aparth=1&slp_r_match=0&src_elem=sb&srpvid=704b677afe570188&ss=Lübeck&ss_all=0&ssb=empty&sshis=0&ssne=Lübeck&ssne_untouched=Lübeck&top_ufis=1&rows=25&offset=25'
    ]

    def parse(self, response):
        items = KonkurrenzanalyseItem()

        hotel_name = response.css('.sr-hotel__name::text').extract()
        hotel_price = response.css('.bui-price-display__value::text').extract()

        items['hotel_name'] = hotel_name
        items['hotel_price'] = hotel_price

        yield items

The next image represents the price that I want to extract from the html code:

By now, the code outputs the following values in which the prices are not being listed yet:

Since I am quite a newbie in this environment, please excuse me if my question is not 100% accurately formulated.

Body:
Seems to me like your css selector is just a little bit off, try:

hotel_price = response.css('div.bui-price-display__value.prco-inline-block-maker-helper::text').extract_first()

Have a look at this helpful css slector resource here


问:
How to run a Symfony application on a read-only system, where 'var/cache' can't be written into?
I'm trying to configure my Symfony 5 application to be run in a read-only system.

But despite configuring it to use Memcached instead of the filesystem for the cached data that is usually written in the application var/cache directory
(according to the documentation, all I need to do is to change the cache adapter for the system cache pool and for the app cache pool if desired), I find that Symfony continues writing to var/cache.

What am I missing? How can I deploy the application in a read only system?

答:
If you configure the system not to use a filesystem based cache, you only need to run php bin/console cache:warmup, on deployment and then deploy all the generated code (including the contents of var/cache) to the execution environment.

From here:

In the prod environment (i.e. when APP_ENV is prod and APP_DEBUG is 0), as long as you run php bin/console cache:warmup, no cache files will need to be written to disk at runtime. The only exception is when using a filesystem-based cache, such as Doctrine's query result cache or Symfony's cache with a filesystem provider configured.

You'll also need to make sure that you are not logging to disk.

Nowadays, since Symfony 4, var/cache is mostly meant to store long term artefacts like compiled container files, compiled translations, and/or Doctrine proxies. Not for temporary cache files.

Following these practices, a well configured application should be able to be deployed on read-only environments.


问:
Call operator by name
What is the Go equivalent of, for example, Python's operator package for calling builtin operators by name?

Meaning, how can I do something like:

func f(op func(int, int)bool, a int, b int)
    ...
    if op(a, b) {
        ...

f(operators.LessThan, 1, 2) // true
```

Stated otherwise, how to write a function that takes in what basic operator to apply as a function argument?

答:
Update 2023 / Go with Generics

Powered by Go generics, I made a new package to do this at github.com/tawesoft/golib/v2/operator:

For your example use case,

import "tawesoft/golib/v2/operator"

...

f := operator.LT[int] // less than
f(1, 2) // true
```
<hr />
<p><strong>Old answer</strong></p>
<p>I needed the same thing - basic operators as first-class functions in Go - and ended up writing a template and a bit of Python to generate my own.</p>
<p>I've packaged it up into a single well-tested Go module, called <code>operator</code> after the Python module.</p>
<p>Hope this helps!</p>
<p><strong>Go Get:</strong></p>
```go get -u tawesoft.co.uk/go/operator
```
<p><strong>Examples:</strong></p>
```operator.Boolean.Not(true) == false
operator.Boolean.Nary.Any(false, true, true, false) == true
operator.Int.Binary.Add(1, 2) == 3
```
<p>In your case:</p>
```f(operator.Int.Binary.Lt, 1, 2)
```

Title: Call operator by name

Body:
What is the Go equivalent of, for example, Python's operator package for calling builtin operators by name?

Meaning, how can I do something like:

func f(op func(int, int)bool, a int, b int)
    ...
    if op(a, b) {
        ...

f(operators.LessThan, 1, 2) // true

Stated otherwise, how to write a function that takes in what basic operator to apply as a function argument?

Body:
Update 2023 / Go with Generics

Powered by Go generics, I made a new package to do this at github.com/tawesoft/golib/v2/operator:

For your example use case,

import "tawesoft/golib/v2/operator"

...

f := operator.LT[int] // less than
f(1, 2) // true

Old answer

I needed the same thing - basic operators as first-class functions in Go - and ended up writing a template and a bit of Python to generate my own.

I've packaged it up into a single well-tested Go module, called operator after the Python module.

Hope this helps!

Go Get:

go get -u tawesoft.co.uk/go/operator

Examples:

operator.Boolean.Not(true) == false
operator.Boolean.Nary.Any(false, true, true, false) == true
operator.Int.Binary.Add(1, 2) == 3

In your case:

f(operator.Int.Binary.Lt, 1, 2)


问:
How can i redirect unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei) using .htaccess?
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

```<code>RewriteEngine On
ErrorDocument 404 /example.com
</code>```

答:
A simple 301 redirect will do the job.</p>

```<code>redirect 301 /old_url http://www.domainroot.com/
</code>```

Body:
There is a issue of unstructured link like (https://example.com/digital-marketing.php/ercbierubcrei)

How can I redirect its to main root?

My .htaccess not working, I'm using below code in .htaccess:-

RewriteEngine On
ErrorDocument 404 /example.com

Body:
A simple 301 redirect will do the job.

redirect 301 /old_url http://www.domainroot.com/


问:
One character in multiple groups
I have a string like:

s = 'ababbabbba'
```

<p>I'm trying to match all patterns matching any number of <em>b</em>'s between <em>a</em>'s. This is what I expect the patterns to be for <code>s</code> above:</p>

<pre class="lang-py prettyprint-override"><code>['aba', 'abba', 'abbba']
</code>```

This is what I've tried:

import re
re.findall('ab+a', s)
```

<p>Which gives:</p>

<pre class="lang-py prettyprint-override"><code>['aba', 'abbba']
</code>```

I think that happens because any single a can only be part of a single group. Whereas my requirement would make the middle a's be part of two groups. Reading through the re documentation, I can't find any way to do this.

答:
Based on the comment above, the solution is:

re.findall('(?=(ab+a))', s)
```

Title: One character in multiple groups

Body:
I have a string like:

s = 'ababbabbba'

I'm trying to match all patterns matching any number of b's between a's. This is what I expect the patterns to be for s above:

['aba', 'abba', 'abbba']

This is what I've tried:

import re
re.findall('ab+a', s)

Which gives:

['aba', 'abbba']

I think that happens because any single a can only be part of a single group. Whereas my requirement would make the middle a's be part of two groups. Reading through the re documentation, I can't find any way to do this.


问:
Maven build error - The following artifacts could not be resolved
I want to build a spring mvc project by maven, I got the following error:

```<code>The following artifacts could not be resolved: org.aopalliance:com.springsource.org.aopalliance:jar:1.0.0, org.hibernate:hibernate-validator:jar:4.2.0.Beta1: Could not find artifact org.aopalliance:com.springsource.org.aopalliance:jar:1.0.0 in central (http://repo1.maven.org/maven2)
</code>```

I use eclipse and m2eclipse plugin. I don't know how to add local repository. And I found for different versions of eclipse,the result is different. Some can pass, some fail. I am confused.

By the way where can I find the version of maven used in m2eclipse?

Update：Now I can handle hibernate-validator,but even I deleted all spring mvc dependencies,I found there are many other library are dependent  on com.springsource.org.aopalliance,

答:
Check your %.m2\repository\org\aopalliance\com.springsource.org.aopalliance\1.0.0\.
If there isn't a com.springsource.org.aopalliance-1.0.0.jar in there, just download it by yourself and copy it to this folder.

Body:
I want to build a spring mvc project by maven, I got the following error:

The following artifacts could not be resolved: org.aopalliance:com.springsource.org.aopalliance:jar:1.0.0, org.hibernate:hibernate-validator:jar:4.2.0.Beta1: Could not find artifact org.aopalliance:com.springsource.org.aopalliance:jar:1.0.0 in central (http://repo1.maven.org/maven2)

I use eclipse and m2eclipse plugin. I don't know how to add local repository. And I found for different versions of eclipse,the result is different. Some can pass, some fail. I am confused.

By the way where can I find the version of maven used in m2eclipse?

Update：Now I can handle hibernate-validator,but even I deleted all spring mvc dependencies,I found there are many other library are dependent  on com.springsource.org.aopalliance,


问:
Removing time from datestamp with twig
I am using prestashop 1.7 which now uses twig (not sure what version).

I have the following in a twig file :

```<code>{{ customerInformation.personalInformation.registrationDate }}
</code>```

which gives me:

```<code>29/01/2020 11:04:38
</code>```

(so the date in DD-MM-YYYY-TIME format).

Does anyone know how to remove the time from the date?

e.g. so it just echo's

```<code>29/01/2020
</code>```

答:
You should store dates as a valid DateTime notation, then you could just use the date filter

{{ '01/29/2020 10:00:00' | date('d/m/Y') }}
{{ '2020-01-29 10:00:00' | date('d/m/Y') }}
{{ '29-01-2020 10:00:00' | date('d/m/Y') }}
```

demo

Title: Removing time from datestamp with twig

Body:
I am using prestashop 1.7 which now uses twig (not sure what version).

I have the following in a twig file :

{{ customerInformation.personalInformation.registrationDate }}

which gives me:

29/01/2020 11:04:38

(so the date in DD-MM-YYYY-TIME format).

Does anyone know how to remove the time from the date?

e.g. so it just echo's

29/01/2020

Body:
You should store dates as a valid DateTime notation, then you could just use the date filter

{{ '01/29/2020 10:00:00' | date('d/m/Y') }}
{{ '2020-01-29 10:00:00' | date('d/m/Y') }}
{{ '29-01-2020 10:00:00' | date('d/m/Y') }}

demo


问:
How to execute tasks in parallel but not more than N tasks per T seconds?
I need to run many tasks in parallel as fast as possible. But if my program runs more than 30 tasks per 1 second, it will be blocked. How to ensure that tasks run no more than 30 per any 1-second interval?

In other words, we must prevent the new task from starting if 30 tasks were completed in the last 1-second interval.

My ugly possible solution:

```<code>private async Task Process(List<Task> taskList, int maxIntervalCount, int timeIntervalSeconds)
{
    var timeList = new List<DateTime>();

    var sem = new Semaphore(maxIntervalCount, maxIntervalCount);
    var tasksToRun = taskList.Select(async task =>
    {
        do
        {
            sem.WaitOne();
        }
        while (HasAllowance(timeList, maxIntervalCount, timeIntervalSeconds));

        await task;

        timeList.Add(DateTime.Now);

        sem.Release();
    });

    await Task.WhenAll(tasksToRun);
}

private bool HasAllowance(List<DateTime> timeList, int maxIntervalCount, int timeIntervalSeconds)
{
    return timeList.Count <= maxIntervalCount
    || DateTime.Now.Subtract(TimeSpan.FromSeconds(timeIntervalSeconds)) > timeList[timeList.Count - maxIntervalCount];
}
</code>```

答:
I think that this problem can be solved by a SemaphoreSlim limited to the number of maximum tasks per interval, and also by a Task.Delay that delays the release of the SemaphoreSlim after each task's completion, for an interval equal to the required throttling interval. Below is an implementation based on this idea. The rate limiting can be applied in two ways:

With includeAsynchronousDuration: false the rate limit affects how many operations can be started during the specified time span. The duration of each operation is not taken into account.

With includeAsynchronousDuration: true the rate limit affects how many operations can be counted as "active" during the specified time span, and is more restrictive (makes the enumeration slower). Instead of counting each operation as a moment in time (when started), it is counted as a time span (between start and completion). An operation is counted as "active" for a specified time span, if and only if its own time span intersects with the specified time span.

```<code>/// <summary>
/// Applies an asynchronous transformation for each element of a sequence,
/// limiting the number of transformations that can start or be active during
/// the specified time span.
/// </summary>
public static async Task<TResult[]> ForEachAsync<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, Task<TResult>> action,
    int maxActionsPerTimeUnit,
    TimeSpan timeUnit,
    bool includeAsynchronousDuration = false,
    bool onErrorContinue = false, /* Affects only asynchronous errors */
    bool executeOnCapturedContext = false)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (action == null) throw new ArgumentNullException(nameof(action));
    if (maxActionsPerTimeUnit < 1)
        throw new ArgumentOutOfRangeException(nameof(maxActionsPerTimeUnit));
    if (timeUnit < TimeSpan.Zero || timeUnit.TotalMilliseconds > Int32.MaxValue)
        throw new ArgumentOutOfRangeException(nameof(timeUnit));

    using var semaphore = new SemaphoreSlim(maxActionsPerTimeUnit,
        maxActionsPerTimeUnit);
    using var cts = new CancellationTokenSource();
    var tasks = new List<Task<TResult>>();
    var releaseTasks = new List<Task>();

    try // Watch for exceptions thrown by the source enumerator
    {
        foreach (var item in source)
        {
            try
            {
                await semaphore.WaitAsync(cts.Token)
                    .ConfigureAwait(executeOnCapturedContext);
            }
            catch (OperationCanceledException) { break; }

            // Exceptions thrown synchronously by invoking the action are breaking
            // the loop unconditionally (the onErrorContinue has no effect on them).
            var task = action(item);
            if (!onErrorContinue) task = ObserveFailureAsync(task);
            tasks.Add(task);
            releaseTasks.Add(ScheduleSemaphoreReleaseAsync(task));
        }
    }
    catch (Exception ex) { tasks.Add(Task.FromException<TResult>(ex)); }
    cts.Cancel(); // Cancel all release tasks

    Task<TResult[]> whenAll = Task.WhenAll(tasks);
    try { return await whenAll.ConfigureAwait(false); }
    catch (OperationCanceledException) when (whenAll.IsCanceled) { throw; }
    catch { whenAll.Wait(); throw; } // Propagate AggregateException
    finally { await Task.WhenAll(releaseTasks); }

    async Task<TResult> ObserveFailureAsync(Task<TResult> task)
    {
        try { return await task.ConfigureAwait(false); }
        catch { cts.Cancel(); throw; }
    }

    async Task ScheduleSemaphoreReleaseAsync(Task<TResult> task)
    {
        if (includeAsynchronousDuration)
            try { await task.ConfigureAwait(false); } catch { } // Ignore exceptions
        // Release only if the Task.Delay completed successfully
        try { await Task.Delay(timeUnit, cts.Token).ConfigureAwait(false); }
        catch (OperationCanceledException) { return; }
        semaphore.Release();
    }
}
</code>```

Usage example:

```<code>int[] results = await ForEachAsync(Enumerable.Range(1, 100), async n =>
{
    await Task.Delay(500); // Simulate some asynchronous I/O-bound operation
    return n;
}, maxActionsPerTimeUnit: 30, timeUnit: TimeSpan.FromSeconds(1.0),
    includeAsynchronousDuration: true);
</code>```

The reasons for propagating an AggregateException using the catch+Wait technique, are explained here.

Body:
I need to run many tasks in parallel as fast as possible. But if my program runs more than 30 tasks per 1 second, it will be blocked. How to ensure that tasks run no more than 30 per any 1-second interval?

In other words, we must prevent the new task from starting if 30 tasks were completed in the last 1-second interval.

My ugly possible solution:

private async Task Process(List<Task> taskList, int maxIntervalCount, int timeIntervalSeconds)
{
    var timeList = new List<DateTime>();

    var sem = new Semaphore(maxIntervalCount, maxIntervalCount);
    var tasksToRun = taskList.Select(async task =>
    {
        do
        {
            sem.WaitOne();
        }
        while (HasAllowance(timeList, maxIntervalCount, timeIntervalSeconds));

        await task;

        timeList.Add(DateTime.Now);

        sem.Release();
    });

    await Task.WhenAll(tasksToRun);
}

private bool HasAllowance(List<DateTime> timeList, int maxIntervalCount, int timeIntervalSeconds)
{
    return timeList.Count <= maxIntervalCount
    || DateTime.Now.Subtract(TimeSpan.FromSeconds(timeIntervalSeconds)) > timeList[timeList.Count - maxIntervalCount];
}

Body:
I think that this problem can be solved by a SemaphoreSlim limited to the number of maximum tasks per interval, and also by a Task.Delay that delays the release of the SemaphoreSlim after each task's completion, for an interval equal to the required throttling interval. Below is an implementation based on this idea. The rate limiting can be applied in two ways:

With includeAsynchronousDuration: false the rate limit affects how many operations can be started during the specified time span. The duration of each operation is not taken into account.

With includeAsynchronousDuration: true the rate limit affects how many operations can be counted as "active" during the specified time span, and is more restrictive (makes the enumeration slower). Instead of counting each operation as a moment in time (when started), it is counted as a time span (between start and completion). An operation is counted as "active" for a specified time span, if and only if its own time span intersects with the specified time span.

/// <summary>
/// Applies an asynchronous transformation for each element of a sequence,
/// limiting the number of transformations that can start or be active during
/// the specified time span.
/// </summary>
public static async Task<TResult[]> ForEachAsync<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, Task<TResult>> action,
    int maxActionsPerTimeUnit,
    TimeSpan timeUnit,
    bool includeAsynchronousDuration = false,
    bool onErrorContinue = false, /* Affects only asynchronous errors */
    bool executeOnCapturedContext = false)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (action == null) throw new ArgumentNullException(nameof(action));
    if (maxActionsPerTimeUnit < 1)
        throw new ArgumentOutOfRangeException(nameof(maxActionsPerTimeUnit));
    if (timeUnit < TimeSpan.Zero || timeUnit.TotalMilliseconds > Int32.MaxValue)
        throw new ArgumentOutOfRangeException(nameof(timeUnit));

    using var semaphore = new SemaphoreSlim(maxActionsPerTimeUnit,
        maxActionsPerTimeUnit);
    using var cts = new CancellationTokenSource();
    var tasks = new List<Task<TResult>>();
    var releaseTasks = new List<Task>();

    try // Watch for exceptions thrown by the source enumerator
    {
        foreach (var item in source)
        {
            try
            {
                await semaphore.WaitAsync(cts.Token)
                    .ConfigureAwait(executeOnCapturedContext);
            }
            catch (OperationCanceledException) { break; }

            // Exceptions thrown synchronously by invoking the action are breaking
            // the loop unconditionally (the onErrorContinue has no effect on them).
            var task = action(item);
            if (!onErrorContinue) task = ObserveFailureAsync(task);
            tasks.Add(task);
            releaseTasks.Add(ScheduleSemaphoreReleaseAsync(task));
        }
    }
    catch (Exception ex) { tasks.Add(Task.FromException<TResult>(ex)); }
    cts.Cancel(); // Cancel all release tasks

    Task<TResult[]> whenAll = Task.WhenAll(tasks);
    try { return await whenAll.ConfigureAwait(false); }
    catch (OperationCanceledException) when (whenAll.IsCanceled) { throw; }
    catch { whenAll.Wait(); throw; } // Propagate AggregateException
    finally { await Task.WhenAll(releaseTasks); }

    async Task<TResult> ObserveFailureAsync(Task<TResult> task)
    {
        try { return await task.ConfigureAwait(false); }
        catch { cts.Cancel(); throw; }
    }

    async Task ScheduleSemaphoreReleaseAsync(Task<TResult> task)
    {
        if (includeAsynchronousDuration)
            try { await task.ConfigureAwait(false); } catch { } // Ignore exceptions
        // Release only if the Task.Delay completed successfully
        try { await Task.Delay(timeUnit, cts.Token).ConfigureAwait(false); }
        catch (OperationCanceledException) { return; }
        semaphore.Release();
    }
}

Usage example:

int[] results = await ForEachAsync(Enumerable.Range(1, 100), async n =>
{
    await Task.Delay(500); // Simulate some asynchronous I/O-bound operation
    return n;
}, maxActionsPerTimeUnit: 30, timeUnit: TimeSpan.FromSeconds(1.0),
    includeAsynchronousDuration: true);

The reasons for propagating an AggregateException using the catch+Wait technique, are explained here.


问:
Integrating circuitbreaker, retry and timelimiter in Resilience4j
I am trying to use Resilience4j features.

My use case is to combine the 3 modules:

circuitbreaker

retry

timelimiter

I want to combine all these modules and execute the method only once.

Code

Here is what I have tried.

Supplier<R> supplier = this::doSomething;

timeLimiter.executeFutureSupplier(() -> CompletableFuture.supplyAsync(supplier));

return Decorators.ofSupplier(supplier)
                .withCircuitBreaker(circuitBreaker)
                .withRetry(retry)
                .withBulkhead(bulkhead)
                .decorate();
```

Issue

My doSomething() method executes twice instead of expected once.

Has anyone seen this issue earlier?

答:
You are using timeLimiter.executeFutureSupplier which executes the Future instead of decorating it.

Please use it in exactly this order:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
Supplier<R> supplier = this::doSomething;

CompletableFuture<R> future = Decorators.ofSupplier(supplier)
    .withThreadPoolBulkhead(threadPoolBulkhead)
    .withTimeLimiter(timeLimiter, scheduledExecutorService)
    .withCircuitBreaker(circuitBreaker)
    .withRetry(retry)
    .get().toCompletableFuture();
```

Body:
I am trying to use Resilience4j features.

My use case is to combine the 3 modules:

circuitbreaker

retry

timelimiter

I want to combine all these modules and execute the method only once.

Code

Here is what I have tried.

Supplier<R> supplier = this::doSomething;

timeLimiter.executeFutureSupplier(() -> CompletableFuture.supplyAsync(supplier));

return Decorators.ofSupplier(supplier)
                .withCircuitBreaker(circuitBreaker)
                .withRetry(retry)
                .withBulkhead(bulkhead)
                .decorate();

Issue

My doSomething() method executes twice instead of expected once.

Has anyone seen this issue earlier?


问:
How to remove the square brackets in output of the list?
```<code>items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
    print(item)

#or
print("The first 3 items in the list are: " + str(items[:3]))

</code>```

Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?

答:
This would do it:

```<code>print("The first 3 items in the list are: " + str(items[:3])[1:-1])
</code>```

assuming you don't mind the items separated by commas.

Body:
items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
    print(item)

#or
print("The first 3 items in the list are: " + str(items[:3]))

Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?

Body:
This would do it:

print("The first 3 items in the list are: " + str(items[:3])[1:-1])

assuming you don't mind the items separated by commas.


问:
Update part of page automatically when the data from an object changes without reloading the page
I have data being inserted into various divs collected from the backend.
This data gets updated, what i need is for the divs to also automatically update the data within the divs without actually refreshing the whole page.
Right now a page refresh would update the divs but I want the divs to auto update without affecting users experience.
Any suggestions.
As an example, I have a vote up/down button in the frontend, the vote gets sent to the backend then sent back through to the front and inserted into a div, however they wouldnt see their vote registered in the frontend unless they refreshed the page, So I would need the users vote result to be updated in the front end everytime then make a vote or change a vote ect automatically.
This is just one example, there is more data inserted in this table which could be updated at any time.

Update,
Not sure people understand fully what I need or trying to do.
Basically have and object coming through from back-end,  on page load, data from that object is inserted into a table such as new posts,  votes ect.

What I need to be able to do is check if the object has changed since the page load and if so to then update the data on the page without refreshing the page.

Ideally need this to happen instantaneously, so it recognises as soon as there is a difference between the object data and that being displayed in the browser and updates it.

Hope that makes it more clear as to what I want to do.

I have and object  with information such as the  suggestiontitle, description, votestatus, etc,  these get inserted into a row, when a new.  A new row gets added when a new object with main object comes through.
So I need to be able to check for changes in the main object so that I can then add the new objects as rows into the table and also Detect and update any changes with current objects already inserted.

答:
What I Understood is that you need to update the div whenever Vote is updated? If I understood correctly then I would like to go with delegate and call a function to the server once you get a response from Vote stuff call.

If you want to get an event from the server-side then I would suggest you go for SignalR, for real-time communication, which will give you an event called the server-side.