问:
My "Buy" function in smart contract file keep making error
This is my solidity file for NFT marketplace.

```<code>// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

 contract NFT is ERC721URIStorage,Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;
    address payable public _owner;
    mapping(address => uint[]) public addressToTokenArray;
    mapping(uint256 => bool) public forSale;
    mapping(uint256 => uint256) public tokenIdToPrice;
    event Minting(address _owner, uint256 _tokenId, uint256 _price);
    event Purchase(address _seller, address _buyer, uint256 _price);
    event Remove(uint256 _tokenId, uint[] beforeBuy, uint[] afterBuy);

    constructor() ERC721("TeddyBear", "TEDDY") {
    }

    function mint(string memory _tokenURI, uint256 _price) public onlyOwner returns (bool)
    {
        _tokenIds.increment();
        uint256 newItemId = _tokenIds.current();
        tokenIdToPrice[newItemId] = _price;
        if(addressToTokenArray[msg.sender].length !=1){
            addressToTokenArray[msg.sender].push(newItemId);
        }else{
            addressToTokenArray[msg.sender] = [newItemId];
        }
        _mint(msg.sender, newItemId);
        _setTokenURI(newItemId, _tokenURI);
        emit Minting(msg.sender, newItemId, _price);
        return true;
    }

    // 토큰의 주인이 판매 하는 함수
    function sell(uint256 _tokenId, uint256 _price) external {
        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
        require(_price > 0, 'Price zero');
        tokenIdToPrice[_tokenId] = _price;
        forSale[_tokenId] = true;
    }

    // 토큰의 주인이 판매를 취하하는 함수
    function stopSell(uint256 _tokenId) external {
        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
        forSale[_tokenId] = false;
    }

    // function remove(uint[] memory array, uint index) public pure  returns(uint[] memory) {
    //     if (index >= array.length) return array;

    //     for (uint i = index; i<array.length-1; i++){
    //         array[i] = array[i+1];
    //     }
    //     delete array[array.length-1];
    //     return array;
    // }

    function buy(uint256 _tokenId, uint256 sendAmount) external payable {
        uint256 price = tokenIdToPrice[_tokenId];
        bool isOnSale = forSale[_tokenId];
        require(isOnSale, 'This token is not for sale');
        require(sendAmount == price, 'Incorrect value');
        address seller = ownerOf(_tokenId);
        require(seller == ownerOf(_tokenId), 'Seller and Owner is not same');
        // uint[] memory beforeBuy = addressToTokenArray[seller];
        // // for(uint i=0;i<addressToTokenArray[seller].length;i++){
        // //     if(_tokenId == addressToTokenArray[seller][i]){
        // //         remove(addressToTokenArray[seller],i);
        // //     }
        // // }
        // uint[] memory afterBuy = addressToTokenArray[seller];
        // emit Remove(_tokenId, beforeBuy, afterBuy);
        addressToTokenArray[msg.sender] = [_tokenId];
        safeTransferFrom(seller, msg.sender, _tokenId);
        forSale[_tokenId] = true;
        payable(seller).transfer(sendAmount); // send the ETH to the seller
        emit Purchase(seller, msg.sender, sendAmount);
    }

    function getPrice(uint256 _tokenId) public view returns (uint256){
        uint256 price = tokenIdToPrice[_tokenId];
        return price;
    }

    function isSale(uint256 _tokenId) public view returns (bool){
        bool isOnSale = forSale[_tokenId];
        return isOnSale;
    }

    function getMyTokenId() public view returns (uint[] memory){
        uint[] memory myTokens = addressToTokenArray[msg.sender];
        return myTokens;
    }
}
</code>```

Among functions up there, the buy function does not emit an error when I compile the .sol file, but after I deploy this contract and send transaction for "buy" function it keeps making this error.

I just want to know where I should fix it and if there is any better idea for other functions, feel free to let me know... many thanks

答:
Most likely it is failing here:

```<code> safeTransferFrom(seller, msg.sender, _tokenId);
</code>```

If you check the ERC721 contract, safeTransferFrom eventually calls this:

```<code>function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // ******  HERE IS THE ISSUE *****
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;
        emit Transfer(from, to, tokenId);
        _afterTokenTransfer(from, to, tokenId);
    }
</code>```

If your contract is going to transfer a token on behalf of owner, owner has to approve first.

so from the seller's contract, this should be called:

```<code>function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }
</code>```

tokenApprovals is a mapping that keeps track of which tokens can be transferred.

Debugging

in order to test which function call is causing error, place this requirement statement require(sendAmount == price, 'Incorrect value'); right before the function. and pass an incorrect value and you will get an error : 'Incorrect value'

Then put that require statement after the function, and pass a wrong value, if this require does send you error, you can be sure that function is causing the error

Body:
This is my solidity file for NFT marketplace.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

 contract NFT is ERC721URIStorage,Ownable {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;
    address payable public _owner;
    mapping(address => uint[]) public addressToTokenArray;
    mapping(uint256 => bool) public forSale;
    mapping(uint256 => uint256) public tokenIdToPrice;
    event Minting(address _owner, uint256 _tokenId, uint256 _price);
    event Purchase(address _seller, address _buyer, uint256 _price);
    event Remove(uint256 _tokenId, uint[] beforeBuy, uint[] afterBuy);

    constructor() ERC721("TeddyBear", "TEDDY") {
    }

    function mint(string memory _tokenURI, uint256 _price) public onlyOwner returns (bool)
    {
        _tokenIds.increment();
        uint256 newItemId = _tokenIds.current();
        tokenIdToPrice[newItemId] = _price;
        if(addressToTokenArray[msg.sender].length !=1){
            addressToTokenArray[msg.sender].push(newItemId);
        }else{
            addressToTokenArray[msg.sender] = [newItemId];
        }
        _mint(msg.sender, newItemId);
        _setTokenURI(newItemId, _tokenURI);
        emit Minting(msg.sender, newItemId, _price);
        return true;
    }

    // 토큰의 주인이 판매 하는 함수
    function sell(uint256 _tokenId, uint256 _price) external {
        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
        require(_price > 0, 'Price zero');
        tokenIdToPrice[_tokenId] = _price;
        forSale[_tokenId] = true;
    }

    // 토큰의 주인이 판매를 취하하는 함수
    function stopSell(uint256 _tokenId) external {
        require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
        forSale[_tokenId] = false;
    }

    // function remove(uint[] memory array, uint index) public pure  returns(uint[] memory) {
    //     if (index >= array.length) return array;

    //     for (uint i = index; i<array.length-1; i++){
    //         array[i] = array[i+1];
    //     }
    //     delete array[array.length-1];
    //     return array;
    // }

    function buy(uint256 _tokenId, uint256 sendAmount) external payable {
        uint256 price = tokenIdToPrice[_tokenId];
        bool isOnSale = forSale[_tokenId];
        require(isOnSale, 'This token is not for sale');
        require(sendAmount == price, 'Incorrect value');
        address seller = ownerOf(_tokenId);
        require(seller == ownerOf(_tokenId), 'Seller and Owner is not same');
        // uint[] memory beforeBuy = addressToTokenArray[seller];
        // // for(uint i=0;i<addressToTokenArray[seller].length;i++){
        // //     if(_tokenId == addressToTokenArray[seller][i]){
        // //         remove(addressToTokenArray[seller],i);
        // //     }
        // // }
        // uint[] memory afterBuy = addressToTokenArray[seller];
        // emit Remove(_tokenId, beforeBuy, afterBuy);
        addressToTokenArray[msg.sender] = [_tokenId];
        safeTransferFrom(seller, msg.sender, _tokenId);
        forSale[_tokenId] = true;
        payable(seller).transfer(sendAmount); // send the ETH to the seller
        emit Purchase(seller, msg.sender, sendAmount);
    }

    function getPrice(uint256 _tokenId) public view returns (uint256){
        uint256 price = tokenIdToPrice[_tokenId];
        return price;
    }

    function isSale(uint256 _tokenId) public view returns (bool){
        bool isOnSale = forSale[_tokenId];
        return isOnSale;
    }

    function getMyTokenId() public view returns (uint[] memory){
        uint[] memory myTokens = addressToTokenArray[msg.sender];
        return myTokens;
    }
}

Among functions up there, the buy function does not emit an error when I compile the .sol file, but after I deploy this contract and send transaction for "buy" function it keeps making this error.

I just want to know where I should fix it and if there is any better idea for other functions, feel free to let me know... many thanks

Body:
Most likely it is failing here:

 safeTransferFrom(seller, msg.sender, _tokenId);

If you check the ERC721 contract, safeTransferFrom eventually calls this:

function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // ******  HERE IS THE ISSUE *****
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;
        emit Transfer(from, to, tokenId);
        _afterTokenTransfer(from, to, tokenId);
    }

If your contract is going to transfer a token on behalf of owner, owner has to approve first.

so from the seller's contract, this should be called:

function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

tokenApprovals is a mapping that keeps track of which tokens can be transferred.

Debugging

in order to test which function call is causing error, place this requirement statement require(sendAmount == price, 'Incorrect value'); right before the function. and pass an incorrect value and you will get an error : 'Incorrect value'

Then put that require statement after the function, and pass a wrong value, if this require does send you error, you can be sure that function is causing the error


来源: stackexchange

问:
how to copy value from one row(timestamp) to all the rows(timestamp) of a column in pyspark
I have pyspark dataframe like below

```<code>Name|ManagerName|Maxdateutc

ABC|XYZ|2021-12-21T23:59:59.0000000

PQR|BED|null

SUV|YTR|null
</code>```

...and so on

I need output like below

```<code>Name|ManagerName|Maxdateutc

ABC|XYZ|2021-12-21 23:59:59.0000000

PQR|BED|2021-12-21 23:59:59.0000000

SUV|YTR|2021-12-21 23:59:59.0000000
</code>```

Could you please tell me how to do this in pyspark

ContentLicense: CC BY-SA 4.0

Body:
I have pyspark dataframe like below

Name|ManagerName|Maxdateutc

ABC|XYZ|2021-12-21T23:59:59.0000000

PQR|BED|null

SUV|YTR|null

...and so on

I need output like below

Name|ManagerName|Maxdateutc

