问:
java.lang.RuntimeException: An error occurred while executing doInBackground() (kotlin)
the only code i have in the doinbackground is  'URL(params[0]).readText()' i chacked params[0] its the write url and also the interet permition is declared in the manefest file im so confuse write now if any on know the error i did please let me know

'

```<code>    class MainActivity : AppCompatActivity() {
    private  val TAG : String  = "mytag"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var downloadData = DownloadData()
        downloadData.execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml")
    }

    inner class DownloadData: AsyncTask<String , Void , String>(){
        override fun doInBackground(vararg params: String): String {
           return  URL(params[0]).readText()
        }

        override fun onPostExecute(result: String) {
            Log.d(TAG , "onpostExecute : link received is $result ")
        }
    }

}
</code>```

'

答:
after some seach here is the solution
in the android mainfest add the falwing 'android:usesCleartextTraffic="true"'</p>

Body:
the only code i have in the doinbackground is  'URL(params[0]).readText()' i chacked params[0] its the write url and also the interet permition is declared in the manefest file im so confuse write now if any on know the error i did please let me know

'

    class MainActivity : AppCompatActivity() {
    private  val TAG : String  = "mytag"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var downloadData = DownloadData()
        downloadData.execute("http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml")
    }

    inner class DownloadData: AsyncTask<String , Void , String>(){
        override fun doInBackground(vararg params: String): String {
           return  URL(params[0]).readText()
        }

        override fun onPostExecute(result: String) {
            Log.d(TAG , "onpostExecute : link received is $result ")
        }
    }

}

'


来源: stackexchange

问:
Div is not fitting the space available
I know that this question has already been asked, but I tried everything and I haven't find a solution, so I'm asking again, my apologizes :-).

I'm trying to make my row fill all the remaining screen space of the page, however, my row never shrink, it stays at his initial size.

Notice that my map fits the size of the div.

Here is the code that i'm using :

```<code><div class="row">
  <div class="col-xl-12 col-md-12 mb-12 col-lg-12 ">
    <div class="card shadow mb-4 h-100">

      <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">
          Carte des balises
        </h6>
      </div>

      <div class="card-body">
        <div id="map"></div>
      </div>

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

And there is the render of the page :

If someone could give me some clues, I would really appreciate it !

Thanks in advance, :)

答:
```<code><div class="card shadow mb-4 h-100">
</code>```

the h-100 class here says take 100% height of it's parent and the parent element

```<code><div class="col-xl-12 col-md-12 mb-12 col-lg-12 ">
</code>```

Does not have a height setup. Also all block label elements in html does not have a height defined out of the box, rather it's depends on it's child.

So what you need to do is set a height on the parent, ex:

In HTML: add a class

```<code><div class="col-xl-12 col-md-12 mb-12 col-lg-12 map-height">
</code>```

CSS: define the class as below

```<code>.map-height{
   min-height:calc( 100vh - 300px )
}
</code>```

the 300 px is hard codded here but you need to calculate your header height + the section with 4 big labels height + footer height
Assuming those 3 section has a static height setup.

ContentLicense: CC BY-SA 4.0

Title: Div is not fitting the space available

Body:
I know that this question has already been asked, but I tried everything and I haven't find a solution, so I'm asking again, my apologizes :-).

I'm trying to make my row fill all the remaining screen space of the page, however, my row never shrink, it stays at his initial size.

Notice that my map fits the size of the div.

Here is the code that i'm using :

          Carte des balises

And there is the render of the page :

If someone could give me some clues, I would really appreciate it !

Thanks in advance, :)

Body:
<div class="card shadow mb-4 h-100">

the h-100 class here says take 100% height of it's parent and the parent element

<div class="col-xl-12 col-md-12 mb-12 col-lg-12 ">

Does not have a height setup. Also all block label elements in html does not have a height defined out of the box, rather it's depends on it's child.

So what you need to do is set a height on the parent, ex:

In HTML: add a class

<div class="col-xl-12 col-md-12 mb-12 col-lg-12 map-height">

CSS: define the class as below

.map-height{
   min-height:calc( 100vh - 300px )
}

the 300 px is hard codded here but you need to calculate your header height + the section with 4 big labels height + footer height
Assuming those 3 section has a static height setup.


问:
Converting a resultset variable to an array
I am using SSIS (VS 2008) and I want to take a populated resultset variable (populated from an EXECUTE SQL task) and convert within an SSIS Script Component (c#) it into an array.

The resultset contains a single column.

What would be the code to do this?

Edit: This is for a backfilling exercise; in normal circumstances, a web app calls a proc on the db that passes in a text string and gets a list of matching words based on this kind of query:

```<code>SELECT  [Term]
    FROM    [dbo].[ATableOFTerms] WITH ( NOLOCK )
    WHERE   CHARINDEX(' ' + Term + ' ', @StringBeingSearched) > 0
</code>```

Once the web app gets this list, it has a lot of business rules around what it converts it to but essentially it takes the list of matching terms and generates a single string that is then used for passing into a fulltext search.

The backfilling process in SSIS needs to mimic that so the script component has the same web app code that deals with the business logic but I needed c# code that does the above. Which is fine, I am returning all the [ATableTerms] into a resultset variable but now I need populate an array from the variable.

When I have this I can use string.Contains to achieve the same result.

答:
IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0This is how it was solved, although I'd love to get an alternative to this.</p>

```<code>OleDbDataAdapter adapter = new OleDbDataAdapter();

string Title = " " + Row.Title + " ";
DataTable dt = new DataTable();
adapter.Fill(dt , Variables.ATableOfTerms);

ArrayList terms = new ArrayList();
ArrayList returnedTerms = new ArrayList();

foreach (DataRow dr in dt.Rows)
{
    terms.Add(" " + dr["Term"] + " ");

}

