问:
How to get HttpRequestMessage with PushStreamContent in .net core backend
I am trying to implement audio streaming from my Xamarin.Forms app to my backend (.net core 2.2).
Then my backend will call the Azure cognitive API to transcribe the voice in the audio and return back a string with the transcribed text.

The transcription has to be done and shown in a text box component while the user is speaking (not when he finishes speaking).

To record the audio and put it in a stream I am using the Plugin.AudioRecorder from Nate Rickard (https://github.com/NateRickard/Plugin.AudioRecorder) and it works well.
Basicly, it fills a stream with the audio while the user is speaking and saves it to a file.

Nate Rickard also has another plugin using the Azure cognitive service SpeechToText (https://github.com/NateRickard/Xamarin.Cognitive.Speech).
This one uses the Plugin.AudioRecorder to capture the voice and then an HttpClient to request the transcription to Azure, getting the text as response.
This solution does all the work in the Xamarin.Forms app and I would like the following:

Send the request stream to my backend instead of directly send it to Azure.

From my backend send the request to Azure.

Obtain the Azure response and send it back to my Xamarin.Forms app.

The 2nd and 3rd steps are identical as implemented in the Xamarin.Cognitive.Speech plugin.
I am stuck in the first step when I have to handle the http request in my backend.
Sending a HttpRequestMessage with a PushStreamContent in it as implemented in Xamarin.Cognitive.Speech plugin,
I have changed the URL to send it to my backend instead of send it to azure.

When I run the app I get a 415 status code (Unsuported Media Type error).

Here is the sample code of how the PushStreamContent is built (code from Xamarin.Cognitive.Speech plugin):

```<code>        HttpContent PopulateRequestContent (Stream audioStream, int? channelCount = null, int? sampleRate = null, int? bitsPerSample = null, Task recordingTask = null, int streamReadDelay = 30)
        {
            const int audioDataWaitInterval = 100; //ms
            const int maxReadRetries = 10; //times

            return new PushStreamContent (async (outputStream, httpContext, transportContext) =>
            {
                try
                {
                    byte [] buffer = null;
                    int bytesRead = 0;
                    int readRetryCount = 0;

                    if (audioStream.CanRead)
                    {
                        var totalWait = 0;

                        //wait up to (audioDataWaitInterval * maxReadRetries) for some data to populate
                        while (audioStream.Length < ChunkSize && totalWait < audioDataWaitInterval * maxReadRetries)
                        {
                            Debug.WriteLine ("No audio data detected, waiting 100 MS");
                            await Task.Delay (audioDataWaitInterval);
                            totalWait += audioDataWaitInterval;
                        }

                        if (channelCount.HasValue && sampleRate.HasValue && bitsPerSample.HasValue)
                        {
                            //write a wav/riff header to the stream
                            outputStream.WriteWaveHeader (channelCount.Value, sampleRate.Value, bitsPerSample.Value);
                        }

                        //read 1024 (BufferSize) (max) raw bytes from the input audio stream
                        buffer = new byte [checked((uint) Math.Min (ChunkSize, (int) audioStream.Length))];

                        //probably a better way to do this... but if the caller has passed a Task in for us to determine the end of recording, we'll use that to see if it's ongoing
                        //  Otherwise, we'll always assume that the Stream is being populated and we'll fall back to using delays to attempt to wait for the end of stream
                        var tcs = new TaskCompletionSource<bool> ();
                        var waitTask = recordingTask ?? tcs.Task;

                        // loop while the stream is being populated... attempt to read <buffer.Length> bytes per loop, and see if we should keep checking, either via Task or read retries (when 0 bytes read)
                        while (audioStream.CanRead &&
                              ((bytesRead = await audioStream.ReadAsync (buffer, 0, buffer.Length)) != 0 || !waitTask.Wait (streamReadDelay)))
                        {
                            if (bytesRead > 0)
                            {
                                readRetryCount = -1;

                                //write the bytes to the output stream
                                await outputStream.WriteAsync (buffer, 0, bytesRead);
                            }

                            readRetryCount++;

                            //again, only using read retry timeouts if we don't have a Task
                            if (recordingTask == null && readRetryCount >= maxReadRetries)
                            {
                                tcs.SetResult (true);
                            }
                        }

                        await outputStream.FlushAsync ();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine (ex);
                    throw;
                }
                finally
                {
                    //must close/dispose output stream to notify that content is done
                    outputStream.Close ();
                }
            }, new MediaTypeHeaderValue (Constants.MimeTypes.WavAudio));
        }
</code>```

For test purposes I am using an overloaded method to build the PushContentStream:

HttpContent PopulateRequestContent (string audioFilePath){...} but, as in the plugin, the above one will be used.

Here is the request sent to my backend (code from Xamarin.Cognitive.Speech plugin MODIFIED to set my backend URL. I do not use the method parameters to build the request):

```<code>        async Task<string> SendRequest (Func<HttpRequestMessage> requestFactory, Func<HttpContent> contentFactory)
        {
            try
            {
                HttpRequestMessage httpRequest = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost:5000/api/test/v1/speechtotext");

                httpRequest.Headers.TransferEncodingChunked = true;
                httpRequest.Headers.Accept.ParseAdd(Constants.MimeTypes.Json);
                httpRequest.Headers.Accept.ParseAdd(Constants.MimeTypes.Xml);
                httpRequest.Version = HttpVersion.Version11;
                httpRequest.Content = PopulateRequestContent("/storage/emulated/0/Download/audioFile.wav");

                var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);

                if (response != null)
                {
                    // Do stuff
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine ("Error in sendRequest: {0}", ex);
                throw;
            }

            throw new Exception ("SendRequest: Unable to send successful request - unknown error or null response received");
        }
</code>```

Here is my desired backend endpoint in my Controller class:

```<code>        /// <summary>
        /// Receives stream content from request and calls service to send Azure SpeechToText request.
        /// </summary>
        /// <response code="200"> Ok. Returns transcribed text.</response>
        /// <response code="500">Internal Server Error. The search process ended with error.</response>
        [HttpPost]
        [ProducesResponseType(200)]
        [ProducesResponseType(500)]
        [Route("/api/test/v1/speechtotext")]
        public async Task<HttpResponseMessage> SpeechToText(HttpRequestMessage requestMessage)
        {
            // TODO: Get request, change URL to azure one and send it (have to see if so easy is possible).
            // OR
            // TODO: Get request, get PushStreamContent from it, build a new request, set the PushStreamContent as HttpContent and send it to azure

            // TODO: Receive azure response and send it back to Xamarin.Forms app.
        }
</code>```

To be more precise, I only would like to know how to receive the HttpRequestMessage and get the PushStreamContent from it.

Any help would be appreciated, thank you in advance!

答:
use the following code get the file in the request</p>

```<code>var httpRequest = HttpContext.Current.Request;
var postedFile =httpRequest.Files[0];
</code>```

Body:
I am trying to implement audio streaming from my Xamarin.Forms app to my backend (.net core 2.2).
Then my backend will call the Azure cognitive API to transcribe the voice in the audio and return back a string with the transcribed text.

The transcription has to be done and shown in a text box component while the user is speaking (not when he finishes speaking).

To record the audio and put it in a stream I am using the Plugin.AudioRecorder from Nate Rickard (https://github.com/NateRickard/Plugin.AudioRecorder) and it works well.
Basicly, it fills a stream with the audio while the user is speaking and saves it to a file.

Nate Rickard also has another plugin using the Azure cognitive service SpeechToText (https://github.com/NateRickard/Xamarin.Cognitive.Speech).
This one uses the Plugin.AudioRecorder to capture the voice and then an HttpClient to request the transcription to Azure, getting the text as response.
This solution does all the work in the Xamarin.Forms app and I would like the following:

Send the request stream to my backend instead of directly send it to Azure.

From my backend send the request to Azure.

Obtain the Azure response and send it back to my Xamarin.Forms app.

The 2nd and 3rd steps are identical as implemented in the Xamarin.Cognitive.Speech plugin.
I am stuck in the first step when I have to handle the http request in my backend.
Sending a HttpRequestMessage with a PushStreamContent in it as implemented in Xamarin.Cognitive.Speech plugin,
I have changed the URL to send it to my backend instead of send it to azure.

When I run the app I get a 415 status code (Unsuported Media Type error).

Here is the sample code of how the PushStreamContent is built (code from Xamarin.Cognitive.Speech plugin):

        HttpContent PopulateRequestContent (Stream audioStream, int? channelCount = null, int? sampleRate = null, int? bitsPerSample = null, Task recordingTask = null, int streamReadDelay = 30)
        {
            const int audioDataWaitInterval = 100; //ms
            const int maxReadRetries = 10; //times

            return new PushStreamContent (async (outputStream, httpContext, transportContext) =>
            {
                try
                {
                    byte [] buffer = null;
                    int bytesRead = 0;
                    int readRetryCount = 0;

                    if (audioStream.CanRead)
                    {
                        var totalWait = 0;

                        //wait up to (audioDataWaitInterval * maxReadRetries) for some data to populate
                        while (audioStream.Length < ChunkSize && totalWait < audioDataWaitInterval * maxReadRetries)
                        {
                            Debug.WriteLine ("No audio data detected, waiting 100 MS");
                            await Task.Delay (audioDataWaitInterval);
                            totalWait += audioDataWaitInterval;
                        }

                        if (channelCount.HasValue && sampleRate.HasValue && bitsPerSample.HasValue)
                        {
                            //write a wav/riff header to the stream
                            outputStream.WriteWaveHeader (channelCount.Value, sampleRate.Value, bitsPerSample.Value);
                        }

                        //read 1024 (BufferSize) (max) raw bytes from the input audio stream
                        buffer = new byte [checked((uint) Math.Min (ChunkSize, (int) audioStream.Length))];

                        //probably a better way to do this... but if the caller has passed a Task in for us to determine the end of recording, we'll use that to see if it's ongoing
                        //  Otherwise, we'll always assume that the Stream is being populated and we'll fall back to using delays to attempt to wait for the end of stream
                        var tcs = new TaskCompletionSource<bool> ();
                        var waitTask = recordingTask ?? tcs.Task;

                        // loop while the stream is being populated... attempt to read <buffer.Length> bytes per loop, and see if we should keep checking, either via Task or read retries (when 0 bytes read)
                        while (audioStream.CanRead &&
                              ((bytesRead = await audioStream.ReadAsync (buffer, 0, buffer.Length)) != 0 || !waitTask.Wait (streamReadDelay)))
                        {
                            if (bytesRead > 0)
                            {
                                readRetryCount = -1;

                                //write the bytes to the output stream
                                await outputStream.WriteAsync (buffer, 0, bytesRead);
                            }

                            readRetryCount++;

                            //again, only using read retry timeouts if we don't have a Task
                            if (recordingTask == null && readRetryCount >= maxReadRetries)
                            {
                                tcs.SetResult (true);
                            }
                        }

                        await outputStream.FlushAsync ();
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine (ex);
                    throw;
                }
                finally
                {
                    //must close/dispose output stream to notify that content is done
                    outputStream.Close ();
                }
            }, new MediaTypeHeaderValue (Constants.MimeTypes.WavAudio));
        }

For test purposes I am using an overloaded method to build the PushContentStream:

HttpContent PopulateRequestContent (string audioFilePath){...} but, as in the plugin, the above one will be used.

Here is the request sent to my backend (code from Xamarin.Cognitive.Speech plugin MODIFIED to set my backend URL. I do not use the method parameters to build the request):

        async Task<string> SendRequest (Func<HttpRequestMessage> requestFactory, Func<HttpContent> contentFactory)
        {
            try
            {
                HttpRequestMessage httpRequest = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost:5000/api/test/v1/speechtotext");

                httpRequest.Headers.TransferEncodingChunked = true;
                httpRequest.Headers.Accept.ParseAdd(Constants.MimeTypes.Json);
                httpRequest.Headers.Accept.ParseAdd(Constants.MimeTypes.Xml);
                httpRequest.Version = HttpVersion.Version11;
                httpRequest.Content = PopulateRequestContent("/storage/emulated/0/Download/audioFile.wav");

                var response = await client.SendAsync(httpRequest, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false);

                if (response != null)
                {
                    // Do stuff
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine ("Error in sendRequest: {0}", ex);
                throw;
            }

            throw new Exception ("SendRequest: Unable to send successful request - unknown error or null response received");
        }

Here is my desired backend endpoint in my Controller class:

        ///
        /// Receives stream content from request and calls service to send Azure SpeechToText request.
        ///
        /// <response code="200"> Ok. Returns transcribed text.</response>
        /// <response code="500">Internal Server Error. The search process ended with error.</response>
        [HttpPost]
        [ProducesResponseType(200)]
        [ProducesResponseType(500)]
        [Route("/api/test/v1/speechtotext")]
        public async Task<HttpResponseMessage> SpeechToText(HttpRequestMessage requestMessage)
        {
            // TODO: Get request, change URL to azure one and send it (have to see if so easy is possible).
            // OR
            // TODO: Get request, get PushStreamContent from it, build a new request, set the PushStreamContent as HttpContent and send it to azure

            // TODO: Receive azure response and send it back to Xamarin.Forms app.
        }

To be more precise, I only would like to know how to receive the HttpRequestMessage and get the PushStreamContent from it.

Any help would be appreciated, thank you in advance!

Body:
use the following code get the file in the request

var httpRequest = HttpContext.Current.Request;
var postedFile =httpRequest.Files[0];


来源: stackexchange

答:
They don't need to actually be applied with CSS as backgrounds in order behave like backgrounds for the user.

Create a parent container (e.g. div) to wrap the content you want to set the background for:

```<code><div>
  <YourSVGComponent />
  <div>Your content</div>
</div>
</code>```

Set the parent to position: relative (i.e. create a new positioning context), set the SVG styles to something like this:

position: absolute;
z-index: 1;
pointer-events: none;
top: 0;
right: 0;
bottom: 0;
left: 0;
```

Then I'd also recommend setting position: relative; z-index: 2 on the content div to make sure it shows up above the SVG in the stacking order.

This won't support CSS properties like background-repeat or background-position, but you can work around those on a case-by-case basis if you need to.

ContentLicense: CC BY-SA 4.0

Title: How can an SVG image transformed into a React component be used as a background image?

Body:
In my Gatsby website, I intend to use some animated backgrounds, so I got SVG images, transformed them into a React component and animated certain groups of the SVGs with Framer Motion.
The results are brilliant: I have animations that get displayed perfectly when added to a page as standalone components, but how can they be used as a background for a div or section?

Here's one of the component:

import React from 'react'
import { motion } from 'framer-motion'

const Animation1 = props => (
  <svg
    viewBox="0 0 2000 1000"
    fillRule="evenodd"
    clipRule="evenodd"
    strokeLinecap="round"
    strokeLinejoin="round"
    {...props}
  >
    <g id="pic">
      <motion.g
        animate={{ scaleY: [1, -1, 1] }}
        transition={{ duration: 5, loop: Infinity, repeatDelay: 4 }}
      >
        <path
          d="M581.31 974.891l-41.223-115.423s45.345 22.673 47.406 51.528c0 0-10.306-144.278-30.917-175.195 0 0 32.978 4.122 70.078 164.89 0 0 6.184-185.501-49.467-239.09 0 0 76.262 61.833 82.445 195.806v117.484H581.31zM1354.39 974.891l-9.91-27.752s10.9 5.451 11.39 12.389c0 0-2.47-34.69-7.43-42.124 0 0 7.93 16.85 39.65 0 0 1.487-44.61-11.894-57.49 0 0 18.337 14.87 19.823 47.08 0v28.248l-23.29 29.239z"
          fill="#f2f2f2"
        />
      </motion.g>
      <path
        d="M1244.68 975.543c-.29-.469-7.05-11.76-9.39-35.207-2.15-21.511-.77-57.77 18.03-108.348 35.63-95.817-8.21-173.127-8.65-173.897l2.16-1.254c.11 11.424 19.91 18.106 51.29 0a223.688 223.688 0 01-9.27 124.729c-35.56 95.653-9.12 140.935-8.85 141.381l-35.32 52.596z"
        fill="#3f3d56"
      />
      <path
        d="M989.557 554.987c0-100.078 81.133-181.208 181.213-181.208 100.07 0 181.2 81.13 181.2 181.208 0 100.079-81.13 181.209-181.2 181.209-100.08 0-181.213-81.13-181.213-181.209zM146 37.606h427.402v237.446H146V37.606zM725.867 37.606h427.403v237.446H725.867V37.606zM1305.73 37.606h427.41v237.446h-427.41V37.606z"
        fill="#e0dcdc"
      />
      <motion.g
        animate={{ scaleY: [1, -1, 1] }}
        transition={{ duration: 5, loop: Infinity, repeatDelay: 4 }}
      >
        <path
          d="M1214.51 636.219c0-8.973 7.27-16.247 16.24-16.247 8.97 0 16.25 7.274 16.25 16.247 0 8.972-7.28 16.246-16.25 16.246-8.97 0-16.24-7.274-16.24-16.246zM1230.75 736.196c0-8.973 7.28-16.246 16.25-16.246 8.97 0 16.24 7.273 16.24 16.246 0 8.972-7.27 16.246-16.24 16.246-8.97 0-16.25-7.274-16.25-16.246zM1273.24 769.938c0-8.972 7.28-16.246 16.25-16.246 8.97 0 16.24 7.274 16.24 16.246 0 8.973-7.27 16.246-16.24 16.246-8.97 0-16.25-7.273-16.25-16.246z"
          fill="#35b775"
        />
      </motion.g>
      <path
        d="M1218.25 822.426c0-8.973 7.28-16.246 16.25-16.246 8.97 0 16.25 7.273 16.25 16.246 0 8.973-7.28 16.246-16.25 16.246-8.97 0-16.25-7.273-16.25-16.246zM1254.5 976.141s-16.25-39.991 32.49-69.984l-32.49 69.984zM1234.52 975.415s-7.4-42.527-64.63-42.162l64.63 42.162zM146.625 23.86h426.152v21.244H146.625V23.86zM726.492 23.86h427.398v21.244H726.492V23.86zM1306.36 23.86h426.15v21.244h-426.15V23.86z"
        fill="#3f3d56"
      />
      <path
        d="M178.493 78.222h77.482v54.987h-77.482V78.222zM327.208 78.222h213.701v6.248H327.208v-6.248zM327.208 103.216h213.701v6.249H327.208v-6.249zM327.208 128.21h213.701v6.249H327.208v-6.249zM758.36 78.222h77.482v54.987H758.36V78.222zM907.075 78.222h213.705v6.248H907.075v-6.248zM907.075 103.216h213.705v6.249H907.075v-6.249zM907.075 128.21h213.705v6.249H907.075v-6.249zM1338.23 78.222h77.48v54.987h-77.48V78.222zM1486.94 78.222h213.7v6.248h-213.7v-6.248zM1486.94 103.216h213.7v6.249h-213.7v-6.249zM1486.94 128.21h213.7v6.249h-213.7v-6.249z"
        fill="#fff"
      />
      <path
        d="M192.239 106.34c0-13.804 11.191-24.994 24.995-24.994s24.994 11.19 24.994 24.994-11.19 24.995-24.994 24.995-24.995-11.191-24.995-24.995zM1351.97 106.34c0-13.804 11.19-24.994 25-24.994 13.8 0 24.99 11.19 24.99 24.994s-11.19 24.995-24.99 24.995c-13.81 0-25-11.191-25-24.995z"
        fill="#35b775"
      />
      <motion.g
        animate={{ scaleY: [1, -1, 1] }}
        transition={{ duration: 5, loop: Infinity, repeatDelay: 4 }}
      >
        <path
          d="M343.169 275.052h2.5v7.498h-2.5v-7.498zM345.669 582.481h-2.5v-14.996h2.5v14.996zm0-29.993h-2.5v-14.997h2.5v14.997zm0-29.993h-2.5v-14.997h2.5v14.997zm0-29.993h-2.5v-14.997h2.5v14.997zm0-29.993h-2.5v-14.997h2.5v14.997zm0-29.994h-2.5v-14.996h2.5v14.996zm0-29.993h-2.5v-14.996h2.5v14.996zm0-29.993h-2.5v-14.996h2.5v14.996zm0-29.993h-2.5V327.54h2.5v14.996zm0-29.993h-2.5v-14.997h2.5v14.997zM351.917 606.226h-8.748v-8.748h2.499v6.248h6.249v2.5zM1496.87 606.226h-15.06v-2.5h15.06v2.5zm-30.13 0h-15.06v-2.5h15.06v2.5zm-30.13 0h-15.06v-2.5h15.06v2.5zm-30.13 0h-15.06v-2.5h15.06v2.5zm-30.13 0h-15.06v-2.5h15.06v2.5zm-30.13 0h-15.06v-2.5h15.06v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.13 0h-15.07v-2.5h15.07v2.5zm-30.135 0H969.59v-2.5h15.065v2.5zm-30.13 0H939.46v-2.5h15.065v2.5zm-30.13 0H909.33v-2.5h15.065v2.5zm-30.13 0h-15.066v-2.5h15.066v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.066v-2.5h15.066v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.066v-2.5h15.066v2.5zm-30.13 0h-15.066v-2.5h15.066v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.066v-2.5h15.066v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.066v-2.5h15.066v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.065v-2.5H532.7v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.065v-2.5h15.065v2.5zm-30.131 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.065v-2.5h15.065v2.5zm-30.13 0h-15.065v-2.5h15.065v2.5zM1520.69 606.226h-8.75v-2.5h6.24v-6.248h2.51v8.748zM1520.68 582.481h-2.49v-14.996h2.49v14.996zm0-29.993h-2.49v-14.997h2.49v14.997zm0-29.993h-2.49v-14.997h2.49v14.997zm0-29.993h-2.49v-14.997h2.49v14.997zm0-29.993h-2.49v-14.997h2.49v14.997zm0-29.994h-2.49v-14.996h2.49v14.996zm0-29.993h-2.49v-14.996h2.49v14.996zm0-29.993h-2.49v-14.996h2.49v14.996zm0-29.993h-2.49V327.54h2.49v14.996zm0-29.993h-2.49v-14.997h2.49v14.997zM1518.19 275.052h2.49v7.498h-2.49v-7.498z"
          fill="#3f3d56"
        />
      </motion.g>
      <path
        d="M725.867 529.993h427.403v444.898H725.867V529.993z"
        fill="#3f3d56"
      />
      <path
        d="M758.36 588.105h77.482v54.987H758.36v-54.987zM907.075 588.105h213.705v6.248H907.075v-6.248zM907.075 613.099h213.705v6.249H907.075v-6.249zM907.075 638.093h213.705v6.249H907.075v-6.249zM758.36 786.184h77.482v54.988H758.36v-54.988zM907.075 786.184h213.705v6.249H907.075v-6.249zM907.075 811.179h213.705v6.248H907.075v-6.248zM907.075 836.173h213.705v6.248H907.075v-6.248z"
        fill="#fff"
      />
      <path
        d="M797.429 629.506l-26.522-35.362 6.283-4.712 21.605 28.808 55.072-44.603 4.973 6.078-61.411 49.791zM797.429 825.711l-26.522-35.362 6.283-4.711 21.605 28.806 55.072-44.603 4.973 6.08-61.411 49.79z"
        fill="#35b775"
      />
      <motion.g
        animate={{ scaleY: [1, -1, 1] }}
        transition={{ duration: 5, loop: Infinity, repeatDelay: 4 }}
      >
        <path
          d="M157.247 973.641H1700.64v2.5H157.247v-2.5zM993.365 288.798s41.245-17.97 60.615 0c19.37 17.971-51.87 13.747-60.615 0z"
          fill="#3f3d56"
        />
      </motion.g>
      <path
        d="M1064.58 203.574c-13.86-23.418-41.28-24.509-41.28-24.509s-26.72-3.417-43.859 32.248c-15.976 33.243-38.024 65.34-3.55 73.122l6.227-19.381 3.856 20.824c4.914.269 9.838.269 14.746 0 36.92-1.192 72.08 70.947-12.895 0 82.345-30.259 90.085-59.772 76.755-82.304zM977.744 460.634l-7.498 16.246s-109.975 36.242-99.977 78.732c9.997 42.491 58.736 108.725 66.234 106.226 7.499-2.5 47.49-9.998 48.739-31.243 1.25-21.245-28.743-58.736-28.743-58.736l41.24-37.492 60.011-1.25 51.21 38.742s-53.73 47.489-29.99 66.234c23.75 18.746 58.74 31.243 63.74 23.745 5-7.498 61.23-118.723 52.48-128.721-8.74-9.997-97.47-47.489-97.47-47.489l-23.75-33.742-92.477-4.999-3.749 13.747z"
        fill="#2f2e41"
      />
      <path
        d="M1000.24 254.431s6.25 41.241-6.25 46.24c-12.497 4.999 24.99 26.244 24.99 26.244h21.25l13.75-28.744s-12.5-22.495-5-43.74-48.74 0-48.74 0z"
        fill="#ffb8b8"
      />
      <path
        d="M1000.24 254.431s6.25 41.241-6.25 46.24c-12.497 4.999 24.99 26.244 24.99 26.244h21.25l13.75-28.744s-12.5-22.495-5-43.74-48.74 0-48.74 0z"
        opacity={0.1}
      />
      <path
        d="M991.491 289.423s13.749 14.997 16.249 17.496c2.5 2.5 13.74 16.247 37.49-3.749 23.74-19.995 26.24 3.749 26.24 3.749v149.966s-19.99-8.748-36.24 0c-16.25 8.748-49.988-2.499-49.988-2.499l-6.248-154.965 12.497-9.998z"
        fill="#fff"
      />
      <motion.g
        animate={{ scaleY: [1, -1, 1] }}
        transition={{ duration: 5, loop: Infinity, repeatDelay: 4 }}
      >
        <path
          d="M1000.67 289.423s-11.678-4.999-21.676 0c-9.998 4.999-44.99 29.993-42.49 41.241 2.499 11.247 34.992 89.979 12.497 127.471-22.495 37.491-26.244 47.489-26.244 47.489l54.987-28.744s42.486-26.244 38.746-42.49c-3.75-16.246-15.82-144.967-15.82-144.967zM1050.24 289.423s26.23 2.5 27.48 4.999c1.25 2.5 39.37 13.122 36.87 24.37-2.5 11.247-36.87 111.849-21.87 130.595 14.99 18.745 39.99 44.989 31.24 47.489-8.75 2.499-23.74-3.749-38.74 0-15 3.749-49.99-27.494-46.24-61.236s.03-137.469 11.26-146.217z"
          fill="#35b775"
        />
      </motion.g>
      <path
        d="M987.742 528.119v12.497s-6.249 28.743 13.748 27.493c19.99-1.249 7.5-34.992 7.5-34.992l-1.25-11.247-19.998 6.249zM1043.98 529.368s-13.75 28.744 0 31.243c13.75 2.5 23.74-16.246 23.74-21.245 0-4.999-23.74-9.998-23.74-9.998zM1059.6 237.56c0-2.761 1.12-4.999 2.5-4.999s2.5 2.238 2.5 4.999c0 2.761-1.12 4.999-2.5 4.999s-2.5-2.238-2.5-4.999zM985.867 237.56c0-2.761 1.119-4.999 2.5-4.999 1.38 0 2.499 2.238 2.499 4.999 0 2.761-1.119 4.999-2.499 4.999-1.381 0-2.5-2.238-2.5-4.999z"
        fill="#ffb8b8"
      />
      <path
        d="M1083.97 305.67s31.24 0 29.99 12.497-42.49 227.448-42.49 227.448-17.49-16.247-32.49-12.498l44.99-227.447zM962.748 309.419s-31.243 6.248-31.243 24.994 44.989 198.704 51.238 198.704c6.249 0 29.997-3.749 29.997-9.997 0-6.249-49.992-213.701-49.992-213.701z"
        fill="#35b775"
      />
      <path
        d="M969.621 346.285l28.119 109.964s-13.122-96.217-28.119-109.964zM1078.99 330.834l-28.44 143.772s9.09-135.479 28.44-143.772z"
        opacity={0.2}
      />
      <path
        d="M988.992 238.185c0-20.016 16.228-36.242 36.238-36.242 20.02 0 36.24 16.226 36.24 36.242s-16.22 36.242-36.24 36.242c-20.01 0-36.238-16.226-36.238-36.242z"
        fill="#ffb8b8"
      />
      <path
        d="M1058.45 201.317l-27.09-14.19-37.408 5.804-7.739 34.184 19.267-.74 5.38-12.559v12.352l8.89-.343 5.16-19.994 3.23 21.284 31.6-.644-1.29-25.154z"
        fill="#2f2e41"
      />
      <path
        d="M945.701 660.032c0 13.608-31.809 53.241-17.691 58.514 14.118 5.273 74.16-37.422 74.16-37.422l-18.49-44.905M1082.46 642.341l-25.17 48.989M1083.87 638.004l-25.2 40.064s55.35 50.767 64.13 36.671c6.95-11.147-.48-55.734-.48-55.734"
        fill="#313037"
      />
    </g>
  </svg>
)

export default Animation1

Thank you in advance!

Body:
They don't need to actually be applied with CSS as backgrounds in order behave like backgrounds for the user.

Create a parent container (e.g. div) to wrap the content you want to set the background for:

<div>
  <YourSVGComponent />
  <div>Your content</div>
</div>

Set the parent to position: relative (i.e. create a new positioning context), set the SVG styles to something like this:

position: absolute;
z-index: 1;
pointer-events: none;
top: 0;
right: 0;
bottom: 0;
left: 0;

Then I'd also recommend setting position: relative; z-index: 2 on the content div to make sure it shows up above the SVG in the stacking order.

This won't support CSS properties like background-repeat or background-position, but you can work around those on a case-by-case basis if you need to.


问:
Insert multiple strings into a string without adjusting for index changes
The conundrum I have is as follows: I have an array of the pair of indexes of a string at which one character (the third item in the sub-arrays) must be inserted (note, these pairs can be duplicates), e.g.

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];

let my_string = "This is a very important string";

for (let i = 0; i < arr.length; i++) {
  // magic code
}

// => my_string now equals "7hth2is i7hs a 2vejry imjportant string";
```

I can't just insert the character at each index because the next pair of indexes in the array will become out of date, due to the previous pair of indexes changing the string and so causing it to have new indexes for each character.

I've also tried slicing the string based on the index pairs (using them as the start and end indexes) and inserting the characters onto these substrings before merging them all together again, but the issue with this is that if two pairs of indexes overlap, then parts of the original string get duplicated.

NOTE: the array is sorted in order from smallest second index in the pair to largest, as shown above. This can be changed. However, the array will always contain pairs of indexes - i.e. I cannot flatten the array into just indexes because of the third item of the arrays being the character I want to insert.

One other thing I tried was going from the end of the array of index pairs to the start, but again the fact that index pairs can overlap means this does not work.

How would I insert the characters at each index in the array of index pairs?

Thanks in advance for any help.

答:
You could create an object of indicies containing strings, where each string item specifies the string to insert at that index. Eg, from

```<code>[[0, 6], [0, 6], [2, 10]]
</code>```

and an array of characters to insert ['x', 'y', 'z'], construct

```<code>{
  0: 'xy',
  2: 'z',
  6: 'xy',
  10: 'z'
}
</code>```

Then you can use a regular expression to match any position (without matching any characters), and use its callback function to look up the current index on the object, and replace with all the characters at that point (if any):

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];
const obj = {};
for (const [left, right, char] of arr) {
  obj[left] = (obj[left] || '') + char;
  obj[right] = (obj[right] || '') + char;
}
const my_string = "This is a very important string";

console.log(
  my_string.replace(
    /(?:)/g,
    (_, index) => obj[index] || ''
  )
);```

Body:
The conundrum I have is as follows: I have an array of the pair of indexes of a string at which one character (the third item in the sub-arrays) must be inserted (note, these pairs can be duplicates), e.g.

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];

let my_string = "This is a very important string";

for (let i = 0; i < arr.length; i++) {
  // magic code
}

// => my_string now equals "7hth2is i7hs a 2vejry imjportant string";

I can't just insert the character at each index because the next pair of indexes in the array will become out of date, due to the previous pair of indexes changing the string and so causing it to have new indexes for each character.

I've also tried slicing the string based on the index pairs (using them as the start and end indexes) and inserting the characters onto these substrings before merging them all together again, but the issue with this is that if two pairs of indexes overlap, then parts of the original string get duplicated.

NOTE: the array is sorted in order from smallest second index in the pair to largest, as shown above. This can be changed. However, the array will always contain pairs of indexes - i.e. I cannot flatten the array into just indexes because of the third item of the arrays being the character I want to insert.

One other thing I tried was going from the end of the array of index pairs to the start, but again the fact that index pairs can overlap means this does not work.

How would I insert the characters at each index in the array of index pairs?

Thanks in advance for any help.

Body:
You could create an object of indicies containing strings, where each string item specifies the string to insert at that index. Eg, from

[[0, 6], [0, 6], [2, 10]]

and an array of characters to insert ['x', 'y', 'z'], construct

{
  0: 'xy',
  2: 'z',
  6: 'xy',
  10: 'z'
}

Then you can use a regular expression to match any position (without matching any characters), and use its callback function to look up the current index on the object, and replace with all the characters at that point (if any):

let arr = [[0, 6, "7"], [0, 6, "h"], [2, 10, "2"], [12, 17, "j"]];
const obj = {};
for (const [left, right, char] of arr) {
  obj[left] = (obj[left] || '') + char;
  obj[right] = (obj[right] || '') + char;
}
const my_string = "This is a very important string";

console.log(
  my_string.replace(
    /(?:)/g,
    (_, index) => obj[index] || ''
  )
);


问:
How to compare every record to another record(name reverse problem) and erase duplicates one?
I have a terrible to identify unique record(value).
I have a table like this:

```<code>ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il-kwan      new author
3  Fumit Yanagida  best author
4  Ha Il Kwan      new author
5  Ilkwan Ha       new author
</code>```

There are 5 records in same table called autho table. But in actually, there are 2 authors.
First record and third record are stored from one author information and second, 4th and 5th are one author.
I want to make this like below.

```<code>ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il Kwan      new author
</code>```

It means that, I am going to erase all duplicates against reverse name problem.
I wonder if I can compare two values(string) in same column.
Help me please. I will be happy with your any help!

答:
Oracle answer:

create or replace table authors as
Select distinct name, description
from authors;

Body:
I have a terrible to identify unique record(value).
I have a table like this:

ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il-kwan      new author
3  Fumit Yanagida  best author
4  Ha Il Kwan      new author
5  Ilkwan Ha       new author

There are 5 records in same table called autho table. But in actually, there are 2 authors.
First record and third record are stored from one author information and second, 4th and 5th are one author.
I want to make this like below.

ID NAME            DESCRIPTION
1  Yanagida Fumit  best author
2  Ha Il Kwan      new author

It means that, I am going to erase all duplicates against reverse name problem.
I wonder if I can compare two values(string) in same column.
Help me please. I will be happy with your any help!


问:
Solution required for the query related to Visual Source Safe 6.0d
I'm using Microsoft Visual Studio .NET 2003 Enterprise Developer Tool(Visual Source Safe 6.0d). As per my knowledge, In VSS there is a provision for admin to provide the access(r/w access or checkin / checkout access) to the given specific user for a perticular folder(that is having no. of different types of files) in a project. But I want to know, Is there any provision at Admin level to provide the access for a specific file (that is in a folder) to any given user.

答: There is no file-based security setting support in VSS, as far as I know</p>

ContentLicense: CC BY-SA 3.0


问:
Update json and insert in specific postion
I have an json as:

```<code>{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new"
    }
}
</code>```

I want to update this existing one and add an extra element to the data2 part so that the output is as below:

```<code>{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new",
        "priority":"none"
    }
}
</code>```

See  "priority":"none" been added above.

I tried using data.Insert but this takes in position and the data.

How can I loop through and add this to the data2 part of my object.

Thanks

--Update

```<code> public string metaData { get; set; }

 //getting data from db
 var myData = await this.getDataAsync(id);

// myData.metaData contains the above json
</code>```

I am trying to insert another element to above.

I am not sure how to parse and add it to a particular postion with the code I am using

I have read we can deserialize the object and then add it using .Add but again I have my string above which is holding this
 how can i update this

答:
If you can use models with newtonsoft this example might help.

Model contains the additional fields you want. when deserialized in to the model, on existing properties (ones that are nullable) will be null. Then assign as you wish

```<code>using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Program
    {

        static string jsonStr = "{" +
                    "    \"count\":500," +
                    "    \"type\":\"table\"," +
                    "    \"data1\": {" +
                    "        \"name\":\"test123\"," +
                    "        \"comments\":\"test123\"," +
                    "        \"id\":\"123\"      " +
                    "    }," +
                    "    \"data2\":{" +
                    "        \"env\":\"dev\"," +
                    "        \"status\":\"new\"" +
                    "    }" +
                    "}";

        public class Data1
        {
            public string name { get; set; }
            public string comments { get; set; }
            public string id { get; set; }
        }

        public class Data2
        {
            public string env { get; set; }
            public string status { get; set; }

            // Additional property
            public string priority { get; set; }
        }

        public class RootObject
        {
            public int count { get; set; }
            public string type { get; set; }
            public Data1 data1 { get; set; }
            public Data2 data2 { get; set; }
        }

        static void Main(string[] args)
        {
            // Replace Program.jsonStr with your data from awaited context
            RootObject obj = JsonConvert.DeserializeObject<RootObject>(Program.jsonStr);
            obj.data2.priority = "none";
            Console.ReadKey();
        }
    }
}
</code>```

Body:
I have an json as:

{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new"
    }
}

I want to update this existing one and add an extra element to the data2 part so that the output is as below:

{
    "count":500,
    "type":"table",
    "data1": {
        "name":"test123",
        "comments":"test123",
        "id":"123"
    },
    "data2":{
        "env":"dev",
        "status":"new",
        "priority":"none"
    }
}

See  "priority":"none" been added above.

I tried using data.Insert but this takes in position and the data.

How can I loop through and add this to the data2 part of my object.

Thanks

--Update

 public string metaData { get; set; }

 //getting data from db
 var myData = await this.getDataAsync(id);

// myData.metaData contains the above json

I am trying to insert another element to above.

I am not sure how to parse and add it to a particular postion with the code I am using

I have read we can deserialize the object and then add it using .Add but again I have my string above which is holding this
 how can i update this

Body:
If you can use models with newtonsoft this example might help.

Model contains the additional fields you want. when deserialized in to the model, on existing properties (ones that are nullable) will be null. Then assign as you wish

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Program
    {

        static string jsonStr = "{" +
                    "    \"count\":500," +
                    "    \"type\":\"table\"," +
                    "    \"data1\": {" +
                    "        \"name\":\"test123\"," +
                    "        \"comments\":\"test123\"," +
                    "        \"id\":\"123\"      " +
                    "    }," +
                    "    \"data2\":{" +
                    "        \"env\":\"dev\"," +
                    "        \"status\":\"new\"" +
                    "    }" +
                    "}";

        public class Data1
        {
            public string name { get; set; }
            public string comments { get; set; }
            public string id { get; set; }
        }

        public class Data2
        {
            public string env { get; set; }
            public string status { get; set; }

            // Additional property
            public string priority { get; set; }
        }

        public class RootObject
        {
            public int count { get; set; }
            public string type { get; set; }
            public Data1 data1 { get; set; }
            public Data2 data2 { get; set; }
        }

        static void Main(string[] args)
        {
            // Replace Program.jsonStr with your data from awaited context
            RootObject obj = JsonConvert.DeserializeObject<RootObject>(Program.jsonStr);
            obj.data2.priority = "none";
            Console.ReadKey();
        }
    }
}


问:
ArrayList<String[]> won't add more than one item
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:

```<code>    static JComboBox<String> foodChoice;
    DefaultTableModel foodList;
    static String[] newFood;
    static List<String[]> foodData;
    JTextField newFoodText, portionText, carbsText;

public Main() {
        void createFood() {

            String[] foodProperties = new String[3];
            foodProperties[0] = newFoodText.getText();
            foodProperties[1] = portionText.getText();
            foodProperties[2] = carbsText.getText();
            Main.createFood(foodProperties);
            }

    static void createFood(String[] foodArray) {
            foodData = new ArrayList<String[]>();
            foodData.add(foodArray);
            foodChoice.addItem(foodArray[0]);
        }

        void addFoodToTable() {

            String[] s = new String[3];
            s = (String[]) foodData.get(foodChoice.getSelectedIndex());
            System.out.println(foodData.get(0));
            System.out.println(foodData.get(1));
        }
</code>```

addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!

答: Worked like a charm. Man I don't know how I missed that... I guess when you look at the same problem for too long you miss the obvious. Thanks guys!</p>

Body:
I'm trying to create an ArrayList of String[], but can't get it to add more than one item. Ultimately I want to extract the items from the ArrayList and send them to a JTable. The program is 5 separate classes, but here's the applicable code for this issue:

    static JComboBox<String> foodChoice;
    DefaultTableModel foodList;
    static String[] newFood;
    static List<String[]> foodData;
    JTextField newFoodText, portionText, carbsText;

public Main() {
        void createFood() {

            String[] foodProperties = new String[3];
            foodProperties[0] = newFoodText.getText();
            foodProperties[1] = portionText.getText();
            foodProperties[2] = carbsText.getText();
            Main.createFood(foodProperties);
            }

    static void createFood(String[] foodArray) {
            foodData = new ArrayList<String[]>();
            foodData.add(foodArray);
            foodChoice.addItem(foodArray[0]);
        }

        void addFoodToTable() {

            String[] s = new String[3];
            s = (String[]) foodData.get(foodChoice.getSelectedIndex());
            System.out.println(foodData.get(0));
            System.out.println(foodData.get(1));
        }

addFoodToTable gets called with a button click. So the issue I'm having is that (based on the sysouts) I will get a pointer address to the first entry in the ArrayList, but then a Null Pointer Exception stating that it is out of bounds for Length 0 when it tries to print the second one to console. This is obviously after calling createFood() 3 or four times in order to populate foodData. I can provide additional code if required, it's just too much to place in whole into this post. Thanks!


问:
QuickLook Generator Audio
I'm trying to create a QuickLook plugin to play audio from within a package for that package's QuickLook preview, but my attempts only display the default QL preview - a larger file icon, file name, type, size and modification date.

I've successfully displayed a test string as kUTTPlainText with my XCode setup for the targeted UTI type, and verified that the CFDataRef passed to QLPreviewRequestSetDataRepresentation isn't NULL.

Here is the basic code I've got inside my GeneratePreviewForURL function:

```<code>NSURL *audioFilePath = @"the file path";
CFDataRef data = (__bridge CFDataRef)[NSData dataWithContentsOfURL:audioFilePath];
QLPreviewRequestSetDataRepresentation(preview, data, kUTTypeAudio, NULL);
return noErr;
</code>```

Any ideas? Is playing audio from a QuickLook preview even possible?

答:
Some of the comments here refer to using audio in HTML-based Quicklook plugins (sorry, not enough reputation yet to add additional comments ).

I recently had the same problem in a project I worked on where I needed to embed an audio file, but as noted by others, trying to use that data referenced as a 'CID:' object within the Quicklook plugin fails.

The solution I found was to embed the data as Base64 encoded within the HTML, like so:

```<code><audio src="data:audio/wav;base64,{base64Data}">
</code>```

with {base64Data} replaced with the actual Base64 data. Any NSData object can be converted to a Base64 string using:

```<code>[dataObject base64EncodedStringWithOptions:0]
</code>```

Alternatively if you need to refer to that data more than once in your HTML code, you can create a Javascript URL object and use that instead:

```<code>let soundURL = new URL("data:audio/wav;base64,{base64Data}");
audioElement.src = soundURL;
</code>```

Title: QuickLook Generator Audio

Body:
I'm trying to create a QuickLook plugin to play audio from within a package for that package's QuickLook preview, but my attempts only display the default QL preview - a larger file icon, file name, type, size and modification date.

I've successfully displayed a test string as kUTTPlainText with my XCode setup for the targeted UTI type, and verified that the CFDataRef passed to QLPreviewRequestSetDataRepresentation isn't NULL.

Here is the basic code I've got inside my GeneratePreviewForURL function:

NSURL *audioFilePath = @"the file path";
CFDataRef data = (__bridge CFDataRef)[NSData dataWithContentsOfURL:audioFilePath];
QLPreviewRequestSetDataRepresentation(preview, data, kUTTypeAudio, NULL);
return noErr;

Any ideas? Is playing audio from a QuickLook preview even possible?

Body:
Some of the comments here refer to using audio in HTML-based Quicklook plugins (sorry, not enough reputation yet to add additional comments ).

I recently had the same problem in a project I worked on where I needed to embed an audio file, but as noted by others, trying to use that data referenced as a 'CID:' object within the Quicklook plugin fails.

The solution I found was to embed the data as Base64 encoded within the HTML, like so:

<audio src="data:audio/wav;base64,{base64Data}">

with {base64Data} replaced with the actual Base64 data. Any NSData object can be converted to a Base64 string using:

[dataObject base64EncodedStringWithOptions:0]

Alternatively if you need to refer to that data more than once in your HTML code, you can create a Javascript URL object and use that instead:

let soundURL = new URL("data:audio/wav;base64,{base64Data}");
audioElement.src = soundURL;


问:
Delay a transition in SwiftUI
How can I delay a transition? I want to click on a button and then a view should transition with a delay.

I have the following code but it is not properly synchronized.

struct ContentView: View {
    @State var showOne = true

    var body:some View{
        VStack{
            if showOne{
                HStack{
                    Spacer()
                    Text("One")
                    Spacer()
                }
                .animation(Animation.default.delay(2))
                .background(Color.red)
                .transition(.slide)
            }else{
                HStack{
                    Spacer()
                    Text("Two")
                    Spacer()
                }
                .background(Color.blue)
                .animation(Animation.default.delay(1))
                .transition(.slide)
            }
            Button("Toggle"){
                withAnimation(){
                    self.showOne.toggle()
                }
            }
        }
    }
}
```

答:
If you add an explicit id it works as you would like.  Note, I made only one animation delay to make it a little more obvious that this is working.

struct ContentView: View {
    @State var showOne = true
    var body:some View {
        VStack {
            if showOne {
                HStack {
                    Spacer()
                    Text("One")
                    Spacer()
                }
                .background(Color.red)
                .id("one")
                .animation(Animation.default)
                .transition(.slide)
            } else {
                HStack {
                    Spacer()
                    Text("Two")
                    Spacer()
                }
                .background(Color.blue)
                .id("two")
                .animation(Animation.default.delay(2))
                .transition(.slide)
            }
            Button("Toggle") {
                withAnimation {
                    self.showOne.toggle()
                }
            }
        }
    }
}

```

I've found an explicit id to be helpful most of the time I want to use a transition.  In your example, not using the id can cause the text to change before the background.  This would seem to be a bug, and I recommend filing feedback on it.

Title: Delay a transition in SwiftUI

Body:
If you add an explicit id it works as you would like.  Note, I made only one animation delay to make it a little more obvious that this is working.

struct ContentView: View {
    @State var showOne = true
    var body:some View {
        VStack {
            if showOne {
                HStack {
                    Spacer()
                    Text("One")
                    Spacer()
                }
                .background(Color.red)
                .id("one")
                .animation(Animation.default)
                .transition(.slide)
            } else {
                HStack {
                    Spacer()
                    Text("Two")
                    Spacer()
                }
                .background(Color.blue)
                .id("two")
                .animation(Animation.default.delay(2))
                .transition(.slide)
            }
            Button("Toggle") {
                withAnimation {
                    self.showOne.toggle()
                }
            }
        }
    }
}

I've found an explicit id to be helpful most of the time I want to use a transition.  In your example, not using the id can cause the text to change before the background.  This would seem to be a bug, and I recommend filing feedback on it.


问:
import * as (jasmine spyOn) not writable
After upgrading to babel 7.1.5 my tests fail when i'm using import * as.

test.spec.js

```<code>import * as Helper from "../../../../src/renderer/modules/Helper";

describe('Testing', () => {
    it('Should import correctly', () => {
        console.log(Helper.test()) // a
        spyOn(Helper, 'test').and.returnValue('b');
    });
});
</code>```

Helper.js

```<code>function test() {
    return 'a'
}

export {test}
</code>```

ERROR

```<code>'Upgrade.spec.js (7:8)', 'a'

Error: <spyOn> : test is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)
    at <Jasmine>
    at UserContext.it (webpack:///./test/unit/specs/renderer/Upgrade.spec.js?:7:5)
    at <Jasmine>
</code>```

答:
I've had the same issue and the only workaround I found was to use babel-plugin-rewire.

Here are the main files:

src/index.js

function bar() {
  return 42;
}

export function foo() {
  const result = bar();
  return result;
}
```
<ul>
<li>test/index_test.js</li>
</ul>
<pre class="lang-js prettyprint-override"><code>import { foo, __RewireAPI__ as RewireAPI } from '../src/index';

describe('test foo', () => {
  it('should call bar', () => {
    const barSpy = jasmine.createSpy('bar');
    RewireAPI.__Rewire__('bar', barSpy);
    foo();
    expect(barSpy).toHaveBeenCalledWith();
  });
});
</code>```

karma.conf.js

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: ['test/index_test.js'],

    // list of files / patterns to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap'],
    },

    webpack: {
      mode: 'development',
      devtool: 'inline-source-map',
      module: {
        rules: [
          {
            test: /src\/.+\.js$/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
                plugins: ['rewire'],
              },
            },
          },
        ],
      },
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    // browsers: ['Chrome'],
    browsers: ['MyHeadlessChrome'],

    customLaunchers: {
      MyHeadlessChrome: {
        base: 'ChromeHeadless',
        flags: ['--remote-debugging-port=9333'],
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,
  });
};
```
<ul>
<li>package.json</li>
</ul>
<pre class="lang-json prettyprint-override"><code>{
  "name": "webpack-karma-spy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/karma/bin/karma start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "babel-loader": "^8.0.6",
    "babel-plugin-rewire": "^1.2.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb-base": "^14.0.0",
    "eslint-plugin-import": "^2.20.1",
    "jasmine": "^3.5.0",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "^3.1.0",
    "karma-jasmine": "^3.1.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^4.0.2",
    "webpack": "^4.41.6"
  }
}
</code>```

Body:
After upgrading to babel 7.1.5 my tests fail when i'm using import * as.

test.spec.js

import * as Helper from "../../../../src/renderer/modules/Helper";

describe('Testing', () => {
    it('Should import correctly', () => {
        console.log(Helper.test()) // a
        spyOn(Helper, 'test').and.returnValue('b');
    });
});

Helper.js

function test() {
    return 'a'
}

export {test}

ERROR

'Upgrade.spec.js (7:8)', 'a'

Error: <spyOn> : test is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)
    at <Jasmine>
    at UserContext.it (webpack:///./test/unit/specs/renderer/Upgrade.spec.js?:7:5)
    at <Jasmine>

Body:
I've had the same issue and the only workaround I found was to use babel-plugin-rewire.

Here are the main files:

src/index.js

function bar() {
  return 42;
}

export function foo() {
  const result = bar();
  return result;
}

test/index_test.js

import { foo, __RewireAPI__ as RewireAPI } from '../src/index';

describe('test foo', () => {
  it('should call bar', () => {
    const barSpy = jasmine.createSpy('bar');
    RewireAPI.__Rewire__('bar', barSpy);
    foo();
    expect(barSpy).toHaveBeenCalledWith();
  });
});

karma.conf.js

module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: ['test/index_test.js'],

    // list of files / patterns to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap'],
    },

    webpack: {
      mode: 'development',
      devtool: 'inline-source-map',
      module: {
        rules: [
          {
            test: /src\/.+\.js$/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
                plugins: ['rewire'],
              },
            },
          },
        ],
      },
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    // browsers: ['Chrome'],
    browsers: ['MyHeadlessChrome'],

    customLaunchers: {
      MyHeadlessChrome: {
        base: 'ChromeHeadless',
        flags: ['--remote-debugging-port=9333'],
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,
  });
};

package.json

{
  "name": "webpack-karma-spy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/karma/bin/karma start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "babel-loader": "^8.0.6",
    "babel-plugin-rewire": "^1.2.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb-base": "^14.0.0",
    "eslint-plugin-import": "^2.20.1",
    "jasmine": "^3.5.0",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "^3.1.0",
    "karma-jasmine": "^3.1.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^4.0.2",
    "webpack": "^4.41.6"
  }
}


问:
What is the difference between a state machine and the implementation of the state pattern?
I wonder if a state machine is just the state pattern at work or if there is actually a difference between those two?

I found this article with the bold title "the state design pattern vs state machine" but at the end of the day he only says that the state pattern makes state machines obsolete but then doesn't describe what exactly is a state machine compared to the implementation of the state pattern.

答:
I wrote an article about the state design pattern and state machines: https://medium.com/@1gravityllc/the-super-state-design-pattern-166127ce7c9a. In the article I'm showing that their focus is different but that they are also not mutually exclusive. There's a way to combine the two to come up with a super state design pattern.

The emphasis of the state design pattern is on encapsulation of behavior to create reusable, maintainable components (the states).

The focus of the finite state machine is on states and their transitions (captured by the state diagram) but not on the actual behavior (that’s an implementation detail).

The article describes how these two concepts can be combined by using a finite state machine to describe and manage the states and their transitions for an object that delegates behavior to state objects using the state design pattern.


问:
Segmentation Fault (core dumped) in find/remove of linked list In C
So I am doing a very basic C exercise with a basic linked list. I keep receiving a segmentation error and I'm not too sure what it might be about.

Basically my program adds successfully and then I cant quite tell if the remove or find methods are what are giving me the error.

The structure of the Node is

```<code>struct Node {
        char * word ;
        struct Node * next ;
} ;
</code>```

I'll attach the add, find, and remove because the rest of the code is of my professors handy-work and that all runs, it is simply the issue I created.

add

```<code>void add_ll( struct Node * anchor, char * word ) {
        // given a pointer to the anchor of the list, and a word, add the word
        // to the list, does not matter where (except don't replace the anchor)
        struct Node * newNode = (struct Node *) malloc(sizeof(struct Node)) ;
        newNode -> word = word;
        newNode -> next = anchor -> next;
        anchor -> next = newNode;
        if(anchor == NULL){
          anchor -> next = NULL;
          anchor -> word = word;
      }
      return ;
  }
</code>```

find

```<code>struct Node * find_ll(struct Node * anchor, char * word) {
        // given a pointer to the anchor of the list, and a word, search
        // the list for the word. return the pointer to the with the word, if found,
        // or NULL if not found
        if (anchor -> word == NULL)
          {
            struct Node * node = new_ll();
            return node;
          }
        while(anchor != NULL)
          {
            if(anchor -> word == word)
              return anchor;
            else
              anchor = anchor -> next;
          }
        return NULL ;
}
</code>```

remove

```<code>void remove_ll( struct Node * anchor, struct Node * node_to_remove ) {
        // given a list anchor, and a pointer to a node in the list (but not the anchor)
        // do pointer surgery to remove the node, and free it.
        // sanity checks
        assert(node_to_remove) ;
        assert(node_to_remove!=anchor) ;
        while(anchor != NULL)
          {
            struct Node * temp = anchor;
            struct Node * prev = anchor;
            while(temp != NULL && temp != node_to_remove)
              {
                prev = temp;
                temp = temp -> next;
              }
            prev -> next = temp -> next;
            free(temp);
          }
        return ;
}
</code>```

A thing I have tried to see if it would fix it includes changing

while(temp != NULL && temp -> next != node_to_remove)
to
 while(temp != NULL && temp != node_to_remove)

incase it had something to do with accessing information too early, but it did not fix anything.

Also this is not graded class work if that affects you helping me morally!

So my question basically is... What is causing the segmentation error and if that truly is the only issue, how can I go about fixing it? If you notice any other mistakes please point them out too. I would really appreciate it! If I am missing any information I can add that too! All method headers are my professors and shouldn't be touched!

答:
Well, if you don't know when the error occurs, I don't either.

But I see an issue in add:

```<code>if(anchor == NULL) {
    anchor -> next = NULL;
    anchor -> word = word;
}
</code>```

If anchor is NULL, then setting it's properties is going to crash your program. NULL is not a valid pointer and should never be used.

And in find:

```<code>while(anchor != NULL)
{
    if(anchor -> word == word)
        return anchor;
    else
        anchor = anchor -> next;
}
</code>```

Do you understand what anchor->word == word does? If both point to the same string, it will return false because it is comparing the pointers. That is, it's comparing the address of each string. It will only return true if both pointers point to the same memory. Look at strcmp() to compare the string.

And in remove:

```<code>while(anchor != NULL)
{
    struct Node * temp = anchor;
    struct Node * prev = anchor;

    while(temp != NULL && temp != node_to_remove)
    {
        prev = temp;
        temp = temp -> next;
    }
    prev -> next = temp -> next;
    free(temp);
}
</code>```

So, this doesn't seem quite right either. For one thing, if temp is ever NULL, then temp = temp->next will be accessing a NULL pointer. Again, NULL is an invalid pointer and should never be used. Overall, I would complete rewrite this. I can't see any reason for nested loops. One loop should be enough. And the logic needs to be simplified.

Body:
So I am doing a very basic C exercise with a basic linked list. I keep receiving a segmentation error and I'm not too sure what it might be about.

Basically my program adds successfully and then I cant quite tell if the remove or find methods are what are giving me the error.

The structure of the Node is

struct Node {
        char * word ;
        struct Node * next ;
} ;

I'll attach the add, find, and remove because the rest of the code is of my professors handy-work and that all runs, it is simply the issue I created.

add

void add_ll( struct Node * anchor, char * word ) {
        // given a pointer to the anchor of the list, and a word, add the word
        // to the list, does not matter where (except don't replace the anchor)
        struct Node * newNode = (struct Node *) malloc(sizeof(struct Node)) ;
        newNode -> word = word;
        newNode -> next = anchor -> next;
        anchor -> next = newNode;
        if(anchor == NULL){
          anchor -> next = NULL;
          anchor -> word = word;
      }
      return ;
  }

find

struct Node * find_ll(struct Node * anchor, char * word) {
        // given a pointer to the anchor of the list, and a word, search
        // the list for the word. return the pointer to the with the word, if found,
        // or NULL if not found
        if (anchor -> word == NULL)
          {
            struct Node * node = new_ll();
            return node;
          }
        while(anchor != NULL)
          {
            if(anchor -> word == word)
              return anchor;
            else
              anchor = anchor -> next;
          }
        return NULL ;
}

remove

void remove_ll( struct Node * anchor, struct Node * node_to_remove ) {
        // given a list anchor, and a pointer to a node in the list (but not the anchor)
        // do pointer surgery to remove the node, and free it.
        // sanity checks
        assert(node_to_remove) ;
        assert(node_to_remove!=anchor) ;
        while(anchor != NULL)
          {
            struct Node * temp = anchor;
            struct Node * prev = anchor;
            while(temp != NULL && temp != node_to_remove)
              {
                prev = temp;
                temp = temp -> next;
              }
            prev -> next = temp -> next;
            free(temp);
          }
        return ;
}

A thing I have tried to see if it would fix it includes changing

while(temp != NULL && temp -> next != node_to_remove)
to
 while(temp != NULL && temp != node_to_remove)

incase it had something to do with accessing information too early, but it did not fix anything.

Also this is not graded class work if that affects you helping me morally!

So my question basically is... What is causing the segmentation error and if that truly is the only issue, how can I go about fixing it? If you notice any other mistakes please point them out too. I would really appreciate it! If I am missing any information I can add that too! All method headers are my professors and shouldn't be touched!

Body:
Well, if you don't know when the error occurs, I don't either.

But I see an issue in add:

if(anchor == NULL) {
    anchor -> next = NULL;
    anchor -> word = word;
}

If anchor is NULL, then setting it's properties is going to crash your program. NULL is not a valid pointer and should never be used.

And in find:

while(anchor != NULL)
{
    if(anchor -> word == word)
        return anchor;
    else
        anchor = anchor -> next;
}

Do you understand what anchor->word == word does? If both point to the same string, it will return false because it is comparing the pointers. That is, it's comparing the address of each string. It will only return true if both pointers point to the same memory. Look at strcmp() to compare the string.

And in remove:

while(anchor != NULL)
{
    struct Node * temp = anchor;
    struct Node * prev = anchor;

    while(temp != NULL && temp != node_to_remove)
    {
        prev = temp;
        temp = temp -> next;
    }
    prev -> next = temp -> next;
    free(temp);
}

So, this doesn't seem quite right either. For one thing, if temp is ever NULL, then temp = temp->next will be accessing a NULL pointer. Again, NULL is an invalid pointer and should never be used. Overall, I would complete rewrite this. I can't see any reason for nested loops. One loop should be enough. And the logic needs to be simplified.


问:
How Can i remove duplicate from a list in Groovy
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

```<code>["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]
</code>```

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

```<code>// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.
</code>```

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

答:
Assume we start with a list like this:

```<code>def list = ["154515 Sawgrass",
            "170985 Mexico APIs for Payments",
            "153026 CitiCards Consumer and Business Account Online (authenticated pgs) No CSI App ID",
            "153890 GC Citibank Online - Singapore IPB v3",
            "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
            "171706 Quip",
            "167518 GC Eclipse [Teller]",
            "167518 GC Eclipse [Signature]"]

</code>```

Then we can start with a new list and a set of values:

```<code>def listUniqueValues = []
def valuesAlreadySeen = new HashSet()
</code>```

Then we iterate over the list, checking to see if the current value is in the set of "previously seen" values:

```<code>list.each { item ->
    def value = item.split(" ")[0]

    if (! valuesAlreadySeen.contains(value)) {
        listUniqueValues << item
    }

    valuesAlreadySeen << value
}
</code>```

then we can sort listUniqueValues and print:

```<code>listUniqueValues.sort() { a,b -> a <=> b }.each { println it }
</code>```

to get

```<code>144564 Citibank Online (CBOL) US, Zack Dummy CSI #3
153026 CitiCards Consumer and Business Account Online (authenticated pgs) No CSI App ID
153890 GC Citibank Online - Singapore IPB v3
154515 Sawgrass
167518 GC Eclipse [Teller]
170985 Mexico APIs for Payments
171706 Quip
</code>```

NOTE: this isn't the most efficient method, nor the "Grooviest" (there is a cooler way with the inject method). But it is straight-forward and hopefully easy to understand.

Body:
Hi I have a groovy code for JIRA.
Here I need to sort or remove duplicate value from the list.

Ex :

["154515 Sawgrass",
 "170985 Mexico APIs for Payments",
 "153026 CitiCards Consumer and Business Account Online (authenticated pgs), No CSI App ID",
 "153890 GC Citibank Online - Singapore IPB v3",
 "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
 "171706 Quip",
 "167518 GC Eclipse [Teller]",
 "167518 GC Eclipse [Signature]]",]

the above is the result, from where I need a sorting like ... 167518 - with this number there are two values, but I need to store only one 167518, I dont want to store multi value. or else in simple word I need to sort the list in this way that if number is same but with multiple values, I need to store only 1 value with same number.

// From here Child Issue Details Starts....
def issue = event.issue as Issue
def issueManager = ComponentAccessor.getIssueManager() ;
def customField = ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602")
log.debug("Printing Custom Field : --" + customField)
def impactedAppValues = customField.getValueFromIssue(issue) as String
log.info "Printing Custom Field with Issuee Value : --" + impactedAppValues

String[] elements = impactedAppValues.split("\\s*[;]\\s*");
log.info "Printing elements with Issuee Value : --" + elements

List<String> fixedLenghtList = Arrays.asList(elements);

ArrayList<String> listOfString = new ArrayList<String>(fixedLenghtList);

log.info "Printing listOfString with Issuee Value : --" + listOfString

// From here parent Issue Details Starts....
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Parent Link")
def parentValue = issue.getCustomFieldValue(cf)
log.info "Printing parentValue value :-----" + parentValue

def planviewProjectSide =  ComponentAccessor.getComponent(CustomFieldManager).getCustomFieldObject("customfield_10602");
Issue PlanviewIssue = issueManager.getIssueObject("" + parentValue);
def parentCustomField = planviewProjectSide.getValueFromIssue(PlanviewIssue) as String
log.info "Printing parentCustomField value :-----" + parentCustomField

String[] elements1 = parentCustomField.split("\\s*[;]\\s*");
log.info "Printing elements for Parent Issuee Value : --" + elements1

List<String> fixedLenghtList1 = Arrays.asList(elements1);

ArrayList<String> listOfString1 = new ArrayList<String>(fixedLenghtList1);

log.info "Printing listOfString1 For Parent Issuee Value : --" + listOfString1

listOfString1.addAll(listOfString)
log.info "Printing listOfString1 Againnnnnnnnn For Combined Value of 1 & 2--" + listOfString1

listOfString1.unique()
log.info "Printing listOfString1 Unique Values of 1 & 2--" + listOfString1

parentCustomField = listOfString1 as String
log.info "Printing parentCustomField -----" + parentCustomField

here I have gave the code for what I have written till now.

Is this possible to to sort like the above? I mean we can remove the duplicates but how to removes the number from a value or String?

Body:
Assume we start with a list like this:

def list = ["154515 Sawgrass",
            "170985 Mexico APIs for Payments",
            "153026 CitiCards Consumer and Business Account Online (authenticated pgs) No CSI App ID",
            "153890 GC Citibank Online - Singapore IPB v3",
            "144564 Citibank Online (CBOL) US, Zack Dummy CSI #3",
            "171706 Quip",
            "167518 GC Eclipse [Teller]",
            "167518 GC Eclipse [Signature]"]

Then we can start with a new list and a set of values:

def listUniqueValues = []
def valuesAlreadySeen = new HashSet()

Then we iterate over the list, checking to see if the current value is in the set of "previously seen" values:

list.each { item ->
    def value = item.split(" ")[0]

    if (! valuesAlreadySeen.contains(value)) {
        listUniqueValues << item
    }

    valuesAlreadySeen << value
}

then we can sort listUniqueValues and print:

listUniqueValues.sort() { a,b -> a <=> b }.each { println it }

to get

144564 Citibank Online (CBOL) US, Zack Dummy CSI #3
153026 CitiCards Consumer and Business Account Online (authenticated pgs) No CSI App ID
153890 GC Citibank Online - Singapore IPB v3
154515 Sawgrass
167518 GC Eclipse [Teller]
170985 Mexico APIs for Payments
171706 Quip

NOTE: this isn't the most efficient method, nor the "Grooviest" (there is a cooler way with the inject method). But it is straight-forward and hopefully easy to understand.


问:
Test null hypothesis that regression coefficient equals a nonzero value in statsmodels OLS
In Python statsmodels, calling summary() on an OLS model gives the p value for coefficients equaling zero. Is there a way to test that the coefficient equals some nonzero value?

This CrossValidated question shows that offset() can be used for this in R.

答:
statsmodels includes several methods for hypothesis tests in the results classes. Those are mostly based on Wald test and make it very easy to test linear hypothesis on the parameters.

see for example t_test
https://www.statsmodels.org/stable/generated/statsmodels.regression.linear_model.OLSResults.t_test.html

A simple expample is results.t_test("x1 = 1") when there is a variable with name "x1".

https://github.com/statsmodels/statsmodels/issues/3676 is a FAQ issue that provides some overview of existing and planned hypothesis tests after a model has been estimated


问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答:
Since you are cacthing the exception (and not throwing it again) in your example, The outside code assumes everyting is okay and therefor you should return something useful.

If you need to catch the exception there and do somthing that's all fine, but if it's still an error case you should also throw it, or a different exception, perhaps with the one you just caught as InnerException.

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

OwnerDisplayName: Kris


问:
PIP3 - How to reduce time taken for Building wheel for <lib>?
I run pip3 on a Jetson Nano board which has 4 cores ARM A57 and class 1 sdcard. It is ubuntu 18.04 with nVidia repositories.

pip3 install --user pandas

Takes almost 1 hour!
I have to do it multiple times because I'm building an environment over main OS and dockers. (same behavior on ubuntu and docker image)

HTOP shows that only 1 core is used at 100%; 3 others are idling.

I've thought using --user would resume "Building Wheel" process...
Any option to get pip3 things go faster?
Can I force Pip3 on multiple cores?
It seems to be a GCC task.

答:
Download source code, run python setup.py bdist_wheel to generate a binary wheel once, upload the wheel to some internal server and install from it every time you need it:

```<code>pip install http://<internal-server>/path/to/wheels/pandas.whl
</code>```

Binary wheels are installed quite fast; you only need to compile once.

Or run pip wheel pandas. Or collect all your requirements into requirements.txt and run pip wheel -r requirements.txt to build your wheelhouse. To install from it:

```<code>pip install --index-url=http://<internal-server>/path/to/wheels/ pandas
</code>```

Body:
Download source code, run python setup.py bdist_wheel to generate a binary wheel once, upload the wheel to some internal server and install from it every time you need it:

pip install http://<internal-server>/path/to/wheels/pandas.whl

Binary wheels are installed quite fast; you only need to compile once.

Or run pip wheel pandas. Or collect all your requirements into requirements.txt and run pip wheel -r requirements.txt to build your wheelhouse. To install from it:

pip install --index-url=http://<internal-server>/path/to/wheels/ pandas


问:
Full Width Material-UI Grid not working as it should
I am trying to understand Material-UI@next grid layout system.

My goal is to have two papers that expand through the whole width screen and break whenever the screen gets smaller to just one paper. The documentation has the following code snippet:

```<code>  <Container>
    <Grid container spacing={24}>
      <Grid item xs={12}>
        <Paper>xs=12</Paper>
      </Grid>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
    </Grid>
  </Container>
</code>```

This results in the following:

I then modified the code to try to achieve my goal of just two papers, as this:

```<code>  <Container>
    <Grid container spacing={24}>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
    </Grid>
  </Container>
</code>```

But as you can see, this results into two papers which are not taking the whole screen:

Can someone point me to a working example snippet that allows me to have two elements that take the full width?

答:
For those using Material UI with styled-components, here's how I was able to get the grid items to grow correctly:

```<code>import GridBase from "@material-ui/core/Grid";

const Grid = styled(GridBase)`
  .MuiGrid-root {
    flex-grow: 1;
  }
`
</code>```

Now you can use Grid normally in your components.

Body:
I am trying to understand Material-UI@next grid layout system.

My goal is to have two papers that expand through the whole width screen and break whenever the screen gets smaller to just one paper. The documentation has the following code snippet:

  <Container>
    <Grid container spacing={24}>
      <Grid item xs={12}>
        <Paper>xs=12</Paper>
      </Grid>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
      <Grid item xs={6} sm={3}>
        <Paper>xs=6 sm=3</Paper>
      </Grid>
    </Grid>
  </Container>

This results in the following:

I then modified the code to try to achieve my goal of just two papers, as this:

  <Container>
    <Grid container spacing={24}>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
      <Grid item xs={12} sm={6}>
        <Paper>xs=12 sm=6</Paper>
      </Grid>
    </Grid>
  </Container>

But as you can see, this results into two papers which are not taking the whole screen:

Can someone point me to a working example snippet that allows me to have two elements that take the full width?

Body:
For those using Material UI with styled-components, here's how I was able to get the grid items to grow correctly:

import GridBase from "@material-ui/core/Grid";

const Grid = styled(GridBase)`
  .MuiGrid-root {
    flex-grow: 1;
  }
`

Now you can use Grid normally in your components.