ABC|XYZ|2021-12-21 23:59:59.0000000

PQR|BED|2021-12-21 23:59:59.0000000

SUV|YTR|2021-12-21 23:59:59.0000000

Could you please tell me how to do this in pyspark

Body:
from pyspark.sql import SparkSession
spark=SparkSession.builder.appName("practise").getOrCreate()
from pyspark.sql import functions as F

data = [("ABC", "XYZ", "2021-12-21T23:59:59.0000000",),
        ("PQR", "BED", None),
        ("SUV", "YTR", None), ]
inp=spark.createDataFrame(data, ("Name", "ManagerName", "Maxdateutc",))
inp.show(5,0)

+----+-----------+---------------------------+
|Name|ManagerName|Maxdateutc                 |
+----+-----------+---------------------------+
|ABC |XYZ        |2021-12-21T23:59:59.0000000|
|PQR |BED        |null                       |
|SUV |YTR        |null                       |
+----+-----------+---------------------------+

inp=inp.withColumn("new_Maxdateutc", F.when(inp['Maxdateutc'] == F.lit('2021-12-21T23:59:59.0000000'),\
                                        F.lit('2021-12-21T23:59:59.0000000'))\
                   .otherwise('2021-12-21T23:59:59.0000000')).drop(inp['Maxdateutc'])
inp.show(5,0)

+----+-----------+---------------------------+
|Name|ManagerName|new_Maxdateutc             |
+----+-----------+---------------------------+
|ABC |XYZ        |2021-12-21T23:59:59.0000000|
|PQR |BED        |2021-12-21T23:59:59.0000000|
|SUV |YTR        |2021-12-21T23:59:59.0000000|
+----+-----------+---------------------------+


问:
HTTP POST, head :ok returning 1 mystery byte
I have a Rails application accessed via a mobile App - and the data is exchanged in JSON format.

When I perform a successful POST, I expect, and get, a HTTP code 200 OK returned.  What I don't expect is an accompanying 1 byte of data ASCII 0x20 (i.e. a space).

I have the following code to return from the POST in the case where the object (device) being POSTed already exists.

```<code>    # Device is already registered, so update attributes of existing record (incl. device token)

    if @deviceFound.update_attributes(params[:device])
      format.html { redirect_to(@deviceFound, :notice => 'Device was successfully updated.') }
      format.xml  { head :ok }
      # format.json { head :ok }
      format.json do
        render :nothing => true, :status => :ok
        return true
      end
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @deviceFound.errors, :status => :unprocessable_entity }
      format.json { render :json => @deviceFound.errors, :status => :unprocessable_entity }
    end
</code>```

From the commented out line, you'll see that I have been using format.json { head :ok } but in an attempt to understand why I'm getting this byte returned, I've tried the alternative implementation which I believe to be equivalent. Both yield the same results HTTP 200 + 1 byte of data.

btw, if I filter out the 1 byte in this case, in all other cases my mobile App interacts with the Rails App just fine.

I'd appreciate it if someone could explain why I'm getting a byte of data in the response?

Thank you.

答:
Kudos to @nickgrim for answering this question, but just to close this off, the explanation is available here...

How to return truly empty body in rails? i.e. content-length 0

Good to know I wasn't going mad :-)

ContentLicense: CC BY-SA 3.0

Body:
I have a Rails application accessed via a mobile App - and the data is exchanged in JSON format.

When I perform a successful POST, I expect, and get, a HTTP code 200 OK returned.  What I don't expect is an accompanying 1 byte of data ASCII 0x20 (i.e. a space).

I have the following code to return from the POST in the case where the object (device) being POSTed already exists.

    # Device is already registered, so update attributes of existing record (incl. device token)

    if @deviceFound.update_attributes(params[:device])
      format.html { redirect_to(@deviceFound, :notice => 'Device was successfully updated.') }
      format.xml  { head :ok }
      # format.json { head :ok }
      format.json do
        render :nothing => true, :status => :ok
        return true
      end
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @deviceFound.errors, :status => :unprocessable_entity }
      format.json { render :json => @deviceFound.errors, :status => :unprocessable_entity }
    end

From the commented out line, you'll see that I have been using format.json { head :ok } but in an attempt to understand why I'm getting this byte returned, I've tried the alternative implementation which I believe to be equivalent. Both yield the same results HTTP 200 + 1 byte of data.

btw, if I filter out the 1 byte in this case, in all other cases my mobile App interacts with the Rails App just fine.

I'd appreciate it if someone could explain why I'm getting a byte of data in the response?

Thank you.


问:
In VueJS how to print the v-for’s increment digit key as a suffix to a CSS class
I simply want to increment a CSS class based on the loop count using the index value as a suffix to a defined class "classname nb" to get "classname nb1", "classname nb2".

I'm able to print it as content using double curly brackets {{ index }} (in my example below) but I dont’t know what syntaxe to use within the Vue :class prop.

        <v-bind class="classname" :class="nb{ index }">
            classname nb{{ index }}
        </v-bind>

```
<p>I expect these CSS classes on <code><v-bing></code> :</p>
```1. classname nb1
2. classname nb2
3. classname nb3
```

答:
you can use template literals like this:</p>
```<code><ol>
<li v-for="index in [1,2,3]" :key="index">
    <v-bind class="classname" :class=`nb${index}`>
        classname nb{{ index }}
    </v-bind>
</li>
</code>```

Body:
I simply want to increment a CSS class based on the loop count using the index value as a suffix to a defined class "classname nb" to get "classname nb1", "classname nb2".

I'm able to print it as content using double curly brackets {{ index }} (in my example below) but I dont’t know what syntaxe to use within the Vue :class prop.

        <v-bind class="classname" :class="nb{ index }">
            classname nb{{ index }}
        </v-bind>

I expect these CSS classes on <v-bing> :

1. classname nb1
2. classname nb2
3. classname nb3

Body:
you can use template literals like this:

<ol>
<li v-for="index in [1,2,3]" :key="index">
    <v-bind class="classname" :class=`nb${index}`>
        classname nb{{ index }}
    </v-bind>
</li>


问:
set variable _SERVER["PHP_AUTH_USER"] using php
I need a little help with php_auth I have used HTTP authentication with Php and it seems to working fine (when you go to the url it asks for username and password and is working fine) but what i need to do is pass the username and password for the authentication from another page and authenticate automatically. Something like set variable _SERVER["PHP_AUTH_USER"] using php from another page.

Edit: I forgot to mention that My problem is that two pages are completely different application and
  both maintain separate sessions. Application "A" and Application "B"
  may or may not be hosted on the same domain.

答:
I used a zend function setAuth(username, password); to get the work done.

```<code>$client = new Zend_Http_Client();
$client->setAuth($username, $password);
$response = $client->request('POST');
</code>```

How the setAuth function works is it embeds/encodes the authentication params as header to the url

```<code>// Set HTTP authentication if needed
if (is_array($this->auth)) {
     $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'],      $this->auth['type']);
       $headers[] = "Authorization: {$auth}";
}
</code>```

Body:
I used a zend function setAuth(username, password); to get the work done.

$client = new Zend_Http_Client();
$client->setAuth($username, $password);
$response = $client->request('POST');

How the setAuth function works is it embeds/encodes the authentication params as header to the url

// Set HTTP authentication if needed
if (is_array($this->auth)) {
     $auth = self::encodeAuthHeader($this->auth['user'], $this->auth['password'],      $this->auth['type']);
       $headers[] = "Authorization: {$auth}";
}


问:
Cant reselect previous selected item in CollectionView in Xamarin.Forms on iOS

TLDR

CollectionView broken in iOS, cant find any solution online. Weak Google fu or just not seeing the answer.

The problem

I have a CollectionView (Lets call it A) that contains items that are only strings values for filtering on a different CollectionView (Lets call it B) containing results from selecting a filter option in CollectionView A.

I have 3 different filtering options: "All", "Close to you", "Online" in CollectionView A.

The problem is that on iOS when I select for example filter option "All" in CollectionView A for the first time on the page it does the filtering and shows the results in CollectionView B, when I choose for example filtering option "Online" in CollectionView A it filters and shows the results in CollectionView B.

But when I choose filtering option "All" for the second time in CollectionView A its not responding, no event triggers, no commands runs and its not disabled. It is only showing, but I cant do anything with it.

Expected result

Can reselect the previous item on iOS, in Android no problem.

Actual result

Cant reselect previous item on iOS, need to back to previous page in stack and then navigate back to page to reset filtering.

The xaml markup

This is the xaml markup for the CollectionView A as explained above, the only holding string values to filter on.

```<code><CollectionView ItemsSource="{Binding FilterLocations}"
                Grid.Row="2"
                SelectedItem="{Binding SelectedFilterLocation}"
                SelectionMode="Single"
                HeightRequest="50">
   <CollectionView.ItemsLayout>
      <LinearItemsLayout Orientation="Horizontal"
                         ItemSpacing="10" />
   </CollectionView.ItemsLayout>
      <CollectionView.ItemTemplate>
         <DataTemplate x:DataType="x:String">
            <StackLayout xct:TouchEffect.NativeAnimation="True">
               <Frame BorderColor="{StaticResource BorderColor}"
                      x:Name="subCategoryFrame"
                      Padding="14, 10">
                  <Label Text="{Binding .}"
                         x:Name="subCategoryName"
                         FontFamily="{StaticResource FontPoppinsLight}"
                         TextColor="{StaticResource PrimaryAlt}" />
               </Frame>
            </StackLayout>
         </DataTemplate>
      </CollectionView.ItemTemplate>
         <CollectionView.Header>
            <BoxView WidthRequest="0"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Header>
         <CollectionView.Footer>
            <BoxView WidthRequest="{StaticResource NormalSpacingDouble}"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Footer>
      </CollectionView>