foreach (string term in terms)
{
    if (Title.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
    {
        returnedTerms.Add(term.Trim());

    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using SSIS (VS 2008) and I want to take a populated resultset variable (populated from an EXECUTE SQL task) and convert within an SSIS Script Component (c#) it into an array.

The resultset contains a single column.

What would be the code to do this?

Edit: This is for a backfilling exercise; in normal circumstances, a web app calls a proc on the db that passes in a text string and gets a list of matching words based on this kind of query:

SELECT  [Term]
    FROM    [dbo].[ATableOFTerms] WITH ( NOLOCK )
    WHERE   CHARINDEX(' ' + Term + ' ', @StringBeingSearched) > 0

Once the web app gets this list, it has a lot of business rules around what it converts it to but essentially it takes the list of matching terms and generates a single string that is then used for passing into a fulltext search.

The backfilling process in SSIS needs to mimic that so the script component has the same web app code that deals with the business logic but I needed c# code that does the above. Which is fine, I am returning all the [ATableTerms] into a resultset variable but now I need populate an array from the variable.

When I have this I can use string.Contains to achieve the same result.

Body:
IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0This is how it was solved, although I'd love to get an alternative to this.

OleDbDataAdapter adapter = new OleDbDataAdapter();

string Title = " " + Row.Title + " ";
DataTable dt = new DataTable();
adapter.Fill(dt , Variables.ATableOfTerms);

ArrayList terms = new ArrayList();
ArrayList returnedTerms = new ArrayList();

foreach (DataRow dr in dt.Rows)
{
    terms.Add(" " + dr["Term"] + " ");

}

foreach (string term in terms)
{
    if (Title.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
    {
        returnedTerms.Add(term.Trim());

    }
}


问:
How to replace only the leading zeros with NA?
How can I replace leading zeros with NAs? suppose I have the following example:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})
</code>```

the goal is to have the following result:

```<code> c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0
</code>```

but doing the following will not work since it will replace all and not just the leading zeros:

```<code>df[np.abs(df) < 1e-50] = np.nan
</code>```

答:
You can also check with ffill

```<code>df[df.mask(df==0).ffill().isna()] = np.nan
df
Out[141]:
    c1   c2
0  NaN  1.0
1  NaN  1.0
2  1.0  1.0
3  0.0  0.0
</code>```

Body:
How can I replace leading zeros with NAs? suppose I have the following example:

import pandas as pd
import numpy as np

df = pd.DataFrame(data={'c1': [0.0, 0.0, 1.0, 0.0], 'c2': [1.0, 1.0, 1.0, 0.0]})

the goal is to have the following result:

 c1    c2
 NA   1.0
 NA   1.0
1.0   1.0
0.0   0.0

but doing the following will not work since it will replace all and not just the leading zeros:

df[np.abs(df) < 1e-50] = np.nan

Body:
You can also check with ffill

df[df.mask(df==0).ffill().isna()] = np.nan
df
Out[141]:
    c1   c2
0  NaN  1.0
1  NaN  1.0
2  1.0  1.0
3  0.0  0.0


问:
export data as csv in react
I'm trying to export data as a csv in a react app without a library. My code looks like so:

```<code> const download = () => {
    const dummyData = 'rahul,delhi,accountsdept\n';
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
}

</code>```

And then I have a button with this download function as an onclick.

```<code>      <button onClick={download}>
        Generate Vehicle Offer Prices
      </button>
</code>```

This is supposed to work in vanilla javascript, is there a reason it doesn't work in react?

Here's a sandbox with the code not working in react sandbox

Here's a link with it working in vanilla js vanilla

答:
It is working actually, look here:</p>
```<code>import "./styles.css";

export default function App() {
  const download = () => {
    const dummyData = "rahul,delhi,accountsdept\n";
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={download}>Generate Vehicle Offer Prices</button>
    </div>
  );
}
</code>```

Title: export data as csv in react

Body:
I'm trying to export data as a csv in a react app without a library. My code looks like so:

 const download = () => {
    const dummyData = 'rahul,delhi,accountsdept\n';
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
}

And then I have a button with this download function as an onclick.

      <button onClick={download}>
        Generate Vehicle Offer Prices
      </button>

This is supposed to work in vanilla javascript, is there a reason it doesn't work in react?

Here's a sandbox with the code not working in react sandbox

Here's a link with it working in vanilla js vanilla

Body:
It is working actually, look here:

import "./styles.css";

export default function App() {
  const download = () => {
    const dummyData = "rahul,delhi,accountsdept\n";
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={download}>Generate Vehicle Offer Prices</button>
    </div>
  );
}


问:
Need JS array negative filter based on another array
I need help on filtering a Javascript array to remove names that DO NOT include at least one of a series of letters listed in a second array. I have tried over and over, using combinations of filter(), and also nested FOR loops. EXAMPLE:

name = ["chuck","lina","wanda","denise","reggie","candy"];

letter = ["h","l","z","e"];

The array returned by filter() should be:

nametwo = ["wanda","candy"];

It's simple to explain but I just cannot make it work in code. I've found many examples of filter() on here but none has helped. Thanks!

答:
We can use :

Array.every() method to test whether all elements in the array pass the test implemented by the provided function or not. It returns a Boolean value.

Then we can use Array.filter() method which creates a new array with all elements that pass the test implemented by the provided function.

Working Demo :

const name = ["chuck","lina","wanda","denise","reggie","candy"];
const letter = ["h","l","z","e"];

const resultArr = name.filter((word) => letter.every((char) => !word.includes(char)));

console.log(resultArr);```


问:
Is there any way to list out all permissions and on which resources an IAM user have access?
I am asked to list all users accesses in my company's aws account. Is there any way that I can list out the resources and respective permissions a user has? I feel it is difficult to get the details by looking into both IAM polices as well as Resource based policies. And it is much difficult if the user has cross account access.</p>

答:
Kindly run below one liner bash script regarding to list all users with their policies, groups,attached polices.</p>
```<code>aws iam list-users |grep -i username > list_users ; cat list_users |awk '{print $NF}' |tr '\"' ' ' |tr '\,' ' '|while read user; do echo "\n\n--------------Getting information for user $user-----------\n\n" ; aws iam list-user-policies --user-name $user --output yaml; aws iam list-groups-for-user  --user-name $user --output yaml;aws iam  list-attached-user-policies --user-name $user --output yaml ;done ;echo;echo
</code>```

Body:
Kindly run below one liner bash script regarding to list all users with their policies, groups,attached polices.

aws iam list-users |grep -i username > list_users ; cat list_users |awk '{print $NF}' |tr '\"' ' ' |tr '\,' ' '|while read user; do echo "\n\n--------------Getting information for user $user-----------\n\n" ; aws iam list-user-policies --user-name $user --output yaml; aws iam list-groups-for-user  --user-name $user --output yaml;aws iam  list-attached-user-policies --user-name $user --output yaml ;done ;echo;echo


问:
How to strip html tags out of selection
I want to strip html tags out of a selected text which is inside a content editable div. Lets say selected text is something like this:

  some text

```
<p>So I tried this:</p>
```window.getSelection().anchorNode.parentNode.replace(/<\/?[^>]+>/gi, '');
```
<p>but I get an error that says replace is not a function. I tried also this below:</p>
```window.getSelection().anchorNode.parentNode.remove();
```

but this will remove also the text. Whats the deal here?

Thank you.

答:
Like this

const editable = document.querySelector('div');
const button = document.querySelector('button');

button.addEventListener('click', () => {
  alert(editable.innerText);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div contenteditable="true">
    <span style="color:red">some text</span>
   </div>

   <button>Show me the text</button></code>```

Title: How to strip html tags out of selection

Body:
I want to strip html tags out of a selected text which is inside a content editable div. Lets say selected text is something like this:

  some text

So I tried this:

window.getSelection().anchorNode.parentNode.replace(/<\/?[^>]+>/gi, '');

but I get an error that says replace is not a function. I tried also this below:

window.getSelection().anchorNode.parentNode.remove();

but this will remove also the text. Whats the deal here?

Thank you.

Body:
Like this

const editable = document.querySelector('div');
const button = document.querySelector('button');

button.addEventListener('click', () => {
  alert(editable.innerText);
});

   <div contenteditable="true">
    <span style="color:red">some text</span>
   </div>

   <button>Show me the text</button>


问:
How to compare two vectors using SIMD and get a strncmp like result?
I want to achieve something like strncmp result but not that complicated
I tried to read https://code.woboq.org/userspace/glibc/sysdeps/x86_64/multiarch/strcmp-avx2.S.html source code but I failed to understand it

suppose we have to 256 bit vector
how can I compare these two based on 8 bit comparison to achieve result like strncmp

I know there is a library but I want to understand the basics.

how it return -1,0,1 result with _mm256_cmpeq_epi8 and _mm256_min_epu8

答:
I would do it like that.

```<code>inline int compareBytes( __m256i a, __m256i b )
{
    // Compare for both a <= b and a >= b
    __m256i min = _mm256_min_epu8( a, b );
    __m256i le = _mm256_cmpeq_epi8( a, min );
    __m256i ge = _mm256_cmpeq_epi8( b, min );

    // Reverse bytes within 16-byte lanes
    const __m128i rev16 = _mm_set_epi8( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 );
    const __m256i rev32 = _mm256_broadcastsi128_si256( rev16 );
    le = _mm256_shuffle_epi8( le, rev32 );
    ge = _mm256_shuffle_epi8( ge, rev32 );

    // Move the masks to scalar registers
    uint32_t lessMask = (uint32_t)_mm256_movemask_epi8( le );
    uint32_t greaterMask = (uint32_t)_mm256_movemask_epi8( ge );

    // Flip high/low 16-bit pieces in the masks.
    // Apparently, modern compilers are smart enough to emit ROR instructions for that code
    lessMask = ( lessMask >> 16 ) | ( lessMask << 16 );
    greaterMask = ( greaterMask >> 16 ) | ( greaterMask << 16 );

    // Produce the desired result
    if( lessMask > greaterMask )
        return -1;
    else if( lessMask < greaterMask )
        return +1;
    else
        return 0;
}
</code>```

The reason that method works, integer comparison is essentially searching for the most significant bit which differs, and comparison result is equal to the difference in that most significant different bit. Because we reversed order of the bytes being tested, the first byte in the vectors corresponds to the most significant bit in the masks. For this reason, ( lessMask > greaterMask ) expression evaluates to true when for the first different byte in the source vectors ( a < b ) evaluated to true.

Body:
I would do it like that.

inline int compareBytes( __m256i a, __m256i b )
{
    // Compare for both a <= b and a >= b
    __m256i min = _mm256_min_epu8( a, b );
    __m256i le = _mm256_cmpeq_epi8( a, min );
    __m256i ge = _mm256_cmpeq_epi8( b, min );

    // Reverse bytes within 16-byte lanes
    const __m128i rev16 = _mm_set_epi8( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 );
    const __m256i rev32 = _mm256_broadcastsi128_si256( rev16 );
    le = _mm256_shuffle_epi8( le, rev32 );
    ge = _mm256_shuffle_epi8( ge, rev32 );

    // Move the masks to scalar registers
    uint32_t lessMask = (uint32_t)_mm256_movemask_epi8( le );
    uint32_t greaterMask = (uint32_t)_mm256_movemask_epi8( ge );

    // Flip high/low 16-bit pieces in the masks.
    // Apparently, modern compilers are smart enough to emit ROR instructions for that code
    lessMask = ( lessMask >> 16 ) | ( lessMask << 16 );
    greaterMask = ( greaterMask >> 16 ) | ( greaterMask << 16 );

    // Produce the desired result
    if( lessMask > greaterMask )
        return -1;
    else if( lessMask < greaterMask )
        return +1;
    else
        return 0;
}

The reason that method works, integer comparison is essentially searching for the most significant bit which differs, and comparison result is equal to the difference in that most significant different bit. Because we reversed order of the bytes being tested, the first byte in the vectors corresponds to the most significant bit in the masks. For this reason, ( lessMask > greaterMask ) expression evaluates to true when for the first different byte in the source vectors ( a < b ) evaluated to true.


问:
Using recursion, in java, to have a variety of outputs from a single int parameter
If anyone is familiar with PracticeIt, it's what I'm doing and I'm on recursion problem sets. I'm having trouble doing them. Here's one problem:

Write a method writeSquares that accepts an integer parameter n and prints the first n squares separated by commas, with the odd squares in descending order followed by the even squares in ascending order. The following table shows several calls to the method and their expected output:

```<code>   writeSquares(5); ----> Output: 25, 9, 1, 4, 16
   writeSquares(1); ----> Output: 1
</code>```

I've spent a few hours each day for the past 3 days figuring out recursions but I just can't figure it out.
Can anyone point me in the right direction?

My code looks like:

```<code>public static void writeSquares(int n)
{
    if(n<1)
        throw new IllegalArgumentException();
    else{
        if(n%2==0){
            System.out.print((n-1)*(n-1));
            writeSquares2(n-1, n-1, "down");
        }
        else{
            System.out.print(n*n);
            writeSquares2(n-1, n-1, "down");
        }
    }
}

public static void writeSquares2(int n, int m, String s)
{
    if(m==0){
        return;
    }

    String ss = s;

    if(n<=1){
        ss = "up";}

    if(n%2==1&&s=="down"){
        System.out.print(", " + n*n);
        writeSquares2(n-2,m-1,ss);
    }
    if(n%2==0&&s=="down"){
        writeSquares2(n-1,m-1,ss);
        System.out.print(", " + n*n);
    }
    if(n%2==1&&s=="up"){
        System.out.print(", " + n*n);
        writeSquares2(n+2,m-1,ss);
    }
    if(n%2==0&&s=="up"){
        writeSquares2(n+1,m-1,ss);
        System.out.print(", " + n*n);
    }
</code>```

EDIT: Woops I fixed the code below

And another question from another problem set is:

Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:

```<code>  writeSequence(9);     -----> 5 4 3 2 1 2 3 4 5
  writeSequence(10);    -----> 5 4 3 2 1 1 2 3 4 5
</code>```

My code:

```<code>public void writeSequence(int n)
{
    if(n<1)
        throw new IllegalArgumentException();
    else
        writeSequence2(n, n, "down"); //I actually dont need the second parameter
}

    public void writeSequence2(int n, int m, String s)
    {
        String ss = s;
        if(n/2-1==1)
            ss = "up";

        if(n==1)
            System.out.print(n);

        else if(ss.equals("down")){
            if(n%2==0){
                System.out.print(n/2+" ");
                writeSequence2(n-1, m-1, ss);
            }
            else if(n%2==1){
                writeSequence2(n-1, m-1, ss);
                System.out.print(" "+ (n/2+1));
            }

        }

        else if(ss.equals("up")){
            if(n%2==0){
                System.out.print(n/2+" ");
                writeSequence2(n-1, m-1, ss);
            }
            else if(n%2==1){
                writeSequence2(n-1, m-1, ss);
                System.out.print(" " + (n/2+1));
            }
        }
    }
</code>```

For the second one, my code is somewhat correct. Except when n is odd.
Also another question - is it possible to do these with just a single method?

Thanks for your time. The tutors in my school aren't very helpful and neither are my classmates.

答:
Here is my solution, it's pretty compact and should work.</p>
```<code>public static void writeSequence(int n) {
    if (n <= 1){
        System.out.print(1);
    } else if (n % 2 != 0){
        System.out.print(n*n + ", ");
        writeSequence(n-1);
    } else{
        writeSequence(n-1);
        System.out.print(", " + n*n );
    }
}
</code>```

Body:
If anyone is familiar with PracticeIt, it's what I'm doing and I'm on recursion problem sets. I'm having trouble doing them. Here's one problem:

Write a method writeSquares that accepts an integer parameter n and prints the first n squares separated by commas, with the odd squares in descending order followed by the even squares in ascending order. The following table shows several calls to the method and their expected output:

   writeSquares(5); ----> Output: 25, 9, 1, 4, 16
   writeSquares(1); ----> Output: 1

I've spent a few hours each day for the past 3 days figuring out recursions but I just can't figure it out.
Can anyone point me in the right direction?

My code looks like:

public static void writeSquares(int n)
{
    if(n<1)
        throw new IllegalArgumentException();
    else{
        if(n%2==0){
            System.out.print((n-1)*(n-1));
            writeSquares2(n-1, n-1, "down");
        }
        else{
            System.out.print(n*n);
            writeSquares2(n-1, n-1, "down");
        }
    }
}

public static void writeSquares2(int n, int m, String s)
{
    if(m==0){
        return;
    }

    String ss = s;

    if(n<=1){
        ss = "up";}

    if(n%2==1&&s=="down"){
        System.out.print(", " + n*n);
        writeSquares2(n-2,m-1,ss);
    }
    if(n%2==0&&s=="down"){
        writeSquares2(n-1,m-1,ss);
        System.out.print(", " + n*n);
    }
    if(n%2==1&&s=="up"){
        System.out.print(", " + n*n);
        writeSquares2(n+2,m-1,ss);
    }
    if(n%2==0&&s=="up"){
        writeSquares2(n+1,m-1,ss);
        System.out.print(", " + n*n);
    }

EDIT: Woops I fixed the code below

And another question from another problem set is:

Write a method writeSequence that accepts an integer n as a parameter and prints a symmetric sequence of n numbers with descending integers ending in 1 followed by ascending integers beginning with 1, as in the table below:

  writeSequence(9);     -----> 5 4 3 2 1 2 3 4 5
  writeSequence(10);    -----> 5 4 3 2 1 1 2 3 4 5

My code:

public void writeSequence(int n)
{
    if(n<1)
        throw new IllegalArgumentException();
    else
        writeSequence2(n, n, "down"); //I actually dont need the second parameter
}

    public void writeSequence2(int n, int m, String s)
    {
        String ss = s;
        if(n/2-1==1)
            ss = "up";

        if(n==1)
            System.out.print(n);

        else if(ss.equals("down")){
            if(n%2==0){
                System.out.print(n/2+" ");
                writeSequence2(n-1, m-1, ss);
            }
            else if(n%2==1){
                writeSequence2(n-1, m-1, ss);
                System.out.print(" "+ (n/2+1));
            }

        }

        else if(ss.equals("up")){
            if(n%2==0){
                System.out.print(n/2+" ");
                writeSequence2(n-1, m-1, ss);
            }
            else if(n%2==1){
                writeSequence2(n-1, m-1, ss);
                System.out.print(" " + (n/2+1));
            }
        }
    }

For the second one, my code is somewhat correct. Except when n is odd.
Also another question - is it possible to do these with just a single method?

Thanks for your time. The tutors in my school aren't very helpful and neither are my classmates.

Body:
Here is my solution, it's pretty compact and should work.

public static void writeSequence(int n) {
    if (n <= 1){
        System.out.print(1);
    } else if (n % 2 != 0){
        System.out.print(n*n + ", ");
        writeSequence(n-1);
    } else{
        writeSequence(n-1);
        System.out.print(", " + n*n );
    }
}


问:
PHP & Parsing a JSON response
I'm trying to play with a web service via REST.

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

```<code><?php

    if(isset($_GET['word']))
    {
        $result= get_response_json($_GET['word']);
    } else {$result = "";}

    function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_POST, true);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>

<html>
    <title>Test Rhyme</title>
<body>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
        <input type="input" name="word" />
        <input type="submit" value="Submit" />
    </form>
    <div id="results">
        <?php
            print_r(json_decode($result, true));
        ?>
    </div>
</body>

</html>
</code>```

答:
Here's an example:</p>

```<code>$json = '[
    {
        "ID": "1001",
        "Phone": "5555555555"
    }
]';

$jsonArray = json_decode($json);

foreach($jsonArray as $value){
    $id = $value->ID;
    $phone = $value->Phone;
}
</code>```

Title: PHP & Parsing a JSON response

Body:
I'm trying to play with a web service via REST.

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

<?php

    if(isset($_GET['word']))
    {
        $result= get_response_json($_GET['word']);
    } else {$result = "";}

    function get_response_json($word)
    {
        $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word);
        echo $postURL;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postURL);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_POST, true);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

?>

    <title>Test Rhyme</title>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get">
        <input type="input" name="word" />
        <input type="submit" value="Submit" />
    </form>

        <?php
            print_r(json_decode($result, true));
        ?>

Body:
Here's an example:

$json = '[
    {
        "ID": "1001",
        "Phone": "5555555555"
    }
]';

$jsonArray = json_decode($json);

foreach($jsonArray as $value){
    $id = $value->ID;
    $phone = $value->Phone;
}


问:
creating 16-bit input to cufftXtMakePlanMany and workSize for 1 GPU
I need to compute FFT on unsigned int 8bit data. Previously, I was using cufftPlanMany and my input was cufftReal and the output was cufftComplex, and I was using casting before and after FFT to convert from unsigned 8bit to cufftReal and then from cufftComplex to signed 8bit.

It came to my attention that cuFFT has a nice option to run FFT for half-precision data which I hope improves the running time. According to the documentation, it currently doesn't support all of cudaDataType (that would be wonderful if it can in the future), but at least I can run it with 16bit float (half-precision) with the following signature:

```<code>cufftResult
cufftXtMakePlanMany(cufftHandle plan, int rank, long long int *n, long long int *inembed,
    long long int istride, long long int idist, cudaDataType inputtype,
    long long int *onembed, long long int ostride, long long int odist,
    cudaDataType outputtype, long long int batch, size_t *workSize,
    cudaDataType executiontype);
</code>```

with data types for input, output and execution respectively as:  CUDA_R_16F, CUDA_C_16F and CUDA_C_16F. Tha twould be ideal that I can feed this cuFFT with my U8 data, is there any way for doing so? Otherwise, if the first casting from U8 to cufftReal is necessary how can I convert my data from cufftReal to CUDA_R_16F and then from CUDA_C_16F ? Is cuda smart enough to cast the input from float to half-precision data, because cufftExecR2C ultimaltey would be the same and there is no other function to be called for the half-precision?

The other question is about workSize which is designed for multiple GPU cases. Any idea how this size has to be calculated? (I have just 1 GPU). Am I responsible for managing that buffer?

答:
TL;DR:  I can see two possible approaches here, one using a half-precision transform and one using a single-precision transform (perhaps with CUFFT callbacks).  The reasons to choose one or the other may depend on a number of factors such as size of your transform, control of scope of input data, the GPU you are running on, and other factors.

I'm not going to try to address the processing of the output data that you indicate here:

then from cufftComplex to signed 8bit.

since I don't know how to do that without more information.  However the processing of the input data in each case should be illustrative for how you could process the output data.

Using half-precision transforms

A few things to note here are that you cannot (currently) use callbacks with half-precision transforms, and half-precision transforms can be more sensitive to input data characteristics (e.g. DC offset, transform size, etc.) than single or double-precision transforms.  Also, half-precision transforms for the most part require a pascal or newer GPU (ignoring Jetson family).

Because half-precision transforms don't support callbacks, we'll use "ordinary" host code to process the input data; you could also do this processing on the device prior to the transform, the provided code outlines both possibilities.  My "preprocessing" here  is mostly just designed to prevent the 16-bit transform from overflowing.  If you play around with this code you'll quickly see what an overflow looks like (inf and/or nan in the output).

```<code>$ cat t1961.cu
#include <cufft.h>
#include <stdio.h>
#include <stdlib.h>
#include <cufftXt.h>
#include <cuda_fp16.h>
#include <assert.h>
#include <iostream>

typedef half2 ctype;
typedef half rtype;
typedef unsigned char dtype;
long long sig_size = 1<<18;
const int amplitude = 127;
const float ramplitude = 1/(float)(4*amplitude);

__host__ __device__ half convert(int val){
  return __float2half_rn((val - amplitude)*ramplitude);
}
__global__ void dev_convert(rtype *out, dtype *in, int sz){
  int idx = threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < sz)
    out[idx] = convert(in[idx]);
}

int main(){
  //put 4x sine waves into a U8 array
  dtype *my_data = (dtype *)malloc(sig_size*sizeof(dtype));
  for (int i = 0; i < sig_size; i++) my_data[i] = amplitude*(sin((i*8*3.141592654f)/sig_size)+1.0);
  rtype *d_idata;
  ctype *d_odata;
  cudaMalloc(&d_idata, sizeof(rtype)*sig_size);
#ifdef USE_HOST
  rtype *h_idata = (rtype *)malloc(sig_size*sizeof(rtype));
  // convert to 16 bit float non-offset suitable for cufft
  for (int i = 0; i < sig_size; i++) h_idata[i] = convert(my_data[i]);
  cudaMemcpy(d_idata, h_idata, sig_size*sizeof(rtype), cudaMemcpyHostToDevice);
#else
  const int bs = 256;
  dtype *d_mydata;
  cudaMalloc(&d_mydata, sig_size*sizeof(dtype));
  cudaMemcpy(d_mydata, my_data, sig_size*sizeof(dtype), cudaMemcpyHostToDevice);
  dev_convert<<<(sig_size+bs-1)/bs, bs>>>(d_idata, d_mydata, sig_size);
#endif
  cudaMalloc(&d_odata, sizeof(ctype)*(sig_size/2+1));
  cufftHandle plan;
  cufftResult r;
  r = cufftCreate(&plan);
  assert(r == CUFFT_SUCCESS);
  size_t ws = 0;
  r = cufftXtMakePlanMany(plan, 1,  &sig_size, NULL, 1, 1, CUDA_R_16F, NULL, 1, 1, CUDA_C_16F, 1, &ws, CUDA_C_16F);
  assert(r == CUFFT_SUCCESS);
  r = cufftXtExec(plan, d_idata, d_odata, CUFFT_FORWARD); // warm-up
  assert(r == CUFFT_SUCCESS);
  cudaEvent_t start, stop;
  cudaEventCreate(&start); cudaEventCreate(&stop);
  cudaEventRecord(start);
  r = cufftXtExec(plan, d_idata, d_odata, CUFFT_FORWARD);
  assert(r == CUFFT_SUCCESS);
  cudaEventRecord(stop);
  cudaEventSynchronize(stop);
  float et;
  cudaEventElapsedTime(&et, start, stop);
  printf("forward FFT time for %ld samples: %fms\n", sig_size, et);
  ctype *h_odata = (ctype *)malloc((sig_size/2+1)*sizeof(ctype));
  cudaMemcpy(h_odata, d_odata, (sig_size/2+1)*sizeof(ctype), cudaMemcpyDeviceToHost);
  for (int i = 0; i < 8; i++)
    std::cout << __half2float(h_odata[i].x) << " + " << __half2float(h_odata[i].y) << "i" << std::endl;
  return 0;
}
$ nvcc -o t1961 t1961.cu -lcufft
$ ./t1961
forward FFT time for 262144 samples: 0.027520ms
-258 + 0i
0.00349998 + 0.00127506i
-0.000146866 + -0.000833511i
0.00140095 + -0.00501251i
-1.57031 + -32752i
-0.00198174 + 0.00856018i
0.00474548 + 0.00359917i
-0.00226784 + 0.00987244i
$
</code>```

Using a single precision transform with a load callback

This in my view has a few benefits.  It is not as subject to the overflow phenomenon as the half precision transforms are, and the (load) callback routine allows us to still operate on U8 input data.

```<code>$ cat t1962.cu
#include <cufft.h>
#include <stdio.h>
#include <stdlib.h>
#include <cufftXt.h>
#include <cuda_fp16.h>
#include <assert.h>
#include <iostream>

typedef cufftComplex ctype;
typedef cufftReal rtype;
typedef unsigned char dtype;
long long sig_size = 1<<18;
const int amplitude = 127;
const cufftReal ramplitude = 1/(float)(4*amplitude);

__device__ rtype convert(int val){
  return (val - amplitude)*ramplitude;
}

 __device__ rtype myOwnCallback(void *dataIn,
                                     size_t offset,
                                     void *callerInfo,
                                     void *sharedPtr) {
     rtype ret;
     ret = convert(((dtype *)dataIn)[offset]);
     return ret;
 }
 __device__ cufftCallbackLoadR myOwnCallbackPtr = myOwnCallback;

int main(){
  cufftCallbackLoadR hostCopyOfCallbackPtr;

  cudaMemcpyFromSymbol(&hostCopyOfCallbackPtr,
                     myOwnCallbackPtr,
                     sizeof(hostCopyOfCallbackPtr));
  //put 4x sine waves into a U8 array
  dtype *my_data = (dtype *)malloc(sig_size*sizeof(dtype));
  for (int i = 0; i < sig_size; i++) my_data[i] = amplitude*(sin((i*8*3.141592654f)/sig_size)+1.0);
  ctype *d_odata;
  dtype *d_mydata;
  cudaMalloc(&d_mydata, sig_size*sizeof(dtype));
  cudaMemcpy(d_mydata, my_data, sig_size*sizeof(dtype), cudaMemcpyHostToDevice);
  cudaMalloc(&d_odata, sizeof(ctype)*(sig_size/2+1));
  cufftHandle plan;
  cufftResult r;
  r = cufftCreate(&plan);
  assert(r == CUFFT_SUCCESS);
  size_t ws = 0;
  r = cufftXtMakePlanMany(plan, 1,  &sig_size, NULL, 1, 1, CUDA_R_32F, NULL, 1, 1, CUDA_C_32F, 1, &ws, CUDA_C_32F);
  assert(r == CUFFT_SUCCESS);
  void *rps[] = {(void *)hostCopyOfCallbackPtr};
  r = cufftXtSetCallback(plan, rps, CUFFT_CB_LD_REAL, NULL);
  assert(r == CUFFT_SUCCESS);
  r = cufftXtExec(plan, (cufftReal *)d_mydata, d_odata, CUFFT_FORWARD); // warm-up
  assert(r == CUFFT_SUCCESS);
  cudaEvent_t start, stop;
  cudaEventCreate(&start); cudaEventCreate(&stop);
  cudaEventRecord(start);
  r = cufftXtExec(plan, (cufftReal *)d_mydata, d_odata, CUFFT_FORWARD);
  assert(r == CUFFT_SUCCESS);
  cudaEventRecord(stop);
  cudaEventSynchronize(stop);
  float et;
  cudaEventElapsedTime(&et, start, stop);
  printf("forward FFT time for %ld samples: %fms\n", sig_size, et);
  ctype *h_odata = (ctype *)malloc((sig_size/2+1)*sizeof(ctype));
  cudaMemcpy(h_odata, d_odata, (sig_size/2+1)*sizeof(ctype), cudaMemcpyDeviceToHost);
  for (int i = 0; i < 8; i++)
    std::cout << h_odata[i].x << " + " << h_odata[i].y << "i" << std::endl;
  return 0;
}
$ nvcc -o t1962 t1962.cu -rdc=true -lcufft_static -lculibos
$ ./t1962
forward FFT time for 262144 samples: 0.031488ms
-257.969 + 0i
0.00344251 + 0.00137726i
-3.96543e-05 + -0.00106905i
0.0013994 + -0.00490045i
0.0331312 + -32759.4i
-0.00190887 + 0.00865401i
0.00454092 + 0.00368094i
-0.00219025 + 0.00983646i
$
</code>```

Yes, the results are not numerically identical between the two transform types.  It's not reasonable to expect that 16-bit floating point calculations and 32-bit floating point calculations will be identical.  In all probability the 32-bit calculations are "more accurate". For this sinewave case, the terms I consider most important are the DC term as well as the magnitude spike at the fundamental.  Those are numerically close to each other.  The other terms are "in the noise". The timing results are not exactly comparable either, as the 16-bit calculation case omits the cost of the kernel call to convert the data from U8 to F16.  You can use a profiler or just refactor the code to get more comparable timing.

workSize can be ignored for the single GPU case when using cufftXtMakePlanMany, otherwise, use the provided routines to determine workSize.

Body:
I need to compute FFT on unsigned int 8bit data. Previously, I was using cufftPlanMany and my input was cufftReal and the output was cufftComplex, and I was using casting before and after FFT to convert from unsigned 8bit to cufftReal and then from cufftComplex to signed 8bit.

It came to my attention that cuFFT has a nice option to run FFT for half-precision data which I hope improves the running time. According to the documentation, it currently doesn't support all of cudaDataType (that would be wonderful if it can in the future), but at least I can run it with 16bit float (half-precision) with the following signature:

cufftResult
cufftXtMakePlanMany(cufftHandle plan, int rank, long long int *n, long long int *inembed,
    long long int istride, long long int idist, cudaDataType inputtype,
    long long int *onembed, long long int ostride, long long int odist,
    cudaDataType outputtype, long long int batch, size_t *workSize,
    cudaDataType executiontype);

with data types for input, output and execution respectively as:  CUDA_R_16F, CUDA_C_16F and CUDA_C_16F. Tha twould be ideal that I can feed this cuFFT with my U8 data, is there any way for doing so? Otherwise, if the first casting from U8 to cufftReal is necessary how can I convert my data from cufftReal to CUDA_R_16F and then from CUDA_C_16F ? Is cuda smart enough to cast the input from float to half-precision data, because cufftExecR2C ultimaltey would be the same and there is no other function to be called for the half-precision?

The other question is about workSize which is designed for multiple GPU cases. Any idea how this size has to be calculated? (I have just 1 GPU). Am I responsible for managing that buffer?

Body:
TL;DR:  I can see two possible approaches here, one using a half-precision transform and one using a single-precision transform (perhaps with CUFFT callbacks).  The reasons to choose one or the other may depend on a number of factors such as size of your transform, control of scope of input data, the GPU you are running on, and other factors.

I'm not going to try to address the processing of the output data that you indicate here:

then from cufftComplex to signed 8bit.

since I don't know how to do that without more information.  However the processing of the input data in each case should be illustrative for how you could process the output data.

Using half-precision transforms

A few things to note here are that you cannot (currently) use callbacks with half-precision transforms, and half-precision transforms can be more sensitive to input data characteristics (e.g. DC offset, transform size, etc.) than single or double-precision transforms.  Also, half-precision transforms for the most part require a pascal or newer GPU (ignoring Jetson family).

Because half-precision transforms don't support callbacks, we'll use "ordinary" host code to process the input data; you could also do this processing on the device prior to the transform, the provided code outlines both possibilities.  My "preprocessing" here  is mostly just designed to prevent the 16-bit transform from overflowing.  If you play around with this code you'll quickly see what an overflow looks like (inf and/or nan in the output).

$ cat t1961.cu
#include <cufft.h>
#include <stdio.h>
#include <stdlib.h>
#include <cufftXt.h>
#include <cuda_fp16.h>
#include <assert.h>
#include <iostream>

typedef half2 ctype;
typedef half rtype;
typedef unsigned char dtype;
long long sig_size = 1<<18;
const int amplitude = 127;
const float ramplitude = 1/(float)(4*amplitude);

__host__ __device__ half convert(int val){
  return __float2half_rn((val - amplitude)*ramplitude);
}
__global__ void dev_convert(rtype *out, dtype *in, int sz){
  int idx = threadIdx.x+blockDim.x*blockIdx.x;
  if (idx < sz)
    out[idx] = convert(in[idx]);
}

int main(){
  //put 4x sine waves into a U8 array
  dtype *my_data = (dtype *)malloc(sig_size*sizeof(dtype));
  for (int i = 0; i < sig_size; i++) my_data[i] = amplitude*(sin((i*8*3.141592654f)/sig_size)+1.0);
  rtype *d_idata;
  ctype *d_odata;
  cudaMalloc(&d_idata, sizeof(rtype)*sig_size);
#ifdef USE_HOST
  rtype *h_idata = (rtype *)malloc(sig_size*sizeof(rtype));
  // convert to 16 bit float non-offset suitable for cufft
  for (int i = 0; i < sig_size; i++) h_idata[i] = convert(my_data[i]);
  cudaMemcpy(d_idata, h_idata, sig_size*sizeof(rtype), cudaMemcpyHostToDevice);
#else
  const int bs = 256;
  dtype *d_mydata;
  cudaMalloc(&d_mydata, sig_size*sizeof(dtype));
  cudaMemcpy(d_mydata, my_data, sig_size*sizeof(dtype), cudaMemcpyHostToDevice);
  dev_convert<<<(sig_size+bs-1)/bs, bs>>>(d_idata, d_mydata, sig_size);
#endif
  cudaMalloc(&d_odata, sizeof(ctype)*(sig_size/2+1));
  cufftHandle plan;
  cufftResult r;
  r = cufftCreate(&plan);
  assert(r == CUFFT_SUCCESS);
  size_t ws = 0;
  r = cufftXtMakePlanMany(plan, 1,  &sig_size, NULL, 1, 1, CUDA_R_16F, NULL, 1, 1, CUDA_C_16F, 1, &ws, CUDA_C_16F);
  assert(r == CUFFT_SUCCESS);
  r = cufftXtExec(plan, d_idata, d_odata, CUFFT_FORWARD); // warm-up
  assert(r == CUFFT_SUCCESS);
  cudaEvent_t start, stop;
  cudaEventCreate(&start); cudaEventCreate(&stop);
  cudaEventRecord(start);
  r = cufftXtExec(plan, d_idata, d_odata, CUFFT_FORWARD);
  assert(r == CUFFT_SUCCESS);
  cudaEventRecord(stop);
  cudaEventSynchronize(stop);
  float et;
  cudaEventElapsedTime(&et, start, stop);
  printf("forward FFT time for %ld samples: %fms\n", sig_size, et);
  ctype *h_odata = (ctype *)malloc((sig_size/2+1)*sizeof(ctype));
  cudaMemcpy(h_odata, d_odata, (sig_size/2+1)*sizeof(ctype), cudaMemcpyDeviceToHost);
  for (int i = 0; i < 8; i++)
    std::cout << __half2float(h_odata[i].x) << " + " << __half2float(h_odata[i].y) << "i" << std::endl;
  return 0;
}
$ nvcc -o t1961 t1961.cu -lcufft
$ ./t1961
forward FFT time for 262144 samples: 0.027520ms
-258 + 0i
0.00349998 + 0.00127506i
-0.000146866 + -0.000833511i
0.00140095 + -0.00501251i
-1.57031 + -32752i
-0.00198174 + 0.00856018i
0.00474548 + 0.00359917i
-0.00226784 + 0.00987244i
$

Using a single precision transform with a load callback

This in my view has a few benefits.  It is not as subject to the overflow phenomenon as the half precision transforms are, and the (load) callback routine allows us to still operate on U8 input data.

$ cat t1962.cu
#include <cufft.h>
#include <stdio.h>
#include <stdlib.h>
#include <cufftXt.h>
#include <cuda_fp16.h>
#include <assert.h>
#include <iostream>

typedef cufftComplex ctype;
typedef cufftReal rtype;
typedef unsigned char dtype;
long long sig_size = 1<<18;
const int amplitude = 127;
const cufftReal ramplitude = 1/(float)(4*amplitude);

__device__ rtype convert(int val){
  return (val - amplitude)*ramplitude;
}

 __device__ rtype myOwnCallback(void *dataIn,
                                     size_t offset,
                                     void *callerInfo,
                                     void *sharedPtr) {
     rtype ret;
     ret = convert(((dtype *)dataIn)[offset]);
     return ret;
 }
 __device__ cufftCallbackLoadR myOwnCallbackPtr = myOwnCallback;

int main(){
  cufftCallbackLoadR hostCopyOfCallbackPtr;

  cudaMemcpyFromSymbol(&hostCopyOfCallbackPtr,
                     myOwnCallbackPtr,
                     sizeof(hostCopyOfCallbackPtr));
  //put 4x sine waves into a U8 array
  dtype *my_data = (dtype *)malloc(sig_size*sizeof(dtype));
  for (int i = 0; i < sig_size; i++) my_data[i] = amplitude*(sin((i*8*3.141592654f)/sig_size)+1.0);
  ctype *d_odata;
  dtype *d_mydata;
  cudaMalloc(&d_mydata, sig_size*sizeof(dtype));
  cudaMemcpy(d_mydata, my_data, sig_size*sizeof(dtype), cudaMemcpyHostToDevice);
  cudaMalloc(&d_odata, sizeof(ctype)*(sig_size/2+1));
  cufftHandle plan;
  cufftResult r;
  r = cufftCreate(&plan);
  assert(r == CUFFT_SUCCESS);
  size_t ws = 0;
  r = cufftXtMakePlanMany(plan, 1,  &sig_size, NULL, 1, 1, CUDA_R_32F, NULL, 1, 1, CUDA_C_32F, 1, &ws, CUDA_C_32F);
  assert(r == CUFFT_SUCCESS);
  void *rps[] = {(void *)hostCopyOfCallbackPtr};
  r = cufftXtSetCallback(plan, rps, CUFFT_CB_LD_REAL, NULL);
  assert(r == CUFFT_SUCCESS);
  r = cufftXtExec(plan, (cufftReal *)d_mydata, d_odata, CUFFT_FORWARD); // warm-up
  assert(r == CUFFT_SUCCESS);
  cudaEvent_t start, stop;
  cudaEventCreate(&start); cudaEventCreate(&stop);
  cudaEventRecord(start);
  r = cufftXtExec(plan, (cufftReal *)d_mydata, d_odata, CUFFT_FORWARD);
  assert(r == CUFFT_SUCCESS);
  cudaEventRecord(stop);
  cudaEventSynchronize(stop);
  float et;
  cudaEventElapsedTime(&et, start, stop);
  printf("forward FFT time for %ld samples: %fms\n", sig_size, et);
  ctype *h_odata = (ctype *)malloc((sig_size/2+1)*sizeof(ctype));
  cudaMemcpy(h_odata, d_odata, (sig_size/2+1)*sizeof(ctype), cudaMemcpyDeviceToHost);
  for (int i = 0; i < 8; i++)
    std::cout << h_odata[i].x << " + " << h_odata[i].y << "i" << std::endl;
  return 0;
}
$ nvcc -o t1962 t1962.cu -rdc=true -lcufft_static -lculibos
$ ./t1962
forward FFT time for 262144 samples: 0.031488ms
-257.969 + 0i
0.00344251 + 0.00137726i
-3.96543e-05 + -0.00106905i
0.0013994 + -0.00490045i
0.0331312 + -32759.4i
-0.00190887 + 0.00865401i
0.00454092 + 0.00368094i
-0.00219025 + 0.00983646i
$

Yes, the results are not numerically identical between the two transform types.  It's not reasonable to expect that 16-bit floating point calculations and 32-bit floating point calculations will be identical.  In all probability the 32-bit calculations are "more accurate". For this sinewave case, the terms I consider most important are the DC term as well as the magnitude spike at the fundamental.  Those are numerically close to each other.  The other terms are "in the noise". The timing results are not exactly comparable either, as the 16-bit calculation case omits the cost of the kernel call to convert the data from U8 to F16.  You can use a profiler or just refactor the code to get more comparable timing.

workSize can be ignored for the single GPU case when using cufftXtMakePlanMany, otherwise, use the provided routines to determine workSize.


问:
How to pass API path variable in c#
I need to call a API (/salesandtarget/from/{startDate}/to/{endDate} ). Here is what I have coded -

```<code>HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

        httpWReq.Method = "GET";

        httpWReq.ContentType = "application/json";
        httpWReq.Headers.Add("user-key", userKey);

        HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
</code>```

How should I pass the startDate and endDate to request. Thank you!

答:
It seems like you would need to format the URL string (wURL) that is passed to the WebRequest.Create() method with your desired dates.  Something like:

```<code>string wUrl = string.Format("/salesandtarget/from/{0}/to/{1}", startDate, endDate);
</code>```

Where startDate and endDate are DateTimes.  Pay special attention to how you need your DateTimes formatted for your request.  It may require you to manually call the ToString() method with the required formatting.

You will need to create a new HttpWebRequest object for each unique URL.

Title: How to pass API path variable in c#

Body:
I need to call a API (/salesandtarget/from/{startDate}/to/{endDate} ). Here is what I have coded -

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);

        httpWReq.Method = "GET";

        httpWReq.ContentType = "application/json";
        httpWReq.Headers.Add("user-key", userKey);

        HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();

How should I pass the startDate and endDate to request. Thank you!

Body:
It seems like you would need to format the URL string (wURL) that is passed to the WebRequest.Create() method with your desired dates.  Something like:

string wUrl = string.Format("/salesandtarget/from/{0}/to/{1}", startDate, endDate);

Where startDate and endDate are DateTimes.  Pay special attention to how you need your DateTimes formatted for your request.  It may require you to manually call the ToString() method with the required formatting.

You will need to create a new HttpWebRequest object for each unique URL.


问:
Powershell get eventlog source
Another simple question for you, which is a tough one for me...
I am trying to check, if a source exist in eventlog. using this command to check:

```<code>$EventLogSource = "TestSource"
$EventLogsourceCheck = [System.Diagnostics.EventLog]::SourceExists($EventLogSource)
</code>```

If the source exists, then it gives "true". The problem becomes, if the source doesn't exist. In this case the variable $EventLogsourceCheck remains the same, as it already was. in commandline i see the error:

Ausnahme beim Aufrufen von "SourceExists" mit 1 Argument(en):  "Die
Quelle wurde nicht gefunden, aber einige oder alle Ereignisprotokolle
konnten nicht durchsucht werden. Protokolle, auf die kein Zugriff
möglich war: Security." In Zeile:1 Zeichen:1