</code>```

The CollectionView A is in SelectionMode:Single, and the SelectedItem is bound to a ICommand on its bound ViewModel. And in the ViewModel the selection of a item in CollectionView A will trigger a filtering in CollectionView B

What I done so far

I set up so if a item in the CollectionView A is disabled it become Red, but it dont become Red.

I have tried to add a event in the Code behind, to try and set SelectedItem to null, but that back fired and just made all events go twice, one for selecting the item on the screen and second for altering the SelectedItem in the code behind.

Code:

```<code>private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      if (Device.RuntimePlatform == Device.iOS)
      {
         var collectionView = sender as CollectionView;
         if (collectionView == null) return;

         if (collectionView.SelectedItem != null)
         {
             collectionView.SelectedItem = null;
         }
      }
}
</code>```

(I know it is a big no no to do logic stuff in the Code Behind that is not design logic, but I need to get this solved or have a quick and dirty fix because of time pressure.)

Sorry for the wall of text

答:
Use a TapGestureRecognizer.

Below, MyItemCommand is defined in MyViewModel and {Binding .} refers to the item selected in ItemsSource.

```<code><DataTemplate ...>
  <StackLayout>
    <StackLayout.GestureRecognizers>
      <TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type vm:MyViewModel}},
                                              Path=MyItemCommand}"
                            CommandParameter="{Binding .}"/>
    </StackLayout.GestureRecognizers>
    ...
</code>```

Body:
TLDR

CollectionView broken in iOS, cant find any solution online. Weak Google fu or just not seeing the answer.

The problem

I have a CollectionView (Lets call it A) that contains items that are only strings values for filtering on a different CollectionView (Lets call it B) containing results from selecting a filter option in CollectionView A.

I have 3 different filtering options: "All", "Close to you", "Online" in CollectionView A.

The problem is that on iOS when I select for example filter option "All" in CollectionView A for the first time on the page it does the filtering and shows the results in CollectionView B, when I choose for example filtering option "Online" in CollectionView A it filters and shows the results in CollectionView B.

But when I choose filtering option "All" for the second time in CollectionView A its not responding, no event triggers, no commands runs and its not disabled. It is only showing, but I cant do anything with it.

Expected result

Can reselect the previous item on iOS, in Android no problem.

Actual result

Cant reselect previous item on iOS, need to back to previous page in stack and then navigate back to page to reset filtering.

The xaml markup

This is the xaml markup for the CollectionView A as explained above, the only holding string values to filter on.

<CollectionView ItemsSource="{Binding FilterLocations}"
                Grid.Row="2"
                SelectedItem="{Binding SelectedFilterLocation}"
                SelectionMode="Single"
                HeightRequest="50">
   <CollectionView.ItemsLayout>
      <LinearItemsLayout Orientation="Horizontal"
                         ItemSpacing="10" />
   </CollectionView.ItemsLayout>
      <CollectionView.ItemTemplate>
         <DataTemplate x:DataType="x:String">
            <StackLayout xct:TouchEffect.NativeAnimation="True">
               <Frame BorderColor="{StaticResource BorderColor}"
                      x:Name="subCategoryFrame"
                      Padding="14, 10">

               </Frame>
            </StackLayout>
         </DataTemplate>
      </CollectionView.ItemTemplate>
         <CollectionView.Header>
            <BoxView WidthRequest="0"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Header>
         <CollectionView.Footer>
            <BoxView WidthRequest="{StaticResource NormalSpacingDouble}"
                     HeightRequest="1"
                     BackgroundColor="Transparent" />
         </CollectionView.Footer>
      </CollectionView>

The CollectionView A is in SelectionMode:Single, and the SelectedItem is bound to a ICommand on its bound ViewModel. And in the ViewModel the selection of a item in CollectionView A will trigger a filtering in CollectionView B

What I done so far

I set up so if a item in the CollectionView A is disabled it become Red, but it dont become Red.

I have tried to add a event in the Code behind, to try and set SelectedItem to null, but that back fired and just made all events go twice, one for selecting the item on the screen and second for altering the SelectedItem in the code behind.

Code:

private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
      if (Device.RuntimePlatform == Device.iOS)
      {
         var collectionView = sender as CollectionView;
         if (collectionView == null) return;

         if (collectionView.SelectedItem != null)
         {
             collectionView.SelectedItem = null;
         }
      }
}

(I know it is a big no no to do logic stuff in the Code Behind that is not design logic, but I need to get this solved or have a quick and dirty fix because of time pressure.)

Sorry for the wall of text

Body:
Use a TapGestureRecognizer.

Below, MyItemCommand is defined in MyViewModel and {Binding .} refers to the item selected in ItemsSource.

<DataTemplate ...>
  <StackLayout>
    <StackLayout.GestureRecognizers>
      <TapGestureRecognizer Command="{Binding Source={RelativeSource AncestorType={x:Type vm:MyViewModel}},
                                              Path=MyItemCommand}"
                            CommandParameter="{Binding .}"/>
    </StackLayout.GestureRecognizers>
    ...


问:
How to add embedded resource JSON file to ConfigurationBuilder without creating a temporary file?
I have  appsettings.json  with build action set to Embedded Resource. I usually extract the file and make a new copy of it as follows.

```<code>string jsonFullPath = Path.Combine(FileSystem.AppDataDirectory, "namespace.directory.appsettings.json");
Assembly assembly = Assembly.GetExecutingAssembly();

using (Stream resourceFileStream = assembly.GetManifestResourceStream(resourceFilename))
{
    if (resourceFileStream != null)
    {
        using (FileStream fileStream = File.Create(jsonFullPath))
        {
            resourceFileStream.CopyTo(fileStream);
        }
    }
}
</code>```

And add the copy to an instance of ConfigurationBuilder as follows.

```<code>Configuration = new ConfigurationBuilder()
    .AddJsonFile(jsonFullPath, optional: true, reloadOnChange: true)
    .Build();
</code>```

Question

Is it possible to make ConfigurationBuilder use the embedded JSON file directly without creating a new temporary file as I did above? If yes, how to do so?

答:
In ASP.NET Core 6, streaming the appsettings.ini from an embedded resource is done as follows:</p>
```<code>var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    ContentRootPath = AppContext.BaseDirectory,//Path.GetFullPath(Directory.GetCurrentDirectory()),
    Args = args,
});

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    using (var resourceStream = this.GetType().Assembly.GetManifestResourceStream("Namespace.filename.ext"))
    {
        config.AddJsonStream(resourceStream);
    }
}
...
</code>```

Body:
I have  appsettings.json  with build action set to Embedded Resource. I usually extract the file and make a new copy of it as follows.

string jsonFullPath = Path.Combine(FileSystem.AppDataDirectory, "namespace.directory.appsettings.json");
Assembly assembly = Assembly.GetExecutingAssembly();

using (Stream resourceFileStream = assembly.GetManifestResourceStream(resourceFilename))
{
    if (resourceFileStream != null)
    {
        using (FileStream fileStream = File.Create(jsonFullPath))
        {
            resourceFileStream.CopyTo(fileStream);
        }
    }
}

And add the copy to an instance of ConfigurationBuilder as follows.

Configuration = new ConfigurationBuilder()
    .AddJsonFile(jsonFullPath, optional: true, reloadOnChange: true)
    .Build();

Question

Is it possible to make ConfigurationBuilder use the embedded JSON file directly without creating a new temporary file as I did above? If yes, how to do so?

Body:
In ASP.NET Core 6, streaming the appsettings.ini from an embedded resource is done as follows:

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    ContentRootPath = AppContext.BaseDirectory,//Path.GetFullPath(Directory.GetCurrentDirectory()),
    Args = args,
});

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    using (var resourceStream = this.GetType().Assembly.GetManifestResourceStream("Namespace.filename.ext"))
    {
        config.AddJsonStream(resourceStream);
    }
}
...


问:
more flexible or advanced page creation in wordpress 3.2.1
I've been looking into ways to make the wordpress page creation be a little more flexible.

I've gotten as far as defining my own template pages and using those to create the new pages, but I'd like to be able to have a way to input content for more than just the one post div.

When creating a page it is similar to creating a post - i.e you get to edit a title and a bit of content but that's it.

Does anyone know of a method or plugin that would allow editing the title and content of 2 divs on the same page during page creation?

答:
I suggest you use Magic Fields. It basically allows you to add a lot of custom fields. It allows you to build advanced templates. Example of one I created recently:</p>

```<code><?php get_header();?> <div id="left_sidebar" class="grid_3">
    <ul class="post_menu sf-menu sf-vertical">
        <li class="active"><a href="<?php echo get_pagelink($post->ID); ?>"><?php echo $post->post_title; ?></a></li>

        <?php $currentPost = $post; ?>

        <!-- Start Loop -->
        <?php   $args=array(
                  'post_type' => "post",
                  'category__in' => get_page_cats($post->ID),
                  'showposts' => '5000',
                  'order_by' => 'date',
                  'order' => 'ASC');
        ?>
        <?php $menu_posts = array(); ?>

        <?php $the_query = new WP_Query( $args );?>
        <?php if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); ?>

         <?php if($related_content = get('menu_parent_page')): ?>
            <?php $menu_posts[$related_content]['sub'][] = array('id' => $post->ID, 'title' => $post->post_title); ?>
         <?php else: ?>
            <?php $menu_posts[$post->ID]['parent'] = array('id' => $post->ID, 'title' => $post->post_title); ?>
         <?php endif; ?>

        <?php endwhile; else: ?>

        <?php endif; ?>
        <?php wp_reset_query(); ?>

        <?php $postCount = 1; ?>
        <?php $totalPosts = sizeof($menu_posts); ?>

        <?php if($totalPosts > 0):?>
        <?php foreach($menu_posts as $the_post): ?>
            <li <?php if($postCount == $totalPosts): ?> class="last<?php if($currentPost->ID == $the_post['parent']['id']): ?> active<?php endif; ?>"<?php elseif($currentPost->ID == $the_post['parent']['id']): ?> class="active"<?php endif; ?> ><a href="<?php echo get_pagelink($the_post['parent']['id']); ?>"><?php echo $the_post['parent']['title']; ?></a>

        <?php $totalSubPosts = sizeof($the_post['sub']); ?>
        <?php $subPostCount = 1; ?>

        <?php if($totalSubPosts > 0):?>
        <ul>
            <?php foreach($the_post['sub'] as $sub_post): ?>
                    <li <?php if($subPostCount == $totalSubPosts): ?> class="last" <?php endif; ?>><a href="<?php echo get_pagelink($sub_post['id']); ?>"><?php echo $sub_post['title']; ?></a>
            <?php $subPostCount++; ?>
            <?php endforeach; ?>

        </ul>
        <?php endif; ?>
         </li>
        <?php $postCount++; ?>

        <?php endforeach; ?>
        <?php endif; ?>

    </ul>