$tdf = [System.Diagnostics.EventLog]::SourceExists('sfdsf')

```<code>  + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  + FullyQualifiedErrorId : SecurityException
</code>```

i want to suppress this message and if the source doens't exist, i want the variable $EventLogsourceCheck  to be false.
How can i do this?

答:
You can suppress the errors with a Try - Catch statement, if the SourceExists method fails and throws an error, your Catch block can return $false, for example:

```<code>$ErrorActionPreference = 'Stop'
$EventLogSource = 'Application', 'System', 'SomeOtherLog'
$EventLogSource | ForEach-Object {
    [pscustomobject]@{
        LogName = $_
        SourceExists = try {
            [System.Diagnostics.EventLog]::SourceExists($_)
        } catch { $false }
    }
}
</code>```

Title: Powershell get eventlog source

Body:
Another simple question for you, which is a tough one for me...
I am trying to check, if a source exist in eventlog. using this command to check:

$EventLogSource = "TestSource"
$EventLogsourceCheck = [System.Diagnostics.EventLog]::SourceExists($EventLogSource)

If the source exists, then it gives "true". The problem becomes, if the source doesn't exist. In this case the variable $EventLogsourceCheck remains the same, as it already was. in commandline i see the error:

Ausnahme beim Aufrufen von "SourceExists" mit 1 Argument(en):  "Die
Quelle wurde nicht gefunden, aber einige oder alle Ereignisprotokolle
konnten nicht durchsucht werden. Protokolle, auf die kein Zugriff
möglich war: Security." In Zeile:1 Zeichen:1

$tdf = [System.Diagnostics.EventLog]::SourceExists('sfdsf')

  + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
  + FullyQualifiedErrorId : SecurityException

i want to suppress this message and if the source doens't exist, i want the variable $EventLogsourceCheck  to be false.
How can i do this?

Body:
You can suppress the errors with a Try - Catch statement, if the SourceExists method fails and throws an error, your Catch block can return $false, for example:

$ErrorActionPreference = 'Stop'
$EventLogSource = 'Application', 'System', 'SomeOtherLog'
$EventLogSource | ForEach-Object {
    [pscustomobject]@{
        LogName = $_
        SourceExists = try {
            [System.Diagnostics.EventLog]::SourceExists($_)
        } catch { $false }
    }
}


问:
I am trying to filter products in assending and descending order based on product price in vue js using vuex. But not sure how to do
I have been following youtube tutorials for learning Vue js.
so I want to add functionality to this project for filtering the products based upon price.

here is my  code

store/index.js

```<code>import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})
</code>```

here is what my look like in file data/items.js

```<code>const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items
</code>```

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

```<code><template>
  <div class="home">
    <span class="big-text">NFT</span>
    <div class="nx-container">
      <h1 class="py-45">Get NFT</h1>
      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>
      <div class="flex-it pad-130">
        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>
      </div>
    </div>
  </div>
</template>

<script>
import ProductSummaryContainer from "../components/products/ProductSummaryContainer.vue";
import ProductDetails from "../components/products/ProductDetails.vue";

import items from "../data/items";

export default {
  name: "Home",
  components: { ProductSummaryContainer, ProductDetails },
  data() {
    return {
      items: items,
      product: null,
      active: {
        product_detail: false,
      },
    };
  },
  methods: {
    viewProduct(product) {
      this.product = product;
      this.active.product_detail = true;
      console.log(product);
    },
    closeDetails() {
      this.active.product_detail = false;
    },
    sortUp($store) { //what i tried
      console.log(this.$store.items.val.sort((a, b) => a - b));
      return $store.items.val.sort((a, b) => a - b);
    },
    sortDown() {},//what i tried
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
  text-align: initial;
}
.nx-container {
  max-width: 1200px;
  overflow-x: hidden;
  overflow-y: auto;
  margin: 0 auto;
}
.flex-it {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.pad-130 {
  padding: 0px 15px 130px;
}
.big-text {
  font-family: "Poppins";
  font-size: 16em;
  text-transform: uppercase;
  font-weight: 800;
  position: absolute;
  top: 0;
  right: 0;
  z-index: -6;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke-width: 0.3px;
}
#app {
  position: relative;
}
</style>
</code>```