</div>

<div id="page_content" class="grid_9">

    <!-- Start Loop -->
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <h1 class="page_header"><?php the_title(); ?></h1>
        <?php the_content(); ?>
                        <?php $logo_image = get_image('extra_logo_image', 1, 1, 0);  ?>
        <?php if($logo_image): ?>
        <img class="brand_logo_all" src="<?php echo $logo_image; ?>" alt="logo" />
        <?php endif; ?>
    <?php endwhile; else: ?>
        <p>An Error Occurred</p>
        <?php endif; ?>
    <?php wp_reset_query(); ?>
    <!-- End Loop -->

    <?php $download_items = get_group('download'); ?>
    <?php if($download_items): foreach ($download_items as $item): ?>
    <div class="download">
        <a href="<?php echo $item['download_pdf'][1];?>">
            <div class="pdf">
                <table>
                    <tr>
                        <td><?php echo $item['download_description'][1];?></td>
                    </tr>
                </table>
            </div>
        </a>
    </div>
    <?php endforeach; endif;?>

    <?php $disable_call_to_action = get('extra_disable_call_to_action'); ?>
    <?php if(!$disable_call_to_action): ?>
    <?php include_once(TEMPLATEPATH . "/call_to_action.php"); ?>
    <?php endif; ?>

    </div><!-- #page_content -->