what changes need to be done?
Thank you in advance.

答:
Thanks to @Adam M. I got the idea and I just need to return that sorted item in an array so here is the solution:</p>
```<code>sortUp() {
      return this.items.sort((a, b) => parseFloat(a.val) - parseFloat(b.val));
    },
    sortDown() {
      return this.items.sort((a, b) => parseFloat(b.val) - parseFloat(a.val));
    }
</code>```

Body:
I have been following youtube tutorials for learning Vue js.
so I want to add functionality to this project for filtering the products based upon price.

here is my  code

store/index.js

import { createStore } from 'vuex'

function updateLocalStorage(cart) {
    localStorage.setItem('cart', JSON.stringify(cart))
}

export default createStore({
    state: {
        cart: [],
    },
    getters: {
        productQuantity: state => product => {
            const item = state.cart.find(i => i.id === product.id)
            if (item) {
                return item.quantity;
            } else {
                return null;
            }
        },
        cartItems: state => {
            return state.cart
        },
        cartToatal: state => {
            return state.cart.reduce((a, b) => a + (b.val * b.quantity), 0)
        }
    },
    mutations: {
        addItemInCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)

            if (item) {
                item.quantity++;
            } else {
                state.cart.push({...product, quantity: 1 });
            }

            updateLocalStorage(state.cart);
        },
        removeItemFromCart(state, product) {
            let item = state.cart.find(i => i.id === product.id)
            if (item) {
                if (item.quantity > 1) {
                    item.quantity--
                } else {
                    state.cart = state.cart.filter(i => i.id != product.id)
                }
            }

            updateLocalStorage(state.cart);
        },
        updateCartFromLocalStorage(state) {
            const cart = localStorage.getItem('cart')
            if (cart) {
                state.cart = JSON.parse(cart)
            }
        }
    },
    actions: {},
    modules: {}
})

here is what my look like in file data/items.js

const items = [{
        id: 1,
        name: "One Tribe Black Edition",
        img: "https://enftymart.themenio.com/img/nft-lg.8f26d1a6.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 2,
        name: "One Tribe Black New",
        img: "https://miro.medium.com/max/2000/1*AJrLFnuCAD8dE1p1Bg0dbg.jpeg",
        val: "15.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 3,
        name: "One Tribe Black Edition",
        img: "https://creativereview.imgix.net/content/uploads/2021/09/F4E079D612B9653BEFC4D8D2F39781E39A3025C693B177A61D6C73A5156248EA.jpg?auto=compress,format&q=60&w=1200&h=849",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 4,
        name: "One Tribe Black Edition",
        img: "https://coffeebros.com/wp-content/uploads/2021/10/astronaut-background.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 5,
        name: "One Tribe Black Edition",
        img: "https://cloudfront-us-east-1.images.arcpublishing.com/coindesk/5NOWWNNEBRER7BXFZKCYRCA7NA.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 6,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 7,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/980/1*3iesg_sr8kC6NYN2iiFHRQ.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 8,
        name: "One Tribe Black Edition",
        img: "https://static01.nyt.com/images/2021/08/15/fashion/TEEN-NFTS--fewocious/TEEN-NFTS--fewocious-videoSixteenByNineJumbo1600.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 9,
        name: "One Tribe Black Edition",
        img: "https://www.digitalmusicnews.com/wp-content/uploads/2021/11/are-nfts-a-scam-feat.png",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 10,
        name: "One Tribe Black Edition",
        img: "https://miro.medium.com/max/1082/1*ZZdfsIVNuvbWB15csehQTg.jpeg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 11,
        name: "One Tribe Black Edition",
        img: "https://www.hollywoodreporter.com/wp-content/uploads/2021/10/Mutant-Demon-Ape-Credit-0xb1-copy-H-2021.jpg?w=681&h=383&crop=1",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
    {
        id: 12,
        name: "One Tribe Black Edition",
        img: "https://wp-assets.futurism.com/2021/11/person-furious-right-click-saved-precious-nft.jpg",
        val: "14.99",
        discription: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'",
        owner: "ZeniconStudio",
        quantity: 0,
    },
]

export default items

here is the Vue page where I am trying to filter products I have created to buttons and to methods for descending and ascending order.

<template>

    NFT

Get NFT

      <button class="sort-as" @click="sortUp()">sort up</button>
      <button class="sort-as" @click="sortDown()">sort down</button>

        <product-details
          :product="product"
          :active="active.product_detail"
          v-on:closeDetails="closeDetails()"
        ></product-details>
        <product-summary-container
          v-for="product in items"
          :key="product.id"
          :product="product"
          v-on:explore="viewProduct($event)"
        ></product-summary-container>

</template>

what changes need to be done?
Thank you in advance.

Body:
Thanks to @Adam M. I got the idea and I just need to return that sorted item in an array so here is the solution:

sortUp() {
      return this.items.sort((a, b) => parseFloat(a.val) - parseFloat(b.val));
    },
    sortDown() {
      return this.items.sort((a, b) => parseFloat(b.val) - parseFloat(a.val));
    }


问:
Handle back button actions inside android fragments
i needed to override the default back button behavior so that i could go to the previous fragment instead of closing the entire application.

Below is the implementation of this function

```<code>class DataFragment : Fragment() {

private lateinit var fragment: Fragment
private lateinit var fm: FragmentManager
private lateinit var transaction: FragmentTransaction

override fun onCreateView(
    inflater: LayoutInflater,
    @Nullable container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,object : OnBackPressedCallback(true){
        override fun handleOnBackPressed() {
            fragment = PreviousFragment()
            fm = parentFragmentManager
            transaction = fm.beginTransaction()
            transaction.replace(R.id.contentFragment, fragment)
            transaction.commit()
        }
    })
return binding.rootView
 }
}
</code>```

答:
```<code>public interface OnBackPressedListener {
    /**
     * register and implement OnBackPressedListener in fragment
     * @update status onBackPressed() from Activity to current fragment to handle super.onBackPressed(); or to continue next process
     */
   void onBackPressed();
}

</code>```

Body:
i needed to override the default back button behavior so that i could go to the previous fragment instead of closing the entire application.

Below is the implementation of this function

class DataFragment : Fragment() {

private lateinit var fragment: Fragment
private lateinit var fm: FragmentManager
private lateinit var transaction: FragmentTransaction

override fun onCreateView(
    inflater: LayoutInflater,
    @Nullable container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner,object : OnBackPressedCallback(true){
        override fun handleOnBackPressed() {
            fragment = PreviousFragment()
            fm = parentFragmentManager
            transaction = fm.beginTransaction()
            transaction.replace(R.id.contentFragment, fragment)
            transaction.commit()
        }
    })
return binding.rootView
 }
}


问:
Unable to set BottomSheetDialog initial height
I'm trying to set a height peek from which the dialog must start, then the user if dragged should be able to expand it, the issue is that in any case the bottomsheet initial state get half of screen.

The BottomSheet looks like this:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/varianti_preferite_bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:elevation="8dp"
    app:behavior_peekHeight="200dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

    <ImageButton
        android:id="@+id/closeButton"
        style="@style/Widget.AppCompat.ImageButton"
        android:minWidth="75dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/bottom_border_radius"
        android:contentDescription="@string/bottom_sheet_close_button"
        android:padding="10dp"
        android:layout_marginBottom="16dp"
        app:srcCompat="@drawable/ic_baseline_close" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/variantiRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="16dp"
        android:clipToPadding="false"
        android:scrollbars="vertical"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="4"
        tools:listitem="@layout/varianti_preferite">

    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>