</div><!-- #container --><?php get_footer();?>
</code>```

Body:
I suggest you use Magic Fields. It basically allows you to add a lot of custom fields. It allows you to build advanced templates. Example of one I created recently:

<?php get_header();?> <div id="left_sidebar" class="grid_3">
    <ul class="post_menu sf-menu sf-vertical">
        <li class="active"><a href="<?php echo get_pagelink($post->ID); ?>"><?php echo $post->post_title; ?></a></li>

        <?php $currentPost = $post; ?>

        <!-- Start Loop -->
        <?php   $args=array(
                  'post_type' => "post",
                  'category__in' => get_page_cats($post->ID),
                  'showposts' => '5000',
                  'order_by' => 'date',
                  'order' => 'ASC');
        ?>
        <?php $menu_posts = array(); ?>

        <?php $the_query = new WP_Query( $args );?>
        <?php if ($the_query->have_posts()) : while ($the_query->have_posts()) : $the_query->the_post(); ?>

         <?php if($related_content = get('menu_parent_page')): ?>
            <?php $menu_posts[$related_content]['sub'][] = array('id' => $post->ID, 'title' => $post->post_title); ?>
         <?php else: ?>
            <?php $menu_posts[$post->ID]['parent'] = array('id' => $post->ID, 'title' => $post->post_title); ?>
         <?php endif; ?>

        <?php endwhile; else: ?>

        <?php endif; ?>
        <?php wp_reset_query(); ?>

        <?php $postCount = 1; ?>
        <?php $totalPosts = sizeof($menu_posts); ?>

        <?php if($totalPosts > 0):?>
        <?php foreach($menu_posts as $the_post): ?>
            <li <?php if($postCount == $totalPosts): ?> class="last<?php if($currentPost->ID == $the_post['parent']['id']): ?> active<?php endif; ?>"<?php elseif($currentPost->ID == $the_post['parent']['id']): ?> class="active"<?php endif; ?> ><a href="<?php echo get_pagelink($the_post['parent']['id']); ?>"><?php echo $the_post['parent']['title']; ?></a>

        <?php $totalSubPosts = sizeof($the_post['sub']); ?>
        <?php $subPostCount = 1; ?>

        <?php if($totalSubPosts > 0):?>
        <ul>
            <?php foreach($the_post['sub'] as $sub_post): ?>
                    <li <?php if($subPostCount == $totalSubPosts): ?> class="last" <?php endif; ?>><a href="<?php echo get_pagelink($sub_post['id']); ?>"><?php echo $sub_post['title']; ?></a>
            <?php $subPostCount++; ?>
            <?php endforeach; ?>

        </ul>
        <?php endif; ?>
         </li>
        <?php $postCount++; ?>

        <?php endforeach; ?>
        <?php endif; ?>

    </ul>
</div>

<div id="page_content" class="grid_9">

    <!-- Start Loop -->
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <h1 class="page_header"><?php the_title(); ?></h1>
        <?php the_content(); ?>
                        <?php $logo_image = get_image('extra_logo_image', 1, 1, 0);  ?>
        <?php if($logo_image): ?>
        <img class="brand_logo_all" src="<?php echo $logo_image; ?>" alt="logo" />
        <?php endif; ?>
    <?php endwhile; else: ?>
        <p>An Error Occurred</p>
        <?php endif; ?>
    <?php wp_reset_query(); ?>
    <!-- End Loop -->

    <?php $download_items = get_group('download'); ?>
    <?php if($download_items): foreach ($download_items as $item): ?>
    <div class="download">
        <a href="<?php echo $item['download_pdf'][1];?>">
            <div class="pdf">
                <table>
                    <tr>
                        <td><?php echo $item['download_description'][1];?></td>
                    </tr>
                </table>
            </div>
        </a>
    </div>
    <?php endforeach; endif;?>

    <?php $disable_call_to_action = get('extra_disable_call_to_action'); ?>
    <?php if(!$disable_call_to_action): ?>
    <?php include_once(TEMPLATEPATH . "/call_to_action.php"); ?>
    <?php endif; ?>

    </div><!-- #page_content -->

</div><!-- #container --><?php get_footer();?>


问:
C# .Net Core Web API Check CustomSignature
I am new the API in general, let me give you the background of the API and what I want it to do.

I have a API have that are external facing and so every incoming request are required to check the signature from header. literality my code in every controller call are checking the signature and created many duplicated code.

my question is how can reduces those duplicated code ? do I use Custom Attributes, or AuthorizeAttribute

here are some of the example code:

```<code>[Route("[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
  public async Task<Result> Call_1(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
  public async Task<Result> Call_2(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
}
</code>```

above code is just for showing, the actual Sinature checking logic is around 20 lines of code on every single controller method.

答:
You can use token based authentication or filter method. For reference

Token based authentication

Custom Filter

Body:
I am new the API in general, let me give you the background of the API and what I want it to do.

I have a API have that are external facing and so every incoming request are required to check the signature from header. literality my code in every controller call are checking the signature and created many duplicated code.

my question is how can reduces those duplicated code ? do I use Custom Attributes, or AuthorizeAttribute

here are some of the example code:

[Route("[controller]")]
[ApiController]
public class ExampleController : ControllerBase
{
  public async Task<Result> Call_1(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
  public async Task<Result> Call_2(Rquest request)
  {
    string signaturel;
    signature = Util.getHeaderSignature(request);

    if(unit.IsSinatureValid(signaturel, someVar1, someVar2))
    {
      (My logic)
    }
    else{ return "InvalidSinaturemessage" }
  }
}

above code is just for showing, the actual Sinature checking logic is around 20 lines of code on every single controller method.


问:
Should we change the Password in the Application pool in server if the Active Directory ID password is reset?
We are resetting the password of Active directory service account used in server for

Identity in Application Pool

Certificate  Access Permission

Folder share access permissions

Windows Scheduler job permission

HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > Services > EventLog (Permissions)

Should we modify the all the places after password reset?

答:
No need to reset password for application pool.You can directly entered into application pool but for accessing the sites presents in application pool using identity.You will need new password that you have reset(Indirectly we can say for application pool it auto update the password there is no need of separately change password of application pool).

Windows Domain accounts are used as identities to run IIS App Pools.
Whenever the password of a domain account is changed in the domain
controller, the new password has to be updated individually in all
associated App Pools for web applications to run without any
hindrance. With each domain account running numerous App Pools,
changing all the passwords manally becomes tedious.

Same for Certificate Access Permission, Folder share access permissions, HKEY_LOCAL_MACHINE > SYSTEM > CurrentControlSet > Services > EventLog (Permissions) we don't require change passoword.

It is different for Windows Scheduler job permission we need to change password because in backend Window Scheduler Job is working with old password but all the schedule job will be failed.You need to update the password manually here.

For more information you can refer this Document


问:
AnimatedVisibility doesn't work in Canvas
When I use AnimatedVisibility around Canvas, it doesn't work.

```<code>AnimatedVisibility(
    visible = firstShowVisible,
    modifier = Modifier.align(Alignment.Center),
    enter = fadeIn(0f, tween(300, 3100, LinearEasing))
) {
    Canvas(modifier = Modifier) {
        drawCircleBackground(color, radius, strokeWidth)
        drawCircleProgress(color, progress, radius, strokeWidth)
    }
}
</code>```

The Canvas item would show immediately, rather than fade in slowly.

And firstShowVisible is changed by

```<code>var firstShowVisible by remember { mutableStateOf(false) }
LaunchedEffect(true) {
    firstShowVisible = true
}
</code>```

It works for other items, cannot work for Canvas only to me

答:
It's solved.
It's because the arc I draw is not in the area of the outer Box.
When I make the outer Box fillMaxSize, it works.</p>

Body:
When I use AnimatedVisibility around Canvas, it doesn't work.

AnimatedVisibility(
    visible = firstShowVisible,
    modifier = Modifier.align(Alignment.Center),
    enter = fadeIn(0f, tween(300, 3100, LinearEasing))
) {
    Canvas(modifier = Modifier) {
        drawCircleBackground(color, radius, strokeWidth)
        drawCircleProgress(color, progress, radius, strokeWidth)
    }
}

The Canvas item would show immediately, rather than fade in slowly.

And firstShowVisible is changed by

var firstShowVisible by remember { mutableStateOf(false) }
LaunchedEffect(true) {
    firstShowVisible = true
}

It works for other items, cannot work for Canvas only to me


问:
Getting TSV file output excluding 2 resource types from the az resource list in Azure CLI
I need to get the azure resource list from the azure CLI excluding 2 kinds of resource types and output the file to a TSV file. I was able do this via PowerShell from the following command.

PowerShell Command

```<code>get-azresource | where ResourceType -notmatch microsoft.network/privatednszones/virtualnetworklinks | where ResourceType -notmatch microsoft.insights/actiongroups | export-csv C:\Users\7.csv
</code>```

I need to get this result from Azure CLI excluding the mentioned resource types to TSV file (Since we cannot get the Azure CLI output in CSV)

答:
You need to lookup the info for Export-Csv, where you can see it has a parameter -Delimiter you use to set a different character as field separator (in your case a TAB character) instead of the default comma.

To prevent an extra line on top of the output file with field type definitions, there is also a switch -NoTypeInformation

Then looking at your code I have some remarks:

You use -notmatch which is a regex comparison operator, but the strings to compare against have characters that have special meaning in regex (most notably the dot)

You seem to not use quotes anywhere and because your strings and output path do not contain spaces, in this case that is not a problem. However, I think it is a good habit to always use single quotes around such strings and paths

Try

```<code># the resource types to exclude
$exclude = 'microsoft.network/privatednszones/virtualnetworklinks', 'microsoft.insights/actiongroups'
# create a regex string from the $exclude array, where the elements are joined with the regex OR ('|')
$notThese = ($exclude | ForEach-Object { [regex]::Escape($_) }) -join '|'

Get-AzResource | Where-Object {$_.ResourceType -notmatch $notThese} |
Export-Csv -Path 'C:\Users\7.tsv' -Delimiter "`t" -NoTypeInformation
</code>```

Body:
I need to get the azure resource list from the azure CLI excluding 2 kinds of resource types and output the file to a TSV file. I was able do this via PowerShell from the following command.

PowerShell Command

get-azresource | where ResourceType -notmatch microsoft.network/privatednszones/virtualnetworklinks | where ResourceType -notmatch microsoft.insights/actiongroups | export-csv C:\Users\7.csv

I need to get this result from Azure CLI excluding the mentioned resource types to TSV file (Since we cannot get the Azure CLI output in CSV)

Body:
You need to lookup the info for Export-Csv, where you can see it has a parameter -Delimiter you use to set a different character as field separator (in your case a TAB character) instead of the default comma.

To prevent an extra line on top of the output file with field type definitions, there is also a switch -NoTypeInformation

Then looking at your code I have some remarks:

You use -notmatch which is a regex comparison operator, but the strings to compare against have characters that have special meaning in regex (most notably the dot)

You seem to not use quotes anywhere and because your strings and output path do not contain spaces, in this case that is not a problem. However, I think it is a good habit to always use single quotes around such strings and paths

Try

# the resource types to exclude
$exclude = 'microsoft.network/privatednszones/virtualnetworklinks', 'microsoft.insights/actiongroups'
# create a regex string from the $exclude array, where the elements are joined with the regex OR ('|')
$notThese = ($exclude | ForEach-Object { [regex]::Escape($_) }) -join '|'

Get-AzResource | Where-Object {$_.ResourceType -notmatch $notThese} |
Export-Csv -Path 'C:\Users\7.tsv' -Delimiter "`t" -NoTypeInformation


问:
ActiveStorage - has_one_attached ignores service option
In my Ruby on Rails 6.1.3.2 application, I'm trying to has_one_attached service option to upload one of the model attachments to the separate S3 bucket.
Here is how my storage.yml looks like:

```<code>test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

amazon:
  service: S3
  access_key_id: <%= ENV['AWS_ACCESS_KEY_I'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
  region: us-east-2
  bucket: <%= ENV['AWS_BUCKET'] %>

amazon_logos_images:
  service: S3
  access_key_id: <%= ENV['AWS_ACCESS_KEY_I'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
  region: us-east-2
  bucket: <%= ENV['AWS_LOGOS_BUCKET'] %>
</code>```

In my production.rb I have the following Active Storage configuration:

```<code>config.active_storage.service = :amazon
</code>```

My Logo model looks like this:

```<code>class Logo < ApplicationRecord
  has_one_attached :image, service: :amazon_logos_images
end
</code>```

Unfortunately, when I create a new Logo record, the image is uploaded to the amazon bucket instead of amazon_logos_images. Any idea why the service option is ignored by the has_one_attached method?

答:
If you come from 6.0:

If our project is already using Active Storage and when we upgrade to Rails 6.1, we should run rake app:update to make sure service_name column is added to the internal ActiveStorageBlob model.

https://blog.saeloun.com/2020/02/03/rails-allows-configure-service-for-attachments-to-activestorage.html

Otherwise check that AWS_LOGOS_BUCKET is properly being populated (i.e. is not the wrong bucket)

Body:
In my Ruby on Rails 6.1.3.2 application, I'm trying to has_one_attached service option to upload one of the model attachments to the separate S3 bucket.
Here is how my storage.yml looks like:

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

amazon:
  service: S3
  access_key_id: <%= ENV['AWS_ACCESS_KEY_I'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
  region: us-east-2
  bucket: <%= ENV['AWS_BUCKET'] %>

amazon_logos_images:
  service: S3
  access_key_id: <%= ENV['AWS_ACCESS_KEY_I'] %>
  secret_access_key: <%= ENV['AWS_SECRET_ACCESS_KEY'] %>
  region: us-east-2
  bucket: <%= ENV['AWS_LOGOS_BUCKET'] %>

In my production.rb I have the following Active Storage configuration:

config.active_storage.service = :amazon

My Logo model looks like this:

class Logo < ApplicationRecord
  has_one_attached :image, service: :amazon_logos_images
end

Unfortunately, when I create a new Logo record, the image is uploaded to the amazon bucket instead of amazon_logos_images. Any idea why the service option is ignored by the has_one_attached method?


问:
How can I clear browser cache (memory / disk cache) after logout?
I use asp net core mvc + js. One type of my pages have cache.

```<code>[ResponseCache(Location = ResponseCacheLocation.Client, Duration = 60)]
public async Task<IActionResult> StaticContent(string path)
{
    // code
}
</code>```

I have a problem when user logout on this page. User sees his account after logout because page was cache. If refresh page cache clear and user does not see account.

I try location.reload(); on js when logout click but reload work earlier than logout work on server. I try change Vary header but I change Vary only page which I redirect after logout

How can I clear cache after logout? Any ideas?

答:
In your logout post, you can clear a session that may solve your problem.</p>
```<code>HttpContext.Session.Clear(); //this will clear all session
HttpContext.Session.Remove("sessionName"); //this will clear a specific session
</code>```

Body:
I use asp net core mvc + js. One type of my pages have cache.

[ResponseCache(Location = ResponseCacheLocation.Client, Duration = 60)]
public async Task<IActionResult> StaticContent(string path)
{
    // code
}

I have a problem when user logout on this page. User sees his account after logout because page was cache. If refresh page cache clear and user does not see account.

I try location.reload(); on js when logout click but reload work earlier than logout work on server. I try change Vary header but I change Vary only page which I redirect after logout

How can I clear cache after logout? Any ideas?

Body:
In your logout post, you can clear a session that may solve your problem.

HttpContext.Session.Clear(); //this will clear all session
HttpContext.Session.Remove("sessionName"); //this will clear a specific session


问:
Pandas keep rows where column values change at least twice
Good day,

I have a large dataset with columns that keep track of the scores each person obtains. Here is a sample of the dataset:

In:

```<code>data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df
</code>```

Out:

```<code>    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7
</code>```

I need to find the rows where the column values change at least twice. For example:

Row 0: All values are the same, no change

Row 1: All values are the same, no change

Row 2: 1st and 2nd values differ, 1 change

Row 3: 2nd and 3rd values differ, 1 change

Row 4: 1st, 2nd and 4th values differ, 2 changes

That means that only row 4 meets my requirements.

Thus, the desired output would be:

```<code>    person_id   score_1 score_2 score_3 score_4
4   25          9       8       8       7
</code>```

All help greatly appreciated!

答:
Mozway's answer for the case A->B->A->B counts is brillant:

```<code>df[df.filter(like='score').diff(axis=1).ne(0).sum(axis=1).gt(2)]
</code>```

A more plain answer, based on Mozway's one could be :

```<code>df[ # following lines build a boolean mask
    df.filter(like='score')     # keep only scores columns
      .diff(axis=1).iloc[:, 1:] # diff the columns and keep all except the first one whose values are all `NaN`
      .ne(0).sum(axis=1)        # count changes: values that differ from 0
      .ge(2)                    # finish the boolean mask: changes >= 2
  ]
</code>```

Body:
Good day,

I have a large dataset with columns that keep track of the scores each person obtains. Here is a sample of the dataset:

In:

data = [[7, 10, 10, 10, 10], [17, 10, 10, 10, 10], [18, 8, 10, 10, 10], [20, 10, 10, 9, 9], [25, 9, 8, 8, 7]]
df = pd.DataFrame(data, columns = ['person_id', 'score_1', 'score_2', 'score_3', 'score_4'])
df

Out:

    person_id   score_1 score_2 score_3 score_4
0   7           10      10      10      10
1   17          10      10      10      10
2   18          8       10      10      10
3   20          10      10      9       9
4   25          9       8       8       7

I need to find the rows where the column values change at least twice. For example:

Row 0: All values are the same, no change

Row 1: All values are the same, no change

Row 2: 1st and 2nd values differ, 1 change

Row 3: 2nd and 3rd values differ, 1 change

Row 4: 1st, 2nd and 4th values differ, 2 changes

That means that only row 4 meets my requirements.

Thus, the desired output would be:

    person_id   score_1 score_2 score_3 score_4
4   25          9       8       8       7

All help greatly appreciated!

Body:
Mozway's answer for the case A->B->A->B counts is brillant:

df[df.filter(like='score').diff(axis=1).ne(0).sum(axis=1).gt(2)]

A more plain answer, based on Mozway's one could be :

df[ # following lines build a boolean mask
    df.filter(like='score')     # keep only scores columns
      .diff(axis=1).iloc[:, 1:] # diff the columns and keep all except the first one whose values are all `NaN`
      .ne(0).sum(axis=1)        # count changes: values that differ from 0
      .ge(2)                    # finish the boolean mask: changes >= 2
  ]


问:
Spring JUnit5 test not loading resource values
I know there are a lot of questions regarding this, but all of them are suggesting to use @TestPropertySource and @EnableConfigurationProperties. I have already used them but still not working.

Config class - src/main/java/com/demo/config/AppConfig.java

```<code>@Configuration
@ConfigurationProperties(prefix = "api")
@Getter
@Setter
public class AppConfig {
   private List<String> providers;
   private boolean enabled;
}
</code>```

Property source - src/test/resources/application-test.yml

```<code>api:
  enabled: true
  providers:
    - prov1
    - prov2
</code>```

Test class - src/test/../MyTest.java

```<code>@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTestConfiguration.class)
class MyTest {

    @Autowired
    private AppConfig appConfig;

    @Test
    void runTest() {//some code with breakpoint}
}
</code>```

Test configuraton - src/test/.../MyTestConfiguration.java

```<code>@TestConfiguration
@TestPropertySource(locations = "classpath:application-test.yml")
@EnableConfigurationProperties(value = AppConfig.class)
@ActiveProfiles("test")
public class MyTestConfiguration {
}
</code>```

When I run the test, runTest() and inspect autowired appConfig value, the providers are empty and enabled is false. That means the values in yml file were not loaded.
I found a similar kind of question, but without answer.

答:
I modified MyTest as @sergey-tsypanov suggested and then deleted MyTestConfiguration class. It worked and appConfig has values.

```<code>@SpringBootTest(classes = AppConfig.class)
@EnableAutoConfiguration
@ActiveProfiles("test")
class MyTest {

    @Autowired
    private AppConfig appConfig;

    @Test
    void runTest() {//some code with breakpoint}
}
</code>```

It seems even if I don't have @SpringBootApplication, I can use @SpringBootTest and @EnableAutoConfiguration. I had spring Boot dependency in pom.xml

Body:
I know there are a lot of questions regarding this, but all of them are suggesting to use @TestPropertySource and @EnableConfigurationProperties. I have already used them but still not working.

Config class - src/main/java/com/demo/config/AppConfig.java

@Configuration
@ConfigurationProperties(prefix = "api")
@Getter
@Setter
public class AppConfig {
   private List<String> providers;
   private boolean enabled;
}

Property source - src/test/resources/application-test.yml

api:
  enabled: true
  providers:
    - prov1
    - prov2

Test class - src/test/../MyTest.java

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTestConfiguration.class)
class MyTest {

    @Autowired
    private AppConfig appConfig;

    @Test
    void runTest() {//some code with breakpoint}
}

Test configuraton - src/test/.../MyTestConfiguration.java

@TestConfiguration
@TestPropertySource(locations = "classpath:application-test.yml")
@EnableConfigurationProperties(value = AppConfig.class)
@ActiveProfiles("test")
public class MyTestConfiguration {
}

When I run the test, runTest() and inspect autowired appConfig value, the providers are empty and enabled is false. That means the values in yml file were not loaded.
I found a similar kind of question, but without answer.

Body:
I modified MyTest as @sergey-tsypanov suggested and then deleted MyTestConfiguration class. It worked and appConfig has values.

@SpringBootTest(classes = AppConfig.class)
@EnableAutoConfiguration
@ActiveProfiles("test")
class MyTest {

    @Autowired
    private AppConfig appConfig;

    @Test
    void runTest() {//some code with breakpoint}
}

It seems even if I don't have @SpringBootApplication, I can use @SpringBootTest and @EnableAutoConfiguration. I had spring Boot dependency in pom.xml


问:
I want to make a function in C that prints a 2D array
I know how to print a 2D array without using a function (using nested for loops), but how would I implement a fuction that prints it.

This is what I tried

```<code>int print_matrix(int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

</code>```

答:
you need to add int M, int N to the function:

```<code>int print_matrix(int M, int N, int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}
</code>```

how to call your fucntion:

```<code>int M = 5;
int N = 4;
//define your array
int arr[M][N];

print_matrix(M, N, arr)
</code>```

Body:
I know how to print a 2D array without using a function (using nested for loops), but how would I implement a fuction that prints it.

This is what I tried

int print_matrix(int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

Body:
you need to add int M, int N to the function:

int print_matrix(int M, int N, int arr[M][N])
{
    for (int i = 0; i < M; i++)
    {
        for (int j = 0; j < N; j++)
        {
            printf("{%i}",arr[i][j]);
        }
        printf("\n");
    }
}

how to call your fucntion:

int M = 5;
int N = 4;
//define your array
int arr[M][N];

print_matrix(M, N, arr)


问:
How can I process this array more efficiently
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

```<code>       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }
</code>```

答:
You can use map to remove some of your own looping

```<code>let contacts = ["John Doe", "Mary Blog"]
let result = contacts.map { $0.components(separatedBy: .whitespacesAndNewlines).map { String($0.prefix(1)) }.joined(separator: "") }
print(result)
</code>```

I don't known if this is any quicker, maybe it gives Apple a chance to fro some optimisation that is hard to do

Body:
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }

Body:
You can use map to remove some of your own looping

let contacts = ["John Doe", "Mary Blog"]
let result = contacts.map { $0.components(separatedBy: .whitespacesAndNewlines).map { String($0.prefix(1)) }.joined(separator: "") }
print(result)

I don't known if this is any quicker, maybe it gives Apple a chance to fro some optimisation that is hard to do


问:
R Shiny REST API communication
I have a shiny app that takes a JSON input file, runs it through a classifier and returns a classified JSON object.
I want the app to be able to communicate with an API. I want the API to post a file to the Shiny App which will do its work and return a classified object.
Basically I want the Shiny app to sit in the background until a file is posted and then do its work.
I know that I can use GET from the httr package to get a file from a url. I can put this in the shiny.server file which is fine if I know the file name for the get command

However the filenames coming from the API will be different. So is there any way that I can make this dynamic according to the Post request that comes from the API.

答:
By now library(plumber) needs to be mentioned as an alternative in this context, however the following example is showing how to handle POST requests directly in shiny.

It is based on Joe Cheng's gist here, which suggests to add an attribute "http_methods_supported" to the UI and use httpResponse to answer the requests.

The below code starts a shiny app in a background R process (This is done only to have a single single file MRE - of course, you can put the app in a separate file and remove the r_bg-line). After the app is launched the parent process sends the iris data.frame to the UI.

In the UI function the req$PATH_INFO is checked (see uiPattern = ".*"), then the numerical columns are multiplied by 10 (query_params$factor) and send back as a json string.

```<code>library(shiny)
library(jsonlite)
library(callr)
library(datasets)

ui <- function(req) {
  # The `req` object is a Rook environment
  # See https://github.com/jeffreyhorner/Rook#the-environment
  if (identical(req$REQUEST_METHOD, "GET")) {
    fluidPage(
      h1("Accepting POST requests from Shiny")
    )
  } else if (identical(req$REQUEST_METHOD, "POST")) {
    # Handle the POST
    query_params <- parseQueryString(req$QUERY_STRING)
    body_bytes <- req$rook.input$read(-1)
    if(req$PATH_INFO == "/iris"){
      postedIris <- jsonlite::fromJSON(rawToChar(body_bytes))
      modifiedIris <- postedIris[sapply(iris, class) == "numeric"]*as.numeric(query_params$factor)
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = jsonlite::toJSON(modifiedIris, dataframe = "columns")
      )
    } else {
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = '{"status": "ok"}'
      )
    }
  }
}
attr(ui, "http_methods_supported") <- c("GET", "POST")

server <- function(input, output, session) {}

app <- shinyApp(ui, server, uiPattern = ".*")
# shiny::runApp(app, port = 80, launch.browser = FALSE, host = "0.0.0.0")
shiny_process <- r_bg(function(x){ shiny::runApp(x, port = 80, launch.browser = FALSE, host = "0.0.0.0") }, args = list(x = app))

library(httr)
r <- POST(url = "http://127.0.0.1/iris?factor=10", body = iris, encode = "json", verbose())
recievedIris <- as.data.frame(fromJSON(rawToChar(r$content)))
print(recievedIris)
shiny_process$kill()
</code>```

Please also check this related PR which is providing further examples (also showing how to use session$registerDataObj) and is aiming at a better description of the httpResponse function.

Title: R Shiny REST API communication

Body:
By now library(plumber) needs to be mentioned as an alternative in this context, however the following example is showing how to handle POST requests directly in shiny.

It is based on Joe Cheng's gist here, which suggests to add an attribute "http_methods_supported" to the UI and use httpResponse to answer the requests.

The below code starts a shiny app in a background R process (This is done only to have a single single file MRE - of course, you can put the app in a separate file and remove the r_bg-line). After the app is launched the parent process sends the iris data.frame to the UI.

In the UI function the req$PATH_INFO is checked (see uiPattern = ".*"), then the numerical columns are multiplied by 10 (query_params$factor) and send back as a json string.

library(shiny)
library(jsonlite)
library(callr)
library(datasets)

ui <- function(req) {
  # The `req` object is a Rook environment
  # See https://github.com/jeffreyhorner/Rook#the-environment
  if (identical(req$REQUEST_METHOD, "GET")) {
    fluidPage(
      h1("Accepting POST requests from Shiny")
    )
  } else if (identical(req$REQUEST_METHOD, "POST")) {
    # Handle the POST
    query_params <- parseQueryString(req$QUERY_STRING)
    body_bytes <- req$rook.input$read(-1)
    if(req$PATH_INFO == "/iris"){
      postedIris <- jsonlite::fromJSON(rawToChar(body_bytes))
      modifiedIris <- postedIris[sapply(iris, class) == "numeric"]*as.numeric(query_params$factor)
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = jsonlite::toJSON(modifiedIris, dataframe = "columns")
      )
    } else {
      httpResponse(
        status = 200L,
        content_type = "application/json",
        content = '{"status": "ok"}'
      )
    }
  }
}
attr(ui, "http_methods_supported") <- c("GET", "POST")

server <- function(input, output, session) {}

app <- shinyApp(ui, server, uiPattern = ".*")
# shiny::runApp(app, port = 80, launch.browser = FALSE, host = "0.0.0.0")
shiny_process <- r_bg(function(x){ shiny::runApp(x, port = 80, launch.browser = FALSE, host = "0.0.0.0") }, args = list(x = app))

library(httr)
r <- POST(url = "http://127.0.0.1/iris?factor=10", body = iris, encode = "json", verbose())
recievedIris <- as.data.frame(fromJSON(rawToChar(r$content)))
print(recievedIris)
shiny_process$kill()

Please also check this related PR which is providing further examples (also showing how to use session$registerDataObj) and is aiming at a better description of the httpResponse function.


问:
Sorting grouped bar plots dependently in Plotly
I've 3 x-values (Grouped Bar Chart) for each row which are separated by name (the plot below), displayed using fig.update_xaxes(categoryorder='category ascending').

The values are dependent on the name column.

A, B, C.

It'll always sort based on the A value, I want to sort it based on B and C independently. (sorting by largest red, which the fifth red value should come first, then sorting by largest brown).

how can I achieve that without repeating myself?

Complete Reproducible Code:

want to sort players first by Weight then by Height and at the end, by Score.

like this:

first sort by Weight: [Dante, Evan, Arthur, Carlos, Frank, Bneson]

second sort by Height: [Arthur, Frank, Dante, Carlos, Evan, Benson]...

import pandas as pd
import numpy as np
import plotly.graph_objects as go

dftst = pd.DataFrame([('Arthur', 110, 200, 10),
                   ('Benson', 50, 160, 12),
                   ('Carlos', 90, 170, 14),
                   ('Dante', 160, 180, 11),
                   ('Evan', 130, 165, 18),
                   ('Frank', 70, 190, 20)],
           columns=('Name', 'Weight', 'Height', 'Score'))

pnames = dftst['Name']
x = list(range(len(pnames)))

bar_plots = [
  go.Bar(x=x, y=dftst['Weight'], name='Weight', marker=go.bar.Marker(color='#0343df')),
  go.Bar(x=x, y=dftst['Height'], name='Height', marker=go.bar.Marker(color='#e50000')),
  go.Bar(x=x, y=dftst['Score'], name='Score', marker=go.bar.Marker(color='green')),
]

layout = go.Layout(
  title=go.layout.Title(text="Players", x=0.5),
  yaxis_title="Players Details",
  xaxis_tickmode="array",
  xaxis_tickvals=list(range(6)),
  xaxis_ticktext=tuple(dftst['Name'].values))

fig = go.Figure(data=bar_plots, layout=layout)

fig.update_layout(
    autosize=False,
    width=600,
    height=700)

fig.update_layout(barmode='group', xaxis={'categoryorder':'category ascending'})

fig.update_xaxes(
    showgrid=True,
    ticks="outside",
    tickson="boundaries",
    ticklen=20
)

fig.show()
```

答:
if columns are independent, you can treat them as independent series

hence create by a list of sorted series

fix up trace names (and legend) by updating traces

```<code>import pandas as pd
import numpy as np
import plotly.express as px

df = pd.DataFrame({c: np.random.randint(1, 100, 40) for c in "ABC"})

fig = px.bar(y=[df[c].sort_values(ascending=0) for c in df.columns],barmode="group")

for t, c in zip(fig.data, df.columns):
    t.update(name=c)

fig
</code>```

Body:
if columns are independent, you can treat them as independent series

hence create by a list of sorted series

fix up trace names (and legend) by updating traces

import pandas as pd
import numpy as np
import plotly.express as px

df = pd.DataFrame({c: np.random.randint(1, 100, 40) for c in "ABC"})

fig = px.bar(y=[df[c].sort_values(ascending=0) for c in df.columns],barmode="group")

for t, c in zip(fig.data, df.columns):
    t.update(name=c)

fig


问:
I am facing issue in map fuction using useEffect and useState
I am binding my data with map function but i am getting some errors .. i think the issue is on useState function, when i am putting data in setAllItems(data) and calling in map function like allItems.map() so i am getting error in Dom that allitems is not a function... i am really confuse about how to put data in useState and call in map function</p>
```<code>      import 'bootstrap/dist/js/bootstrap.bundle.min.js';
      import '../StockPage/Stock.css'
      import '../StockPage/stockValidation'
      import { useFormik, Form, Field } from "formik";
      import { Link} from 'react-router-dom';
      import axios from "axios"

      function Stock() {
          const [item, setItems] = useState({
              itemName: "",
              itemCatagory: "",
              itemPrice: "",
              stockAmount: ""
          })
          const [search,setSearch] =useState('');
          const [allItems, setAllItems] = useState([]);

          useEffect(()=>{

              const load = async()=>{
                  try {
                      const res = await fetch('http://localhost:4000/stock/list')
                      const data = await res.json();
                      // setAllItems(data);

                      console.log(data)
                      console.log(allItems);
                  } catch (error) {
                      console.log(error)
                  }
              }
              load()
              }
              )

          const handleChange = e => {
              const { name, value } = e.target
              setItems({
                  ...item,
                  [name]: value
              })
          }
          const itemSubmit = () => {

              const { itemName, itemCatagory, itemPrice, stockAmount } = item
              if (itemName && itemCatagory && itemPrice && stockAmount) {
                  axios.post("http://localhost:4000/stock", item)
                      .then(res => console.log(res))
              }
              else {
                  alert("Invalid inputs")
              }

          }
            // Search Records here
            const searchRecords = () =>
            {
                alert(search)
                axios.get(``)
                .then(response => {
                  setAllItems(response.data);
                });
            }
             // Delete Employee Record
             const deleteRecord = (productId) =>
             {
               axios.delete(``)
               .then((result)=>{
                  // loadItemsDetail();
               })
               .catch(()=>{
                 alert('Error in the Code');
               });
             };

          return (
              <div className="Stock">
                  <div className="container-fluid">
                      <div className="row">
                          {/* insert area */}
                          <div className="col-lg-4">
                              <h4 className='text-center ml-4 mb-5'>Create New Records</h4>
                              {console.log("Item", item)}
                              {/* <form onSubmit={formik.handleSubmit}> */}
                              <div>
                                  <div className="mx-auto w-75 ">
                                      <div className="form-group ">
                                          <label htmlFor="itemName">Item Name:</label>
                                          <input type="text" className="form-control" id="id_itemName" name="itemName" value={item.itemName} onChange={handleChange}
                                              placeholder="Item Name" />

                                      </div>
                                      <div className="form-group ">
                                          <label htmlFor="itemCategory">Item Category</label>
                                          <input type="text" className="form-control" id="id_itemCategory" name="itemCatagory" value={item.itemCatagory} onChange={handleChange}
                                              placeholder="Item Category" />

                                      </div>
                                      <div className="form-group">
                                          <label htmlFor="itemPrice">Item Price</label>
                                          <input type="text" className="form-control" id="id_itemPrice" name="itemPrice" value={item.itemPrice} onChange={handleChange}
                                              placeholder="Item Price" />

                                      </div>
                                      <div className="form-group">
                                          <label htmlFor="stockAmount">Stock Amount</label>
                                          <input type="text" className="form-control" id="id_Amount" name="stockAmount" value={item.stockAmount} onChange={handleChange}
                                              placeholder="Amount" />

                                      </div>
                                  </div>
                                  <div className='text-center mt-4'>
                                      <button type="submit" className="btn btn-primary" onClick={itemSubmit}>Enter</button>
                                  </div>

                              </div>
                          </div>
                          {/* detailed area */}
                          <div className="col-sm-8">
                              <h5 className="text-center  ml-4 mt-4  mb-5">View Records</h5>
                              <div className="input-group mb-4 mt-3">
                                  <div className="form-outline">
                                      <input type="text" id="form1" onChange={(e) => setSearch(e.target.value)} className="form-control" placeholder="Search Employee Here"
                                      style={{ backgroundColor: "#ececec" }} />
                                  </div>
                                  <button type="button" onClick={searchRecords} className="btn btn-success">
                                      <i className="fa fa-search" aria-hidden="true"></i>
                                  </button>
                              </div>
                              <table className="table table-hover  table-striped table-bordered ml-4 ">
                                  <thead>
                                      <tr>

                                      <th>Item Name</th>
                                      <th>Category</th>
                                      <th>Item Price</th>
                                      <th>Item Amount</th>
                                      <th>Action</th>

                                      </tr>
                                  </thead>
                                  <tbody>
                                      {console.log(allItems)}
                                      {allItems.map((name) =>{

                                          <tr>
                                              <td>{name.itemName}</td>
                                              <td>{name.itemCatagory}</td>
                                              <td>{name.itemPrice}</td>
                                              <td>{name.stockAmount}</td>
                                              <td>
                                                  <a className="text-danger mr-2"
                                                      onClick={() => {
                                                          const confirmBox = window.confirm(
                                                              "Do you really want to delete " + name.itemName
                                                          )
                                                          if (confirmBox === true) {
                                                              deleteRecord(name.id)
                                                          }
                                                      }}> <i className="far fa-trash-alt" style={{ fontSize: "18px", marginRight: "5px" }}></i> </a>

                                                  <Link className=" mr-2" to={`/EditEmployee/editID/${name.id}`}>
                                                      <i className="fa fa-edit" aria-hidden="true"></i>
                                                  </Link>
                                              </td>
                                          </tr>} )}
                                  </tbody>
                              </table>
                          </div>
                      </div>
                  </div>
              </div>
          )
      };

      export default Stock;```

          enter code here
</code>```

答:
There is a lot of irrelevant code in your code snippet. In the future, please try to make a minimal reproducible example to make it easier for people to understand your issue.

The issue here is this bit:

```<code>const data = await res.json();
// setAllItems(data);
</code>```

The error allItems.map is not a function indicates that allItems is not an array, which means that data here is not actually an array but more likely an object like this one:

```<code>{
  data: [...] // your actual array
}
</code>```

I can't give you the actual property name without seeing the actual output of the console.log, but check what is actually returned by your fetch call and you should see how to extract your actual data from the output.

Body:
I am binding my data with map function but i am getting some errors .. i think the issue is on useState function, when i am putting data in setAllItems(data) and calling in map function like allItems.map() so i am getting error in Dom that allitems is not a function... i am really confuse about how to put data in useState and call in map function

      import 'bootstrap/dist/js/bootstrap.bundle.min.js';
      import '../StockPage/Stock.css'
      import '../StockPage/stockValidation'
      import { useFormik, Form, Field } from "formik";
      import { Link} from 'react-router-dom';
      import axios from "axios"

      function Stock() {
          const [item, setItems] = useState({
              itemName: "",
              itemCatagory: "",
              itemPrice: "",
              stockAmount: ""
          })
          const [search,setSearch] =useState('');
          const [allItems, setAllItems] = useState([]);

          useEffect(()=>{

              const load = async()=>{
                  try {
                      const res = await fetch('http://localhost:4000/stock/list')
                      const data = await res.json();
                      // setAllItems(data);

                      console.log(data)
                      console.log(allItems);
                  } catch (error) {
                      console.log(error)
                  }
              }
              load()
              }
              )

          const handleChange = e => {
              const { name, value } = e.target
              setItems({
                  ...item,
                  [name]: value
              })
          }
          const itemSubmit = () => {

              const { itemName, itemCatagory, itemPrice, stockAmount } = item
              if (itemName && itemCatagory && itemPrice && stockAmount) {
                  axios.post("http://localhost:4000/stock", item)
                      .then(res => console.log(res))
              }
              else {
                  alert("Invalid inputs")
              }

          }
            // Search Records here
            const searchRecords = () =>
            {
                alert(search)
                axios.get(``)
                .then(response => {
                  setAllItems(response.data);
                });
            }
             // Delete Employee Record
             const deleteRecord = (productId) =>
             {
               axios.delete(``)
               .then((result)=>{
                  // loadItemsDetail();
               })
               .catch(()=>{
                 alert('Error in the Code');
               });
             };

          return (

                          {/* insert area */}

Create New Records

                              {console.log("Item", item)}
                              {/* <form onSubmit={formik.handleSubmit}> */}

                                          Item Name:
                                          <input type="text" className="form-control" id="id_itemName" name="itemName" value={item.itemName} onChange={handleChange}
                                              placeholder="Item Name" />

                                          Item Category
                                          <input type="text" className="form-control" id="id_itemCategory" name="itemCatagory" value={item.itemCatagory} onChange={handleChange}
                                              placeholder="Item Category" />

                                          Item Price
                                          <input type="text" className="form-control" id="id_itemPrice" name="itemPrice" value={item.itemPrice} onChange={handleChange}
                                              placeholder="Item Price" />

                                          Stock Amount
                                          <input type="text" className="form-control" id="id_Amount" name="stockAmount" value={item.stockAmount} onChange={handleChange}
                                              placeholder="Amount" />

                                      <button type="submit" className="btn btn-primary" onClick={itemSubmit}>Enter</button>

                          {/* detailed area */}

View Records

                                      <input type="text" id="form1" onChange={(e) => setSearch(e.target.value)} className="form-control" placeholder="Search Employee Here"
                                      style={{ backgroundColor: "#ececec" }} />

                                  <button type="button" onClick={searchRecords} className="btn btn-success">

                                  </button>

                                      Item Name
                                      Category
                                      Item Price
                                      Item Amount
                                      Action

                                      {console.log(allItems)}
                                      {allItems.map((name) =>{

                                              {name.itemName}
                                              {name.itemCatagory}
                                              {name.itemPrice}
                                              {name.stockAmount}

                                                   {
                                                          const confirmBox = window.confirm(
                                                              "Do you really want to delete " + name.itemName
                                                          )
                                                          if (confirmBox === true) {
                                                              deleteRecord(name.id)
                                                          }
                                                      }}>

                                                  <Link className=" mr-2" to={`/EditEmployee/editID/${name.id}`}>

                                                  </Link>

} )}

          )
      };

      export default Stock;```

          enter code here

Body:
There is a lot of irrelevant code in your code snippet. In the future, please try to make a minimal reproducible example to make it easier for people to understand your issue.

The issue here is this bit:

const data = await res.json();
// setAllItems(data);

The error allItems.map is not a function indicates that allItems is not an array, which means that data here is not actually an array but more likely an object like this one:

{
  data: [...] // your actual array
}

I can't give you the actual property name without seeing the actual output of the console.log, but check what is actually returned by your fetch call and you should see how to extract your actual data from the output.


问:
PUT and POST only specific fields without getting Serializer error in django
Here i wanted to post my data from thingspeak server to Django models and I have imported them by calling functions from DjangoApp.Thingspeak file.But, in this code GET and DELETE method works perfectly but, POST and PUT generates an error exception however, it also take some time for POST and PUT method too. But, as soon as I re-run my server. It catches value Immediately.
Can anybody help me to debug this...

Here is my code for views.py

```<code>import json
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from DjangoApp.serializers import PatientSerializer
from DjangoApp.models import Patient
from DjangoApp.Thingspeak import tempValue,humValue,bodyTempValue
# Create your views here.

@csrf_exempt

def PatientAPI(request,id=0):
    if request.method == 'GET':
        patients = Patient.objects.all()
        patients_serializer = PatientSerializer(patients,many=True)
        return JsonResponse(patients_serializer.data,safe=False)
    elif request.method == 'POST':
        patient_data = JSONParser().parse(request)
        patient = Patient.objects.create(PatientId=patient_data['PatientId'],PatientName=patient_data['PatientName'],RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue())
        patient_data = json.parse(patient)
        patients_serializer = PatientSerializer(data=patient_data)
        if patients_serializer.is_valid():
            patients_serializer.save()
            return JsonResponse("Added Successfully", safe=False)
        return JsonResponse("Failed to add", safe=False)
    elif request.method == 'PUT':
        patient_data = JSONParser().parse(request)
        if patients_Serializer.is_valid():

patient=Patient.objects.filter(PatientId=patient_data['PatientId']).update(RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue())
            patient = json.parse(patient)
            patients_Serializer = PatientSerializer(patient, data=patient_data)
            return JsonResponse("Updated Successfully", safe=False)
        return JsonResponse("Failed to Update")
    elif request.method == 'DELETE':
        patient = Patient.objects.get(PatientId=id)
        patient.delete()
        return JsonResponse("Deleted Successfully", safe=False)
</code>```

and Thingspeak.py code

```<code>import re
import urllib.request

with urllib.request.urlopen("https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true") as url:

    s = repr(url.read())

    def tempValue():
        temp = re.search('field1":"(.+?)",',s)
        if temp:
            return(temp.group(1))

    def humValue():
       hum = re.search('field2":"(.+?)",',s)
       if hum:
        return(hum.group(1))

    def bodyTempValue():
       bodyTemp = re.search('field3":"(.+?)",',s)
       if bodyTemp:
         return(bodyTemp.group(1))

</code>```

答:
Please do not parse JSON with regexes: JSON is a recursive language which can not be parsed (correctly) with a regular expression since JSON is not a regular language.

But even if you only parse subparts of regexes that might be a regular language, the language is a lot more complicated than what it looks like at first: there are rules about escaping strings, etc. so even if you manage to capture the data through a regex, it would be complicated to process it correctly.

You can interpret it as a JSON object, and then access the values associated with a key:

```<code>import <strong>requests</strong>

url = 'https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true'

response = requests.get(url)<strong>.json()</strong>
temp_value = <strong>response['field1']</strong>
hum_value = <strong>response['field2']</strong>
body_temp_value = <strong>response['field3']</strong></code>```

Body:
Here i wanted to post my data from thingspeak server to Django models and I have imported them by calling functions from DjangoApp.Thingspeak file.But, in this code GET and DELETE method works perfectly but, POST and PUT generates an error exception however, it also take some time for POST and PUT method too. But, as soon as I re-run my server. It catches value Immediately.
Can anybody help me to debug this...

Here is my code for views.py

import json
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from DjangoApp.serializers import PatientSerializer
from DjangoApp.models import Patient
from DjangoApp.Thingspeak import tempValue,humValue,bodyTempValue
# Create your views here.

@csrf_exempt

def PatientAPI(request,id=0):
    if request.method == 'GET':
        patients = Patient.objects.all()
        patients_serializer = PatientSerializer(patients,many=True)
        return JsonResponse(patients_serializer.data,safe=False)
    elif request.method == 'POST':
        patient_data = JSONParser().parse(request)
        patient = Patient.objects.create(PatientId=patient_data['PatientId'],PatientName=patient_data['PatientName'],RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue())
        patient_data = json.parse(patient)
        patients_serializer = PatientSerializer(data=patient_data)
        if patients_serializer.is_valid():
            patients_serializer.save()
            return JsonResponse("Added Successfully", safe=False)
        return JsonResponse("Failed to add", safe=False)
    elif request.method == 'PUT':
        patient_data = JSONParser().parse(request)
        if patients_Serializer.is_valid():

patient=Patient.objects.filter(PatientId=patient_data['PatientId']).update(RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue())
            patient = json.parse(patient)
            patients_Serializer = PatientSerializer(patient, data=patient_data)
            return JsonResponse("Updated Successfully", safe=False)
        return JsonResponse("Failed to Update")
    elif request.method == 'DELETE':
        patient = Patient.objects.get(PatientId=id)
        patient.delete()
        return JsonResponse("Deleted Successfully", safe=False)

and Thingspeak.py code

import re
import urllib.request

with urllib.request.urlopen("https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true") as url:

    s = repr(url.read())

    def tempValue():
        temp = re.search('field1":"(.+?)",',s)
        if temp:
            return(temp.group(1))

    def humValue():
       hum = re.search('field2":"(.+?)",',s)
       if hum:
        return(hum.group(1))

    def bodyTempValue():
       bodyTemp = re.search('field3":"(.+?)",',s)
       if bodyTemp:
         return(bodyTemp.group(1))

Body:
Please do not parse JSON with regexes: JSON is a recursive language which can not be parsed (correctly) with a regular expression since JSON is not a regular language.

But even if you only parse subparts of regexes that might be a regular language, the language is a lot more complicated than what it looks like at first: there are rules about escaping strings, etc. so even if you manage to capture the data through a regex, it would be complicated to process it correctly.

You can interpret it as a JSON object, and then access the values associated with a key:

import requests

url = 'https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true'

response = requests.get(url).json()
temp_value = response['field1']
hum_value = response['field2']
body_temp_value = response['field3']