</code>```

What i've tried:

I've tried to override onCreateDialog and set HalfExpanded ratio manually but nothing changed:

```<code>   @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

        dialog.setOnShowListener(dialog1 -> {
            BottomSheetDialog d = (BottomSheetDialog) dialog1;

            FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            BottomSheetBehavior<FrameLayout> bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
            bottomSheetBehavior.setHalfExpandedRatio(0.2f);
            bottomSheetBehavior.setFitToContents(false);

        });

        return dialog;
    }
</code>```

Kotlin answers are welcome too.

答:
I've solved the issue by setting peek height in BottomSheet style.

So in style.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
</style>

<style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/AppModalStyle</item>
</style>

<style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@drawable/bottom_sheet_rounded</item>
    <item name="behavior_peekHeight">@dimen/peek_height</item>
</style>
</code>```

Where in dimens.xml

```<code><dimen name="peek_height">200dp</dimen>
</code>```

But the issue is that it will set the peek_height to all BottomSheets of the application.

Body:
I'm trying to set a height peek from which the dialog must start, then the user if dragged should be able to expand it, the issue is that in any case the bottomsheet initial state get half of screen.

The BottomSheet looks like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/varianti_preferite_bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:elevation="8dp"
    app:behavior_peekHeight="200dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

    <ImageButton
        android:id="@+id/closeButton"
        style="@style/Widget.AppCompat.ImageButton"
        android:minWidth="75dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:background="@drawable/bottom_border_radius"
        android:contentDescription="@string/bottom_sheet_close_button"
        android:padding="10dp"
        android:layout_marginBottom="16dp"
        app:srcCompat="@drawable/ic_baseline_close" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/variantiRecycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="16dp"
        android:clipToPadding="false"
        android:scrollbars="vertical"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="4"
        tools:listitem="@layout/varianti_preferite">

    </androidx.recyclerview.widget.RecyclerView>

</LinearLayout>

What i've tried:

I've tried to override onCreateDialog and set HalfExpanded ratio manually but nothing changed:

   @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

        dialog.setOnShowListener(dialog1 -> {
            BottomSheetDialog d = (BottomSheetDialog) dialog1;

            FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            BottomSheetBehavior<FrameLayout> bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
            bottomSheetBehavior.setHalfExpandedRatio(0.2f);
            bottomSheetBehavior.setFitToContents(false);

        });

        return dialog;
    }

Kotlin answers are welcome too.

Body:
I've solved the issue by setting peek height in BottomSheet style.

So in style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
   <item name="bottomSheetDialogTheme">@style/AppBottomSheetDialogTheme</item>
</style>

<style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/AppModalStyle</item>
</style>

<style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@drawable/bottom_sheet_rounded</item>
    <item name="behavior_peekHeight">@dimen/peek_height</item>
</style>

Where in dimens.xml

<dimen name="peek_height">200dp</dimen>

But the issue is that it will set the peek_height to all BottomSheets of the application.


问:
Overwriting a .txt file in Python
The code below works if the new data is written in a new txt file(test_02.txt).

```<code>with open("test_01.txt", "r+") as list_01:
    for i in list_01:
        if i[0] == "%":
            continue
        else:
            file = []
            file.append(i)
            with open("test_02.txt", "a") as list_02:
                list_02.writelines(file)
</code>```

The file test_01.txt includes many lines and some of them start with %. I am trying to erase the lines start with % and overwrite the rest in the same txt file(test_01.txt).

How can I do that?

Any help/suggestion would be appreciated. Thanks!

答:
The code below resolved my problem.</p>
```<code>import re

with open("test_01.txt", "r+") as list_01:
    data = list_01.read()
    list_01.seek(0)
    list_01.write(re.sub(r'^%.*\n?', '', data, flags=re.MULTILINE))
    list_01.truncate()
</code>```

Title: Overwriting a .txt file in Python

Body:
The code below works if the new data is written in a new txt file(test_02.txt).

with open("test_01.txt", "r+") as list_01:
    for i in list_01:
        if i[0] == "%":
            continue
        else:
            file = []
            file.append(i)
            with open("test_02.txt", "a") as list_02:
                list_02.writelines(file)

The file test_01.txt includes many lines and some of them start with %. I am trying to erase the lines start with % and overwrite the rest in the same txt file(test_01.txt).

How can I do that?

Any help/suggestion would be appreciated. Thanks!

Body:
The code below resolved my problem.

import re

with open("test_01.txt", "r+") as list_01:
    data = list_01.read()
    list_01.seek(0)
    list_01.write(re.sub(r'^%.*\n?', '', data, flags=re.MULTILINE))
    list_01.truncate()


问:
Make a div scrollable inside flexbox
I have a sidebar that contains 2 panes. When I resize the window vertically, I want the top pane to dynamically resize, and the bottom pane to remain to a fixed size. When the total height of the sidebar is smaller than both panes, I want the top pane to shrink smaller than it's content, and become scrollable.

The expected behavior is the same as VS Code's sidebar.

Currently, when resizing, the top pane "pushes" the bottom pane down.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}</code>```

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content```

Use "Full page" in snippet to see resizing behavior.

答:
On your top panel add this:

.top-panel {
  overflow-y: auto;
}
```

Basically you need to tell that div how to behave when it reaches the smallest it can be while showing all of its contents.

flex-shrink: 1 helps with letting it know that the top-panel should shrink and that the bottom-panel shouldn't, but once it shrinks to the height of it's children, you need to let it know that it can shrink further than that. Adding the overflow-y: auto will do that.

That should sort it out :)

Title: Make a div scrollable inside flexbox

Body:
I have a sidebar that contains 2 panes. When I resize the window vertically, I want the top pane to dynamically resize, and the bottom pane to remain to a fixed size. When the total height of the sidebar is smaller than both panes, I want the top pane to shrink smaller than it's content, and become scrollable.

The expected behavior is the same as VS Code's sidebar.

Currently, when resizing, the top pane "pushes" the bottom pane down.

document.addEventListener("DOMContentLoaded", () => {
  const listItem = document.querySelector(".top-panel .list-item");
  for (let i = 0; i < 25; i++) {
    listItem.parentNode.appendChild(listItem.cloneNode(true));
  }
});

html,
body {
  margin: 0;
}

.main {
  margin-left: 12rem;
}

.sidebar {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 12rem;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-right: 1px solid #454545;
}

.top-panel {
  flex-shrink: 1;
  display: flex;
  flex-direction: column;
}

.bottom-panel {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #ababbc;
  font-weight: 700;
}

.panel-top .list {
  flex-shrink: 1;
  overflow-y: auto;
}

.panel-bottom .list {
  flex-shrink: 0;
}

.list-item {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Top panel

https://example.com/users/helloworld

Bottom panel

Lorem

Ipsum

Main content

Use "Full page" in snippet to see resizing behavior.

Body:
On your top panel add this:

.top-panel {
  overflow-y: auto;
}

Basically you need to tell that div how to behave when it reaches the smallest it can be while showing all of its contents.

flex-shrink: 1 helps with letting it know that the top-panel should shrink and that the bottom-panel shouldn't, but once it shrinks to the height of it's children, you need to let it know that it can shrink further than that. Adding the overflow-y: auto will do that.

That should sort it out :)


问:
Check if a word exists in another string in c# without using any inbuilt function
```<code>string sentence = "This is a goodday";
string word = "good";
</code>```

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

答:
try this:</p>
```<code>    static bool checkString(string inputString="",string word="")
    {
            bool returV=false;
            if(inputString =="" ||  word=="")
                return false;
            int intexcS=0;
            Dictionary<int,string> d = new Dictionary<int, string>();
            foreach (char cW in word)
            {
                foreach (char cS in inputString)
                {
                    if(cW==cS){
                        if(!d.ContainsKey(intexcS) && d.Count<word.Length){
                            d.Add(intexcS,cW.ToString());
                        }
                    }
                intexcS++;
                }
                intexcS=0;
            }
            int i=0;
            foreach(var iitem in d) { if(iitem.Value!=word[i].ToString()) returV=false; else returV=true; i++;  }
            return returV;
    }
</code>```

Body:
string sentence = "This is a goodday";
string word = "good";

I know this can be done with .Contains() method. I was asked in an interview how to do it without contains method.

Body:
try this:

    static bool checkString(string inputString="",string word="")
    {
            bool returV=false;
            if(inputString =="" ||  word=="")
                return false;
            int intexcS=0;
            Dictionary<int,string> d = new Dictionary<int, string>();
            foreach (char cW in word)
            {
                foreach (char cS in inputString)
                {
                    if(cW==cS){
                        if(!d.ContainsKey(intexcS) && d.Count<word.Length){
                            d.Add(intexcS,cW.ToString());
                        }
                    }
                intexcS++;
                }
                intexcS=0;
            }
            int i=0;
            foreach(var iitem in d) { if(iitem.Value!=word[i].ToString()) returV=false; else returV=true; i++;  }
            return returV;
    }