问:
Getting a loading wrapper properties error in Android
I am getting the following error :</p>

```<code>'C:\Users\install\Desktop\project\CoMpC2\gradle\wrapper\gradle-wrapper.properties'.
No value with key 'distributionUrl' specified in wrapper properties file 'C:\Users\install\Desktop\project\CoMpC2\gradle\wrapper\gradle-wrapper.properties'.
</code>```

答:
I had the same / a similar issue. Ideally we should not have to make any changes & Android Studio handles these things automatically.

For some reason some of my configuration got corrupted because of which every time I created a project it failed with these errors and was only putting the Gradle folder in the Project hierarchy and not generating any of the project files.

All I did was delete the .gradle, .android, .AndroidStudiox.x folder in this location: C:\Users\username and the next time I loaded Android Studio it reconfigured those dependencies and got rid of the error.

Body:
I am getting the following error :

'C:\Users\install\Desktop\project\CoMpC2\gradle\wrapper\gradle-wrapper.properties'.
No value with key 'distributionUrl' specified in wrapper properties file 'C:\Users\install\Desktop\project\CoMpC2\gradle\wrapper\gradle-wrapper.properties'.


来源: stackexchange

问:
How to access key pair values of individual elements in an array multiple times in 1 API call?
The API request that I am using will return an array of elements and within each element, there are multiple key pair values.

A similar response would like this API: https://www.poemist.com/api/v1/randompoems, which returns an array of poems.

```<code>[
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
]
</code>```

I am using Webflow's embedded code feature to display the responses from the API in multiple boxes:

An example snippet:

```<code><h1 id ="title"></h1>
<p id ="content"></p>
<script>
    fetch("https://www.poemist.com/api/v1/randompoems")
      .then((res) => res.json())
      .then((data) => {
        const { title, content} = data[0];
        document.getElementById("title").textContent = title
        document.getElementById("content").textContent = content
      });
</script>
</code>```

My limits:

In the boxes, there are other unique div classes that contain unique info. So I don't think I can use a for loop.

My question:

I could use the exact same snippet 4 times and change the element respectively, but I will be making 4 API calls. Is there a way that I could call the API just once and then access the data individually? Webflow allows you to add a script at the head tag, so the API request do not necessarily need to be inside the individual embedded code snippet.

答:
```<code><h1 id ="title_0"></h1>
<p id ="content_0"></p>
<script>
    fetch("https://www.poemist.com/api/v1/randompoems")
      .then((res) => res.json())
      .then((data) => {
        for (i=0; i<=4; i++){
        const {title, content} = data[i];
        document.getElementById("title_" + i).textContent = title
        document.getElementById("content_" + i).textContent = content
        }
      });
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The API request that I am using will return an array of elements and within each element, there are multiple key pair values.

A similar response would like this API: https://www.poemist.com/api/v1/randompoems, which returns an array of poems.

[
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
]

I am using Webflow's embedded code feature to display the responses from the API in multiple boxes:

An example snippet:

My limits:

In the boxes, there are other unique div classes that contain unique info. So I don't think I can use a for loop.

My question:

I could use the exact same snippet 4 times and change the element respectively, but I will be making 4 API calls. Is there a way that I could call the API just once and then access the data individually? Webflow allows you to add a script at the head tag, so the API request do not necessarily need to be inside the individual embedded code snippet.


问:
Calling unix shell script remotely from C#
In my current project, i need to call a Unix shell script from the C# application. I also need to get the response back whether the script has been execute successfully or any error has occurred.

The C# program is running on a Windows machine. I need to connect to a Unix machine and execute the script.

Can anyone let me know how this can be done using C#?

答:
A straight forward way of preforming this using System.Diagnostics.Process </p>

```
<code>
// Start the child process.
 Process p = new Process();
 // Redirect the error stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardError = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected error stream.
 // p.WaitForExit();
 // Read the error stream first and then wait.
 string error = p.StandardError.ReadToEnd();
 p.WaitForExit();
</code>
```

ContentLicense: CC BY-SA 3.0

Body:
A straight forward way of preforming this using System.Diagnostics.Process

// Start the child process.
 Process p = new Process();
 // Redirect the error stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardError = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected error stream.
 // p.WaitForExit();
 // Read the error stream first and then wait.
 string error = p.StandardError.ReadToEnd();
 p.WaitForExit();


问:
How can I jump to the error line in Vscode Just like Intellij idea
what should I do to go to the error line just like intellij idea in vscode
vscode debug info

idea debug info

答:
Open the View menu

Select the Problems menu item

Press the Enter key to move to the first problem

Press F8 to move to the next problem

Alternatively, the keyboard shortcut is CTRL + SHIFT + M. You might want to look at the official quick start guide.


问:
What is the time complexity of this code, and could you explain how you calculated it?
The code below I found the time complexity to be n^2 if that is correct?</p>

```<code>int numbers[9] = {1, 5, 7, 8, 9, 14, 21};
int check = 50;

int count = 0;
for (int i = 0; i < 9; i++) {
    int squared = numbers[i]*numbers[i];
    int target = check - squared;
    for (int j = i; j < 9; j++) {
        if (numbers[j]*numbers[j] == target) {
            count++;
        }
    }
}
if (count == 2) {
    printf("Yes\n");
} else {
    printf("No\n");
}
return 0;
</code>```

答:
Yes, the worst case time complexity will be O(n^2), with n obviously being the length of the array.

To find the time complexity of any code you need to count how many times is executed the most recurrent function in your code. In this case that is the comparison numbers[j]*numbers[j] == target.
After finding that the math in this case is easy, the outer loop is executed up to n times (in this case hardcoded to 9, not recommended), and for each of those times the inner loop is executed up to n times resulting in a worst case time complexity of O(n^2).

If you're also interested in the best case time complexity it's still O(n^2) but it can be easily be dropped to 2.

Body:
The code below I found the time complexity to be n^2 if that is correct?

int numbers[9] = {1, 5, 7, 8, 9, 14, 21};
int check = 50;

int count = 0;
for (int i = 0; i < 9; i++) {
    int squared = numbers[i]*numbers[i];
    int target = check - squared;
    for (int j = i; j < 9; j++) {
        if (numbers[j]*numbers[j] == target) {
            count++;
        }
    }
}
if (count == 2) {
    printf("Yes\n");
} else {
    printf("No\n");
}
return 0;


问:
Froala Editor - Image Upload Event Not working - Angular 9
Hello

```<code>   public options: Object = {
      events: {
        'froalaEditor.image.beforeUpload': function(e, editor, images) {

            alert('')
        }
    }
}
</code>```

after uploading image event is not working

答:
You need to install axios into the project to help with sending the request:

For that run the following command

```<code>npm install axios
</code>```

After that, you have a couple that allows image upload to servers, but the most important is that, the imageUpload property must be set to true, see code snippet below for more:

public options: Object = {
  charCounterCount: true,
  imageUpload: true,
  imageUploadMethod: 'POST',
  // Set max image size to 5MB.
  imageMaxSize: 5 * 1024 * 1024,
  events: {
    'froalaEditor.image.beforeUpload': function(e, editor, images): any {
      // Before image is uploaded
      const data = new FormData();
      data.append('image', images[0]);

      axios.post('your_imgur_api_url', data, {
        headers: {
          'accept': 'application/json',
          'Authorization': 'your_imgur_client_id/api_key',
          'Accept-Language': 'en-US,en;q=0.8',
        }
      }).then(res => {
        editor.image.insert(res.data.data.link, null, null, editor.image.get());
      }).catch(err => {
        console.log(err);
      });
      return false;
    }
  }
};
```

Body:
Hello

   public options: Object = {
      events: {
        'froalaEditor.image.beforeUpload': function(e, editor, images) {

            alert('')
        }
    }
}

after uploading image event is not working

Body:
You need to install axios into the project to help with sending the request:

For that run the following command

npm install axios

After that, you have a couple that allows image upload to servers, but the most important is that, the imageUpload property must be set to true, see code snippet below for more:

public options: Object = {
  charCounterCount: true,
  imageUpload: true,
  imageUploadMethod: 'POST',
  // Set max image size to 5MB.
  imageMaxSize: 5 * 1024 * 1024,
  events: {
    'froalaEditor.image.beforeUpload': function(e, editor, images): any {
      // Before image is uploaded
      const data = new FormData();
      data.append('image', images[0]);

      axios.post('your_imgur_api_url', data, {
        headers: {
          'accept': 'application/json',
          'Authorization': 'your_imgur_client_id/api_key',
          'Accept-Language': 'en-US,en;q=0.8',
        }
      }).then(res => {
        editor.image.insert(res.data.data.link, null, null, editor.image.get());
      }).catch(err => {
        console.log(err);
      });
      return false;
    }
  }
};


问:
AVAudioEngine Multichannel mapping
I've converted the objc code to swift: https://forums.developer.apple.com/thread/15416
My audio file will play on my iPhone but when I plug in an audio interface I just get silence. My audio interface has 4 outputs and will play audio in other apps.
Here is the converted code:

```<code>let audioSession = AVAudioSession.sharedInstance()

 // set the session category
 do
 {
     try audioSession.setCategory(.multiRoute, options: .mixWithOthers)
 }
 catch
 {
     print("unable to set category", error)
     return
 }

 // activate the audio session
 do
 {
     try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
 }
 catch
 {
     print("unable to set active", error)
     return
 }

 engine = AVAudioEngine()
 output = engine.outputNode
 mixer = engine.mainMixerNode

 player = AVAudioPlayerNode()

 engine.attach(player)

 guard let filePath: String = Bundle.main.path(forResource: "audio", ofType: "m4a") else { return }
 let fileURL: URL = URL(fileURLWithPath: filePath)
 let file = try! AVAudioFile(forReading: fileURL)

 let numberOfSourceChannels = file.processingFormat.channelCount
 print("numberOfSourceChannels: ", numberOfSourceChannels)

 let outputNumChannels = output.outputFormat(forBus: 0).channelCount
 print("outputNumChannels:" , outputNumChannels)
 var outputChannelMap = [
     0,
     1,
     -1,
     -1
 ]

 if let au = output.audioUnit
 {
     let propSize = UInt32(MemoryLayout.size(ofValue: outputChannelMap))
     print("propSize:", propSize)
     AudioUnitSetProperty(au, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Global, 0, &outputChannelMap, propSize)
 }

 let channelLayout = AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_DiscreteInOrder | UInt32(numberOfSourceChannels))

 let format = AVAudioFormat(streamDescription: file.processingFormat.streamDescription, channelLayout: channelLayout)

 engine.connect(player, to: mixer, format:format)
 engine.connect(mixer, to: output, format:format)

 player.scheduleFile(file, at: nil, completionHandler: nil)

 do
 {
    try engine.start()
 }
 catch
 {
     print("can't start", error)
     return
 }

 player.play()
</code>```

Here is the output from running it:

```<code>/private/var/containers/Bundle/Application/FF7AA751-35A3-4B70-92C3-2D8356DE835A/AVAudioEngineTest.app/audio.m4a
numberOfSourceChannels:  2
outputNumChannels: 4
propSize: 8
</code>```

My end goal is to be able to choose which output a node will play on.
What am I doing wrong? Thanks in advance.

答:
It turns out the code is fine except for the outputChannelMap. I was confused at how it should work. Here is a few examples of how it should work:</p>

```<code>//normal output
var outputChannelMap = [
    0,
    1
]

// left audio to left output only
outputChannelMap = [
    0,
    -1
]

// both audio channels to left output
outputChannelMap = [
    0,
    0
]

// both audio channels to right output
outputChannelMap = [
    1,
    1
]

//left audio channel to right output only
outputChannelMap = [
    1,
    -1
]

// left out right, right our left
outputChannelMap = [
    1,
    0
]

// right audio to left output only
outputChannelMap = [
    -1,
    0
]

// right audio  to right output only
outputChannelMap = [
    -1,
    1
]
</code>```

Title: AVAudioEngine Multichannel mapping

Body:
I've converted the objc code to swift: https://forums.developer.apple.com/thread/15416
My audio file will play on my iPhone but when I plug in an audio interface I just get silence. My audio interface has 4 outputs and will play audio in other apps.
Here is the converted code:

let audioSession = AVAudioSession.sharedInstance()

 // set the session category
 do
 {
     try audioSession.setCategory(.multiRoute, options: .mixWithOthers)
 }
 catch
 {
     print("unable to set category", error)
     return
 }

 // activate the audio session
 do
 {
     try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
 }
 catch
 {
     print("unable to set active", error)
     return
 }

 engine = AVAudioEngine()
 output = engine.outputNode
 mixer = engine.mainMixerNode

 player = AVAudioPlayerNode()

 engine.attach(player)

 guard let filePath: String = Bundle.main.path(forResource: "audio", ofType: "m4a") else { return }
 let fileURL: URL = URL(fileURLWithPath: filePath)
 let file = try! AVAudioFile(forReading: fileURL)

 let numberOfSourceChannels = file.processingFormat.channelCount
 print("numberOfSourceChannels: ", numberOfSourceChannels)

 let outputNumChannels = output.outputFormat(forBus: 0).channelCount
 print("outputNumChannels:" , outputNumChannels)
 var outputChannelMap = [
     0,
     1,
     -1,
     -1
 ]

 if let au = output.audioUnit
 {
     let propSize = UInt32(MemoryLayout.size(ofValue: outputChannelMap))
     print("propSize:", propSize)
     AudioUnitSetProperty(au, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Global, 0, &outputChannelMap, propSize)
 }

 let channelLayout = AVAudioChannelLayout(layoutTag: kAudioChannelLayoutTag_DiscreteInOrder | UInt32(numberOfSourceChannels))

 let format = AVAudioFormat(streamDescription: file.processingFormat.streamDescription, channelLayout: channelLayout)

 engine.connect(player, to: mixer, format:format)
 engine.connect(mixer, to: output, format:format)

 player.scheduleFile(file, at: nil, completionHandler: nil)

 do
 {
    try engine.start()
 }
 catch
 {
     print("can't start", error)
     return
 }

 player.play()

Here is the output from running it:

/private/var/containers/Bundle/Application/FF7AA751-35A3-4B70-92C3-2D8356DE835A/AVAudioEngineTest.app/audio.m4a
numberOfSourceChannels:  2
outputNumChannels: 4
propSize: 8

My end goal is to be able to choose which output a node will play on.
What am I doing wrong? Thanks in advance.

Body:
It turns out the code is fine except for the outputChannelMap. I was confused at how it should work. Here is a few examples of how it should work:

//normal output
var outputChannelMap = [
    0,
    1
]

// left audio to left output only
outputChannelMap = [
    0,
    -1
]

// both audio channels to left output
outputChannelMap = [
    0,
    0
]

// both audio channels to right output
outputChannelMap = [
    1,
    1
]

//left audio channel to right output only
outputChannelMap = [
    1,
    -1
]

// left out right, right our left
outputChannelMap = [
    1,
    0
]

// right audio to left output only
outputChannelMap = [
    -1,
    0
]

// right audio  to right output only
outputChannelMap = [
    -1,
    1
]


问:
How do I approach multiplatform app with React
I'm just learning development and recently, I finished a MERN stack course.

Now I'm wanting to build my second Commercial App for the company where I am working.
At first, I was only considering responsive web platform but now, I can't deny the necessity of functionality on ios and Android.

Thus, I did my own research on which framework or method I will have to use to minimize my production time rather than using react web and react native separately.
It seems like Expo Web and React Native Web will be the closest solution I can think of.

I'm not sure if I'm trying to take things too easy, but if someone can enlighten me with suggestions on how to approach this dillema, that will be greatly appreciated.

In Short.

What is better? Expo Web or Native Web and best way to learn..

答:
When using Expo, you're building the same app for iOS, Android, and Web at the same time.

Building an app with Expo CLI will provide a 100% code base across the 3 platforms. Because the Expo SDK covers most, if not, all the tools you need to build a simple application without touching native code.

Expo also offers you the possibility to eject from it, if by any chance you need to change native code.

I would suggest that you start with Expo CLI, because of how rich its SDK is and how easy it is to get started with it. And if later in time you wanna modify native code, you can eject from it.


问:
Embed logo into email
I'm wondering how can I embed a logo into email. The logo is saved on Google Drive. Also, I know the reference inlineimage and blob need to be used but I don't know how.

I tried this code, but no success

var Img = DriveApp.getFileById(1pRBZ....cKMFll1OouC..er2V97e8...).getBlob();

The line below retreive the message template. So, I want to include the image into the message as a signature.

var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();

```<code>function EnvoiIDCourriel() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
  var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var LR = SS.getLastRow()

  var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
  //Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template

  //Logger.log(NomCandidat);

  //Cette ligne permet de passer à travers de toutes les lignes inscrites
  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

}
</code>```

答:
I believe your goal as follows.

You want to add a logo image to the email using the inlineimage.

The logo image file is put in your Google Drive.

For this, how about this answer?

Modification points:

In order to add the logo image to the email, it is required to use the HTML body.

In this case, options of sendEmail(recipient, subject, body, options) is used.

Modified script:

When your script is modified, it becomes as follows.

From:

```<code>  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});
</code>```

To:

```<code>var fileId = "###";  // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob();  // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    var html = CorpsMessage + '<BR><img src="cid:logo">';  // Added
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}});  // Modified
  }
});
</code>```

or

To:

As other modification, this is the method for using the HTML template. By this, you can prepare the HTML body of the email as a file.

```<code>var fileId = "###";  // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob();  // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    var html = HtmlService.createTemplateFromFile("index");  // Added
    html.text = CorpsMessage;  // Added
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html.evaluate().getContent(), inlineImages: {logo: blob}});  // Added
  }
});
</code>```

And, please create a HTML file at the script editor as the filename of index.html and copy&paste the following HTML.

```<code><!DOCTYPE html>
<html>
  <body>
    <?= text ?>
    <BR>
    <img src="cid:logo">
  </body>
</html>
</code>```

Note:

In this modified script, CorpsMessage + '
' is used as the HTML body. So if you want to modify for your actual situation, please modify this.

logo of cid:logo is corresponding to logo of inlineImages: {logo: blob}.

If the email client cannot read the HTML email, the logo is not shown. Please be careful this.

References:

sendEmail(recipient, subject, body, options)

HTML Service: Templated HTML

Added:

From your replying, you want to use the email template as follows.

```<code>Bonjour {Nom},

Ceci est vorte code d'identification : {ID}

Ce code devra être utillisé lors de votre examen en Iigne pour le processus : {Processus}.

Bon succés !

---
Equipe des tests en ligne

Service des Ressources Humaines
</code>```

For this, how about the following modification? In this case, please modify above template as follows.

From:

```<code>Equipe des tests en ligne
</code>```

To:

```<code>{LOGO}
</code>```

In this modification, {LOGO} is replaced with the logo image.

Modified script:

Please modify your script as follows.

From:

```<code>  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});
</code>```

To:

```<code>var fileId = "###";  // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob();  // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    var html = CorpsMessage.replace(/\n/g, '<br>').replace('{LOGO}', '<img src="cid:logo">');  // Added
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}});  // Modified
  }
});
</code>```

Title: Embed logo into email

Body:
I'm wondering how can I embed a logo into email. The logo is saved on Google Drive. Also, I know the reference inlineimage and blob need to be used but I don't know how.

I tried this code, but no success

var Img = DriveApp.getFileById(1pRBZ....cKMFll1OouC..er2V97e8...).getBlob();

The line below retreive the message template. So, I want to include the image into the message as a signature.

var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();

function EnvoiIDCourriel() {

  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Liste").activate();
  var SS = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var LR = SS.getLastRow()

  var TemplateTexte = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Template").getRange(1, 1).getValue();
  //Permet d'utiliser le corps du courriel qui se trouve dans l'onglet Template

  //Logger.log(NomCandidat);

  //Cette ligne permet de passer à travers de toutes les lignes inscrites
  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

}

Body:
I believe your goal as follows.

You want to add a logo image to the email using the inlineimage.

The logo image file is put in your Google Drive.

For this, how about this answer?

Modification points:

In order to add the logo image to the email, it is required to use the HTML body.

In this case, options of sendEmail(recipient, subject, body, options) is used.

Modified script:

When your script is modified, it becomes as follows.

From:

  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

To:

var fileId = "###";  // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob();  // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    var html = CorpsMessage + '<BR><img src="cid:logo">';  // Added
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}});  // Modified
  }
});

or

To:

As other modification, this is the method for using the HTML template. By this, you can prepare the HTML body of the email as a file.

var fileId = "###";  // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob();  // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    var html = HtmlService.createTemplateFromFile("index");  // Added
    html.text = CorpsMessage;  // Added
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html.evaluate().getContent(), inlineImages: {logo: blob}});  // Added
  }
});

And, please create a HTML file at the script editor as the filename of index.html and copy&paste the following HTML.

<!DOCTYPE html>
<html>
  <body>
    <?= text ?>
    <BR>
    <img src="cid:logo">
  </body>
</html>

Note:

In this modified script, CorpsMessage + '<BR><img src="cid:logo">' is used as the HTML body. So if you want to modify for your actual situation, please modify this.

logo of cid:logo is corresponding to logo of inlineImages: {logo: blob}.

If the email client cannot read the HTML email, the logo is not shown. Please be careful this.

References:

sendEmail(recipient, subject, body, options)

HTML Service: Templated HTML

Added:

From your replying, you want to use the email template as follows.

Bonjour {Nom},

Ceci est vorte code d'identification : {ID}

Ce code devra être utillisé lors de votre examen en Iigne pour le processus : {Processus}.

Bon succés !

---
Equipe des tests en ligne

Service des Ressources Humaines

For this, how about the following modification? In this case, please modify above template as follows.

From:

Equipe des tests en ligne

To:

{LOGO}

In this modification, {LOGO} is replaced with the logo image.

Modified script:

Please modify your script as follows.

From:

  var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
  values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
    if (check === true) {
       var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
       var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage);
  }
});

To:

var fileId = "###";  // Added: Please set the file ID of the logo image.
var blob = DriveApp.getFileById(fileId).getBlob();  // Added
var values = SS.getRange("A2:E" + SS.getLastRow()).getValues();
values.forEach(([check, NomCandidat, ID, CurrentEmail, Processus]) => {
  if (check === true) {
    var CorpsMessage = TemplateTexte.replace("{Nom}",NomCandidat).replace("{ID}",ID).replace("{Processus}",Processus);
    var ObjetCourriel = "Code d'identification: " + ID + " - Test en ligne";
    var html = CorpsMessage.replace(/\n/g, '<br>').replace('{LOGO}', '<img src="cid:logo">');  // Added
    GmailApp.sendEmail(CurrentEmail, ObjetCourriel, CorpsMessage, {htmlBody: html, inlineImages: {logo: blob}});  // Modified
  }
});


问:
HTTPoison.request!/5 raises %HTTPoison.Error with weird reason
After upgrading to Elixir 1.10.3, a call to HTTPoison.request!() raised a HTTPoison.Error with id: nil and a reason of {:options, {:sslv3, {:versions, [:"tlsv1.2", :"tlsv1.1", :tlsv1, :sslv3]}}}. What could cause this? All examples I've seen online assume the reason is an atom.

答:
sslv3 was removed from Erlang 23.0 because it is an old and insecure protocol. You need to upgrade hackney to 1.16.0 or higher so that you can get this PR that fixes that issue:

https://github.com/benoitc/hackney/pull/619


问:
How to enable optional client certificate requests in GlassFish?
The Blog site (Client-Auth REQUESTED in GlassFish) reads:

```<code>In domain.xml, please add the following property to http-listener element
<property name="com.sun.grizzly.ssl.auth" value="want"/>
</code>```

However, when adding this to my GlassFish v3 domain.xml, the existing browser client certificate is not requested. The GlassFish server is properly set up, i.e., requires client certificates with the option "client-auth-enabled" set to true.

The GlassFish bugtracker (1) mentions a different version:

```<code> * client-auth: want/need/<blank>
</code>```

However, this property doesn't get accepted either.

Others have the same problem (2).

How can I enable an optional client certificate request in GlassFish? Are there alternatives?

(1) http://java.net/jira/browse/GLASSFISH-6935

(2) https://stackoverflow.com/questions/3634129/configure-glassfish-v3-client-auth-requested-to-want

答:
Probably because it doesn't exist.

*When you deal with client certificates in HTTPS, keep in mind your HTTPS listener configurations. The SSLv3/TLS protocol allows three modes for an HTTPS socket.

```<code>* The traditional mode requires a single server certificate. An HTTPS client (typically a web browser) validates the server identity by matching the certificate to a list, or truststore, of Certificate Authorities. You probably use this mode every day during typical log-in activity.

* Another mode requires both client and server certificates. The client certificate is validated by the server side, and the server certificate is validated by the client side.

* The third mode requires a server certificate, but the client certificate is optional.
</code>```

*In the real world, you want to use the same HTTPS URL whether a user is authenticated by password or certificate. This approach requires a server that supports the third, optional client certificate mode. At this writing, the GlassFish application server does not support this mode. Fortunately, the Apache Tomcat web server, supported by OpenSSO, is available as an alternative. For Reference

Body:
The Blog site (Client-Auth REQUESTED in GlassFish) reads:

In domain.xml, please add the following property to http-listener element
<property name="com.sun.grizzly.ssl.auth" value="want"/>

However, when adding this to my GlassFish v3 domain.xml, the existing browser client certificate is not requested. The GlassFish server is properly set up, i.e., requires client certificates with the option "client-auth-enabled" set to true.

The GlassFish bugtracker (1) mentions a different version:

 * client-auth: want/need/<blank>

However, this property doesn't get accepted either.

Others have the same problem (2).

How can I enable an optional client certificate request in GlassFish? Are there alternatives?

(1) http://java.net/jira/browse/GLASSFISH-6935

(2) https://stackoverflow.com/questions/3634129/configure-glassfish-v3-client-auth-requested-to-want

Body:
Probably because it doesn't exist.

*When you deal with client certificates in HTTPS, keep in mind your HTTPS listener configurations. The SSLv3/TLS protocol allows three modes for an HTTPS socket.

* The traditional mode requires a single server certificate. An HTTPS client (typically a web browser) validates the server identity by matching the certificate to a list, or truststore, of Certificate Authorities. You probably use this mode every day during typical log-in activity.

* Another mode requires both client and server certificates. The client certificate is validated by the server side, and the server certificate is validated by the client side.

* The third mode requires a server certificate, but the client certificate is optional.

*In the real world, you want to use the same HTTPS URL whether a user is authenticated by password or certificate. This approach requires a server that supports the third, optional client certificate mode. At this writing, the GlassFish application server does not support this mode. Fortunately, the Apache Tomcat web server, supported by OpenSSO, is available as an alternative. For Reference


问:
Per-pixel lookup-table
I was wondering if there was another way to create a per-pixel lookup table in Opencv. What I have now works okay for small resolutions (~4 frames per second) but slow on high resolutions (less than 1 frame per second).

I have read that I can use CUDA but do not know how to use it. If it is the only way can someone point me in the right direction? Thank you.

```<code>In header file:
    Mat_<Vec<uchar,256>> _GB;
    Mat_<Vec<uchar,256>> _GG;
    Mat_<Vec<uchar,256>> _GR;
…
Mat VideoProcessor::CamCalib(Mat _tempFrame)
{

    Mat_<Vec3b> _frame = _tempFrame;

    for( int i = 0; i < _tempFrame.rows; ++i)
        for( int j = 0; j < _tempFrame.cols; ++j )
        {
            _frame(i,j)[0] = _GB(i,j)[ _frame(i,j)[0] ];
            _frame(i,j)[1] = _GG(i,j)[ _frame(i,j)[1] ];
            _frame(i,j)[2] = _GR(i,j)[ _frame(i,j)[2] ];
        }

    _tempFrame = _frame;

    return _tempFrame;
}

</code>```

答:
Thanks Jerome, I followed your suggestion. A simple implementation with a 25% increase in performance. For me, since I am doing real-time image capture with software lens correction, memory is not as costly as speed.

So here is what I added:

added in Pro file:
QMAKE_CXXFLAGS += -openmp

added in CPP file:
#include "omp.h"
...
and added just before the "for loop" in method:
#pragma omp parallel for

Title: Per-pixel lookup-table

Body:
I was wondering if there was another way to create a per-pixel lookup table in Opencv. What I have now works okay for small resolutions (~4 frames per second) but slow on high resolutions (less than 1 frame per second).

I have read that I can use CUDA but do not know how to use it. If it is the only way can someone point me in the right direction? Thank you.

In header file:
    Mat_<Vec<uchar,256>> _GB;
    Mat_<Vec<uchar,256>> _GG;
    Mat_<Vec<uchar,256>> _GR;
…
Mat VideoProcessor::CamCalib(Mat _tempFrame)
{

    Mat_<Vec3b> _frame = _tempFrame;

    for( int i = 0; i < _tempFrame.rows; ++i)
        for( int j = 0; j < _tempFrame.cols; ++j )
        {
            _frame(i,j)[0] = _GB(i,j)[ _frame(i,j)[0] ];
            _frame(i,j)[1] = _GG(i,j)[ _frame(i,j)[1] ];
            _frame(i,j)[2] = _GR(i,j)[ _frame(i,j)[2] ];
        }

    _tempFrame = _frame;

    return _tempFrame;
}


问:
Add text to Froala text editor
I'm trying to programatically input html into Froala text editor. Based on their documentation this should work:

```<code>$(function(){
    $('#editor').editable("setHTML", "<p>My custom paragraph.</p>", false);
});
</code>```

But when I reload page I only get empty space, no errors. This is binded to textarea with id #editor. If I use this code:

```<code>$(function(){
    $('#editor').editable({inlineMode : false});
});
</code>```

... then everything is ok.

Does anyone knows how to programatically input html into this editor.

答:
With the latest version of Froala this works fine</p>

```<code>$("#froalaEditor")[0]["data-froala.editor"].html.set('This should work fine');
</code>```

Title: Add text to Froala text editor

Body:
I'm trying to programatically input html into Froala text editor. Based on their documentation this should work:

$(function(){
    $('#editor').editable("setHTML", "
My custom paragraph.
", false);
});

But when I reload page I only get empty space, no errors. This is binded to textarea with id #editor. If I use this code:

$(function(){
    $('#editor').editable({inlineMode : false});
});

... then everything is ok.

Does anyone knows how to programatically input html into this editor.

Body:
With the latest version of Froala this works fine

$("#froalaEditor")[0]["data-froala.editor"].html.set('This should work fine');


问:
print the current time for every 30 minutes in a file
I have tried this code to print the current time for every 30 minutes in a file and also if day changes print the next day time in the newfile and second day file name is incremental of first day file name.
But mistake of this code is it's not printing next days 30minutes increment time in new file created for that day.

```<code>set i 1
set c [open "$i.txt" w+]
set a [clock seconds]
set b [expr {$a+1800}]
set d [expr {$a+86400}]
while {$a > 0} {
    incr a
    if {$a == $b} {
        if { $a == $d} {
            incr i
            set e [open "$i.txt" w+]
            puts $e "The time is: [clock format $a -format %H:%M:%S]"
            set d [expr {$a+86400}]
        }
        puts $c "The time is: [clock format $a -format %H:%M:%S]"
        set b [expr {$a+1800}]
    }
}
</code>```

答:
You'll want to use the after command to pause for 30 minutes:

```<code>proc day {time} {
    clock format $time -format %e
}

proc write_time {} {
    global file_number prev_time

    set time [clock seconds]

    if {[day $time] != [day $prev_time]} {
        incr file_number
    }

    set fh [open "$file_number.txt" a]  ;# open for append
    puts $fh [clock format $time -format %T]
    close $fh

    # wait 30 minutes in milliseconds
    after 1800000 write_time
}

set file_number 1
set prev_time [clock seconds]

write_time
vwait forever
</code>```

Body:
I have tried this code to print the current time for every 30 minutes in a file and also if day changes print the next day time in the newfile and second day file name is incremental of first day file name.
But mistake of this code is it's not printing next days 30minutes increment time in new file created for that day.

set i 1
set c [open "$i.txt" w+]
set a [clock seconds]
set b [expr {$a+1800}]
set d [expr {$a+86400}]
while {$a > 0} {
    incr a
    if {$a == $b} {
        if { $a == $d} {
            incr i
            set e [open "$i.txt" w+]
            puts $e "The time is: [clock format $a -format %H:%M:%S]"
            set d [expr {$a+86400}]
        }
        puts $c "The time is: [clock format $a -format %H:%M:%S]"
        set b [expr {$a+1800}]
    }
}

Body:
You'll want to use the after command to pause for 30 minutes:

proc day {time} {
    clock format $time -format %e
}

proc write_time {} {
    global file_number prev_time

    set time [clock seconds]

    if {[day $time] != [day $prev_time]} {
        incr file_number
    }

    set fh [open "$file_number.txt" a]  ;# open for append
    puts $fh [clock format $time -format %T]
    close $fh

    # wait 30 minutes in milliseconds
    after 1800000 write_time
}

set file_number 1
set prev_time [clock seconds]

write_time
vwait forever


问:
Time aggregate across years in R
I have 10 years of daily precipitation data. I'm trying to get the total precipitation that occurs between, for exemple, december and april of the following year. Another complication is that the period can change, say Dec-15 to March-15

I know how to do this using aggregate or group_by if I don't have to go across years. But I'm completely out of ideas how to solve this year crossing problem.

Here is a code example of what I'm trying to get.

library(lubridate)

precip <- data.frame(d = seq.Date(from = as.Date('2001-01-01'),
                                  to = as.Date('2004-12-31'),
                                  by = 'day'),
                     prec = runif(1461))

precip$y <- year(precip$d)
precip$m <- month(precip$d)

# I can aggregate by year
aggregate(precip$prec, by = list(precip$y), sum)

# I can aggregate by year, month
aggregate(precip$prec, by = list(precip$y, precip$m), sum)

# How can I aggregate by a period that crosses between years?
# my desired output would be something like
# Group.1        x
# 1 2001-12-15 to 2002-03-15 184.4885
# 2 2002-12-15 to 2003-03-15 192.8315
# 3 2003-12-15 to 2004-03-15 178.8507
```

I don't need the group name to contain the period as a string. It could be just an index.

答:
The question was later updated to ask for seasons that are not whole months so this is an update to the original answer to address that.  It uses the input in the Note at the end and the start date and end date of a prototype season.  If the season spans the end of February be sure to choose a leap year (such as the year 2000 as shown in the example below).

We create a sequence of all dates from the start date to the end date called template.  Convert that to a character vector of all possible month/days in the season, mmdd.

Next define in_season which has one element per row of precip and is TRUE if the month and day of that row match any month and day in the template.

Then define season_no which has one element per row of precip identifying each season with a unique number.  The number is 0 for rows whose date is not in season and is otherwise an increasing positive number.

Subset the data to the in season rows and calculate the least and greatest date in each season giving precip0.

Finally aggregate prec by the start/end dates and also use aggregate to find how many days are in each of the seasons.  This will include partial seasons if they exist.  If this is not wanted subset the data first or subset the result as in the commented out line in the code.

No packages are used.

```<code># to change definition of season change next 2 lines
start_template <- as.Date("1999-12-15")
end_template <- as.Date("2000-03-15")  # note that year 2000 incl Feb 29

# mmdd character vector contains the mm-dd values in season
template <- seq(start_template, end_template, "day")
mmdd <- format(template, "%m-%d")

in_season <- format(precip$d, "%m-%d") %in% mmdd
season_no <- with(rle(in_season), rep(seq_along(lengths), lengths)) * in_season

precip0 <- transform(subset(cbind(precip, season_no), in_season),
  start_date = ave(d, season_no, FUN = min),
  end_date = ave(d, season_no, FUN = max))

ag <- aggregate(cbind(days = 1, prec) ~ start_date + end_date, precip0, sum)

# uncomment if partial seasons not wanted
# ag <- subset(ag, days >= length(mmdd) - 1)
</code>```

giving:

```<code>> ag
  start_date   end_date days      prec
2 2001-01-01 2001-03-15   74 37.963828
3 2001-12-15 2002-03-15   91 44.543114
4 2002-12-15 2003-03-15   91 43.182177
5 2003-12-15 2004-03-15   92 44.083236
1 2004-12-15 2004-12-31   17  9.180353
</code>```

Original answer assuming whole months

The inputs are precip (given in the Note at the end and season which is a vector of month numbers (Jan=1, Feb=2, ..., Dec=12) in order that they appear within the season.  In the example below we use c(12, 1:3), i.e. Dec - Mar.

The code below uses precip and season to set the following variables:

last_month is the month number of the last month in the season

ym is a yearmon class vector with corresponding year/months.  Internally it is represented as a year plus 0 for Jan, 1/12 for Feb, ..., 11/12 for Dec.  ym is the same length as x.

cross is a logical scalar that is TRUE if the season crosses a year boundary and otherwise FALSE

in_season is TRUE if the corresponding date is within the season.  in_season is the same length as x.

start_year and end_year are the corresponding years for the start and end of the season if the date is in season or 0 if not in season.  start_year and end_year are each the same length as x.

start_date and end_date are the corresponding season start and end dates

We then insert start_year and end_year and subset to those rows for which season is TRUE.  Finally we aggregate by start_year and end_year.

```<code>library(zoo)

# define season as Dec - Mar
season <- c(12, 1:3)  # month numbers in order they appear in season

last_month <- tail(season, 1)
ym <- as.yearmon(precip$d)
cross <- last_month < season[1]
in_season <- cycle(ym) %in% season

start_year <- as.integer(ym - cross * last_month / 12) * in_season
end_year <- start_year + cross * in_season

start_date <- as.Date(paste(start_year, season[1], 1, sep = "-"))
end_date <- as.Date(as.yearmon(paste(end_year, last_month, sep = "-")), frac = 1)

precip0 <- subset(data.frame(start_date, end_date, precip), in_season)
aggregate(prec ~ start_date + end_date, precip0, sum)
</code>```

giving:

```<code>  start_date   end_date     prec
1 2000-12-01 2001-03-31 45.70959
2 2001-12-01 2002-03-31 58.67224
3 2002-12-01 2003-03-31 57.93712
4 2003-12-01 2004-03-31 59.66424
5 2004-12-01 2005-03-31 16.69944
</code>```

or perhaps use start_year and end_year since then we can readily plot prec vs. end_year, say.

```<code>precip0 <- subset(data.frame(start_year, end_year, precip), in_season)
aggregate(prec ~ start_year + end_year, precip0, sum)
</code>```

Note

We assume that the input precip is the following.  This is the same as in the question except we have added set.seed to make it reproducible.

```<code>set.seed(123)
precip <- data.frame(d = seq.Date(from = as.Date('2001-01-01'),
                                  to = as.Date('2004-12-31'),
                                  by = 'day'),
                     prec = runif(1461))
</code>```

Title: Time aggregate across years in R

Body:
I have 10 years of daily precipitation data. I'm trying to get the total precipitation that occurs between, for exemple, december and april of the following year. Another complication is that the period can change, say Dec-15 to March-15

I know how to do this using aggregate or group_by if I don't have to go across years. But I'm completely out of ideas how to solve this year crossing problem.

Here is a code example of what I'm trying to get.

library(lubridate)

precip <- data.frame(d = seq.Date(from = as.Date('2001-01-01'),
                                  to = as.Date('2004-12-31'),
                                  by = 'day'),
                     prec = runif(1461))

precip$y <- year(precip$d)
precip$m <- month(precip$d)

# I can aggregate by year
aggregate(precip$prec, by = list(precip$y), sum)

# I can aggregate by year, month
aggregate(precip$prec, by = list(precip$y, precip$m), sum)

# How can I aggregate by a period that crosses between years?
# my desired output would be something like
# Group.1        x
# 1 2001-12-15 to 2002-03-15 184.4885
# 2 2002-12-15 to 2003-03-15 192.8315
# 3 2003-12-15 to 2004-03-15 178.8507

I don't need the group name to contain the period as a string. It could be just an index.

Body:
The question was later updated to ask for seasons that are not whole months so this is an update to the original answer to address that.  It uses the input in the Note at the end and the start date and end date of a prototype season.  If the season spans the end of February be sure to choose a leap year (such as the year 2000 as shown in the example below).

We create a sequence of all dates from the start date to the end date called template.  Convert that to a character vector of all possible month/days in the season, mmdd.

Next define in_season which has one element per row of precip and is TRUE if the month and day of that row match any month and day in the template.

Then define season_no which has one element per row of precip identifying each season with a unique number.  The number is 0 for rows whose date is not in season and is otherwise an increasing positive number.

Subset the data to the in season rows and calculate the least and greatest date in each season giving precip0.

Finally aggregate prec by the start/end dates and also use aggregate to find how many days are in each of the seasons.  This will include partial seasons if they exist.  If this is not wanted subset the data first or subset the result as in the commented out line in the code.

No packages are used.

# to change definition of season change next 2 lines
start_template <- as.Date("1999-12-15")
end_template <- as.Date("2000-03-15")  # note that year 2000 incl Feb 29

# mmdd character vector contains the mm-dd values in season
template <- seq(start_template, end_template, "day")
mmdd <- format(template, "%m-%d")

in_season <- format(precip$d, "%m-%d") %in% mmdd
season_no <- with(rle(in_season), rep(seq_along(lengths), lengths)) * in_season

precip0 <- transform(subset(cbind(precip, season_no), in_season),
  start_date = ave(d, season_no, FUN = min),
  end_date = ave(d, season_no, FUN = max))

ag <- aggregate(cbind(days = 1, prec) ~ start_date + end_date, precip0, sum)

# uncomment if partial seasons not wanted
# ag <- subset(ag, days >= length(mmdd) - 1)

giving:

> ag
  start_date   end_date days      prec
2 2001-01-01 2001-03-15   74 37.963828
3 2001-12-15 2002-03-15   91 44.543114
4 2002-12-15 2003-03-15   91 43.182177
5 2003-12-15 2004-03-15   92 44.083236
1 2004-12-15 2004-12-31   17  9.180353

Original answer assuming whole months

The inputs are precip (given in the Note at the end and season which is a vector of month numbers (Jan=1, Feb=2, ..., Dec=12) in order that they appear within the season.  In the example below we use c(12, 1:3), i.e. Dec - Mar.

The code below uses precip and season to set the following variables:

last_month is the month number of the last month in the season

ym is a yearmon class vector with corresponding year/months.  Internally it is represented as a year plus 0 for Jan, 1/12 for Feb, ..., 11/12 for Dec.  ym is the same length as x.

cross is a logical scalar that is TRUE if the season crosses a year boundary and otherwise FALSE

in_season is TRUE if the corresponding date is within the season.  in_season is the same length as x.

start_year and end_year are the corresponding years for the start and end of the season if the date is in season or 0 if not in season.  start_year and end_year are each the same length as x.

start_date and end_date are the corresponding season start and end dates

We then insert start_year and end_year and subset to those rows for which season is TRUE.  Finally we aggregate by start_year and end_year.

library(zoo)

# define season as Dec - Mar
season <- c(12, 1:3)  # month numbers in order they appear in season

last_month <- tail(season, 1)
ym <- as.yearmon(precip$d)
cross <- last_month < season[1]
in_season <- cycle(ym) %in% season

start_year <- as.integer(ym - cross * last_month / 12) * in_season
end_year <- start_year + cross * in_season

start_date <- as.Date(paste(start_year, season[1], 1, sep = "-"))
end_date <- as.Date(as.yearmon(paste(end_year, last_month, sep = "-")), frac = 1)

precip0 <- subset(data.frame(start_date, end_date, precip), in_season)
aggregate(prec ~ start_date + end_date, precip0, sum)

giving:

  start_date   end_date     prec
1 2000-12-01 2001-03-31 45.70959
2 2001-12-01 2002-03-31 58.67224
3 2002-12-01 2003-03-31 57.93712
4 2003-12-01 2004-03-31 59.66424
5 2004-12-01 2005-03-31 16.69944

or perhaps use start_year and end_year since then we can readily plot prec vs. end_year, say.

precip0 <- subset(data.frame(start_year, end_year, precip), in_season)
aggregate(prec ~ start_year + end_year, precip0, sum)

Note

We assume that the input precip is the following.  This is the same as in the question except we have added set.seed to make it reproducible.

set.seed(123)
precip <- data.frame(d = seq.Date(from = as.Date('2001-01-01'),
                                  to = as.Date('2004-12-31'),
                                  by = 'day'),
                     prec = runif(1461))


问:
how do I assign individual string to an element in one array of pointer?
I am new to C and still trying to figure out pointer.

So here is a task I am stuck in: I would like to assign 10 fruit names to a pointer of array and print them out one by one. Below is my code;

```<code>#include <stdio.h>
#include <string.h>

int main(){
    char *arr_of_ptrs[10];
    char buffer[20];
    int i;
    for (i=0;i<10;i++){
        printf("Please type in a fruit name:");
        fgets(buffer,20,stdin);
        arr_of_ptrs[i]= *buffer;
    }
    int j;
    for (j=0;j<10;j++){
        printf("%s",*(arr_of_ptrs+j));
    }

}
</code>```

However after execution this, it only shows me the last result for all 10 responses. I tried to consult similar questions others asked but no luck.

My understanding is that
1) pointer of array has been allocated memory with [10] so malloc() is not needed.

2) buffer stores the pointer to each individual answer therefore I dereference it and assign it to the arr_of_ptrs[i]
I am unsure if arr_of_ptrs[i] gets me a pointer or a value. I thought it is definitely a pointer but I deference it with * the code and assign it to *buffer, program would get stuck.

If someone could point out my problem that would be great.

Thanks in advance

答:
Three erros, 1. You must allocate memory for elements of elements of arr_of_ptrs, now you only allocate the memory for elements of arr_of_ptrs on stack memory. 2. arr_of_ptrs[i]= *buffer; means all of the arr_of_ptrs elements are pointed to same memory address, which is the "buffer" pointer. So all the elements of arr_of_ptrs will be same to the last stdin input string. 3. subsequent fgets() call has potential problem, one of the explaination could be here

A quick fix could be,

```<code>#include <stdio.h>
#include <string.h>

int main(){

    const int ARR_SIZE = 10, BUFFER_SIZE = 20;
    char arr_of_ptrs[ARR_SIZE][BUFFER_SIZE];
    char *pos;
    int i, c;

    for (i = 0; i < ARR_SIZE; ++i) {
        printf ("Please type in a fruit name: ");
        if (fgets (arr_of_ptrs[i], BUFFER_SIZE, stdin) == NULL) return -1;
        if ((pos = strchr(arr_of_ptrs[i], '\n')))
            *pos = 0;
        else
            while ((c = getchar()) != '\n' && c != EOF) {}
    }
    for (i = 0; i < ARR_SIZE; ++i)
        printf("%s\n", arr_of_ptrs[i]);

    return 0;
}
</code>```

Body:
I am new to C and still trying to figure out pointer.

So here is a task I am stuck in: I would like to assign 10 fruit names to a pointer of array and print them out one by one. Below is my code;

#include <stdio.h>
#include <string.h>

int main(){
    char *arr_of_ptrs[10];
    char buffer[20];
    int i;
    for (i=0;i<10;i++){
        printf("Please type in a fruit name:");
        fgets(buffer,20,stdin);
        arr_of_ptrs[i]= *buffer;
    }
    int j;
    for (j=0;j<10;j++){
        printf("%s",*(arr_of_ptrs+j));
    }

}

However after execution this, it only shows me the last result for all 10 responses. I tried to consult similar questions others asked but no luck.

My understanding is that
1) pointer of array has been allocated memory with [10] so malloc() is not needed.

2) buffer stores the pointer to each individual answer therefore I dereference it and assign it to the arr_of_ptrs[i]
I am unsure if arr_of_ptrs[i] gets me a pointer or a value. I thought it is definitely a pointer but I deference it with * the code and assign it to *buffer, program would get stuck.

If someone could point out my problem that would be great.

Thanks in advance

Body:
Three erros, 1. You must allocate memory for elements of elements of arr_of_ptrs, now you only allocate the memory for elements of arr_of_ptrs on stack memory. 2. arr_of_ptrs[i]= *buffer; means all of the arr_of_ptrs elements are pointed to same memory address, which is the "buffer" pointer. So all the elements of arr_of_ptrs will be same to the last stdin input string. 3. subsequent fgets() call has potential problem, one of the explaination could be here

A quick fix could be,

#include <stdio.h>
#include <string.h>

int main(){

    const int ARR_SIZE = 10, BUFFER_SIZE = 20;
    char arr_of_ptrs[ARR_SIZE][BUFFER_SIZE];
    char *pos;
    int i, c;

    for (i = 0; i < ARR_SIZE; ++i) {
        printf ("Please type in a fruit name: ");
        if (fgets (arr_of_ptrs[i], BUFFER_SIZE, stdin) == NULL) return -1;
        if ((pos = strchr(arr_of_ptrs[i], '\n')))
            *pos = 0;
        else
            while ((c = getchar()) != '\n' && c != EOF) {}
    }
    for (i = 0; i < ARR_SIZE; ++i)
        printf("%s\n", arr_of_ptrs[i]);

    return 0;
}


问:
Firebase REST API auth not working with React?
Basically a friend and I have been working on our React project and we're using Redux and Redux Thunk on the backend to handle authentication. However, we seem to have ran into an issue. Our request was working before, but now it issues a Fetch Failed Loading: POST, and doesn't continue past the initial call. However, when checking Firebase, it returns the correctly created user. I know it doesn't go past the fetch because the console.log doesn't work at all.</p>

```<code>export const signup = (email, password) => {

return async dispatch => {
    const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API-KEY]',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: email,
            password: password,
            returnSecureToken: true
        })
    }
    );

    console.log(response);
</code>```

答:
If async is used,
it is recommended to use try{do await something...}catch(e){} format to write.

```<code>try{
    do await something
 }catch(e){
    error something
}
</code>```

Easy to catch errors

Body:
Basically a friend and I have been working on our React project and we're using Redux and Redux Thunk on the backend to handle authentication. However, we seem to have ran into an issue. Our request was working before, but now it issues a Fetch Failed Loading: POST, and doesn't continue past the initial call. However, when checking Firebase, it returns the correctly created user. I know it doesn't go past the fetch because the console.log doesn't work at all.

export const signup = (email, password) => {

return async dispatch => {
    const response = await fetch('https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API-KEY]',
    {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email: email,
            password: password,
            returnSecureToken: true
        })
    }
    );

    console.log(response);

Body:
If async is used,
it is recommended to use try{do await something...}catch(e){} format to write.

try{
    do await something
 }catch(e){
    error something
}

Easy to catch errors


问:
Calculating follower growth over time for each influencer
I have a table with influencers and their follower counter for each day:

```<code>influencer_id |     date     |    followers
     1        | 2020-05-29   |      7361
     1        | 2020-05-28   |      7234
                    ...
     2        | 2020-05-29   |       82
     2        | 2020-05-28   |       85
                    ...
     3        | 2020-05-29   |      3434
     3        | 2020-05-28   |      2988
     3        | 2020-05-27   |      2765
                    ...
</code>```

Let's say I want to calculate how many followers each individual influencer has gained in the last 7 days and get the following table:

```<code>influencer_id |                       growth
     1        |  <num followers last day - num followers first day>
     2        |                         "
     3        |                         "
</code>```

As a first attempt I did this:

```<code>SELECT influencer_id,
      (MAX(followers) - MIN(followers)) AS growth
FROM influencer_follower_daily
WHERE date < '2020-05-30'
AND date >= '2020-05-23'
GROUP BY influencer_id;
</code>```

This works and shows the growth over the week for each influencer. But it assumes the follower count always increases and people never unfollow!

So is there a way to achieve what I want using an SQL query over the original table? Or will I have to generate a completely new table using a FOR loop that calculates a +/- follower change column between each date?

答:
The simple aggregate functions first() and last() are not implemented in standard Postgres. But see below.

1. array_agg()

Gordon demonstrated a query with array_agg(), but that's more expensive than necessary, especially with many rows per group. Even more so when called twice, and with ORDER BY per aggregate. This equivalent alternative should be substantially faster:

```<code>SELECT influencer_id, arr[array_upper(arr, 1)] - arr[1]
FROM  (
   SELECT influencer_id, array_agg(followers) AS arr
   FROM  (
      SELECT influencer_id, followers
      FROM   influencer_follower_daily
      WHERE  date >= '2020-05-23'
      AND    date <  '2020-05-30'
      ORDER  BY influencer_id, date
      ) sub1
   GROUP  BY influencer_id
   ) sub2;
</code>```

Because it sorts once and aggregates once. The sort order of the inner subquery sub1 is carried over to the next level. See:

How to apply ORDER BY and LIMIT in combination with an aggregate function?

Indexes matter:

If you query the whole table or most of it, an index on (influencer_id, date, followers) can help (a lot) with index-only scans.

If you query only a small fragment of the table, an index on (date) or (date, influencer_id, followers) can help (a lot).

2. DISTINCT & window functions

Gordon also demonstrated DISTINCT with window functions. Again, can be substantially faster:

```<code>SELECT DISTINCT ON (influencer_id)
       influencer_id
     , last_value(followers) OVER (PARTITION BY influencer_id ORDER BY date
                                   ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
     - followers AS growth
FROM   influencer_follower_daily
WHERE  date >= '2020-05-23'
AND    date <  '2020-05-30'
ORDER  BY influencer_id, date;
</code>```

With a single window function, using the same sort order (!) as the main query. To achieve this, we need the non-default window definition with ROWS BETWEEN ... See:

PostgreSQL query with max and min date plus associated id per row

And DISTINCT ON instead of DISTINCT. See:

Select first row in each GROUP BY group?

3. Custom aggregate functions

first() and last()

You can add those yourself, it's pretty simple. See instructions in the Postgres Wiki.

Or install the additional module first_last_agg with a faster implementation in C.

Related:

Use something like TOP with GROUP BY

Then your query becomes simpler:

```<code>SELECT influencer_id, last(followers) - first(followers) AS growth
FROM  (
   SELECT influencer_id, followers
   FROM   influencer_follower_daily
   WHERE  date >= '2020-03-02'
   AND    date <  '2020-05-09'
   ORDER  BY influencer_id, date
   ) z
GROUP  BY influencer_id
ORDER  BY influencer_id;
</code>```

Custom aggregate growth()

You can combine first() and last() in a single aggregate function. That's faster, but calling two C functions will still outperform one custom SQL function.

Basically encapsulates the logic of my first query in a custom aggregate:

```<code>CREATE OR REPLACE FUNCTION f_growth(anyarray)
  RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE AS
'SELECT $1[array_upper($1, 1)] - $1[1]';

CREATE OR REPLACE AGGREGATE growth(anyelement) (
   SFUNC     = array_append
 , STYPE     = anyarray
 , FINALFUNC = f_growth
 , PARALLEL  = SAFE
);
</code>```

Works for any numeric type (or any type with an operator type - type returning the same type). The query is simpler, yet:

```<code>SELECT influencer_id, growth(followers)
FROM  (
   SELECT influencer_id, followers
   FROM   influencer_follower_daily
   WHERE  date >= '2020-05-23'
   AND    date <  '2020-05-30'
   ORDER  BY influencer_id, date
   ) z
GROUP  BY influencer_id
ORDER  BY influencer_id;
</code>```

Or a little slower, but ultimately short:

```<code>SELECT influencer_id, growth(followers ORDER BY date)
FROM   influencer_follower_daily
WHERE  date >= '2020-05-23'
AND    date <  '2020-05-30'
GROUP  BY 1
ORDER  BY 1;
</code>```

db<>fiddle here

4. Performance optimization for many rows per group

With many rows per group / partition, other query techniques can be (a lot) faster. Techniques along these lines:

Optimize GROUP BY query to retrieve latest row per user

If that applies, I suggest you start a new question disclosing exact table definition(s) and cardinalities ...

Closely related:

Get values from first and last row per group

PostgreSQL: joining arrays within group by clause

Use something like TOP with GROUP BY

Best performance in sampling repeated value from a grouped column

Body:
I have a table with influencers and their follower counter for each day:

influencer_id |     date     |    followers
     1        | 2020-05-29   |      7361
     1        | 2020-05-28   |      7234
                    ...
     2        | 2020-05-29   |       82
     2        | 2020-05-28   |       85
                    ...
     3        | 2020-05-29   |      3434
     3        | 2020-05-28   |      2988
     3        | 2020-05-27   |      2765
                    ...

Let's say I want to calculate how many followers each individual influencer has gained in the last 7 days and get the following table:

influencer_id |                       growth
     1        |  <num followers last day - num followers first day>
     2        |                         "
     3        |                         "

As a first attempt I did this:

SELECT influencer_id,
      (MAX(followers) - MIN(followers)) AS growth
FROM influencer_follower_daily
WHERE date < '2020-05-30'
AND date >= '2020-05-23'
GROUP BY influencer_id;

This works and shows the growth over the week for each influencer. But it assumes the follower count always increases and people never unfollow!

So is there a way to achieve what I want using an SQL query over the original table? Or will I have to generate a completely new table using a FOR loop that calculates a +/- follower change column between each date?

Body:
The simple aggregate functions first() and last() are not implemented in standard Postgres. But see below.

1. array_agg()

Gordon demonstrated a query with array_agg(), but that's more expensive than necessary, especially with many rows per group. Even more so when called twice, and with ORDER BY per aggregate. This equivalent alternative should be substantially faster:

SELECT influencer_id, arr[array_upper(arr, 1)] - arr[1]
FROM  (
   SELECT influencer_id, array_agg(followers) AS arr
   FROM  (
      SELECT influencer_id, followers
      FROM   influencer_follower_daily
      WHERE  date >= '2020-05-23'
      AND    date <  '2020-05-30'
      ORDER  BY influencer_id, date
      ) sub1
   GROUP  BY influencer_id
   ) sub2;

Because it sorts once and aggregates once. The sort order of the inner subquery sub1 is carried over to the next level. See:

How to apply ORDER BY and LIMIT in combination with an aggregate function?

Indexes matter:

If you query the whole table or most of it, an index on (influencer_id, date, followers) can help (a lot) with index-only scans.

If you query only a small fragment of the table, an index on (date) or (date, influencer_id, followers) can help (a lot).

2. DISTINCT & window functions

Gordon also demonstrated DISTINCT with window functions. Again, can be substantially faster:

SELECT DISTINCT ON (influencer_id)
       influencer_id
     , last_value(followers) OVER (PARTITION BY influencer_id ORDER BY date
                                   ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
     - followers AS growth
FROM   influencer_follower_daily
WHERE  date >= '2020-05-23'
AND    date <  '2020-05-30'
ORDER  BY influencer_id, date;

With a single window function, using the same sort order (!) as the main query. To achieve this, we need the non-default window definition with ROWS BETWEEN ... See:

PostgreSQL query with max and min date plus associated id per row

And DISTINCT ON instead of DISTINCT. See:

Select first row in each GROUP BY group?

3. Custom aggregate functions

first() and last()

You can add those yourself, it's pretty simple. See instructions in the Postgres Wiki.

Or install the additional module first_last_agg with a faster implementation in C.

Related:

Use something like TOP with GROUP BY

Then your query becomes simpler:

SELECT influencer_id, last(followers) - first(followers) AS growth
FROM  (
   SELECT influencer_id, followers
   FROM   influencer_follower_daily
   WHERE  date >= '2020-03-02'
   AND    date <  '2020-05-09'
   ORDER  BY influencer_id, date
   ) z
GROUP  BY influencer_id
ORDER  BY influencer_id;

Custom aggregate growth()

You can combine first() and last() in a single aggregate function. That's faster, but calling two C functions will still outperform one custom SQL function.

Basically encapsulates the logic of my first query in a custom aggregate:

CREATE OR REPLACE FUNCTION f_growth(anyarray)
  RETURNS anyelement LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE AS
'SELECT $1[array_upper($1, 1)] - $1[1]';

CREATE OR REPLACE AGGREGATE growth(anyelement) (
   SFUNC     = array_append
 , STYPE     = anyarray
 , FINALFUNC = f_growth
 , PARALLEL  = SAFE
);

Works for any numeric type (or any type with an operator type - type returning the same type). The query is simpler, yet:

SELECT influencer_id, growth(followers)
FROM  (
   SELECT influencer_id, followers
   FROM   influencer_follower_daily
   WHERE  date >= '2020-05-23'
   AND    date <  '2020-05-30'
   ORDER  BY influencer_id, date
   ) z
GROUP  BY influencer_id
ORDER  BY influencer_id;

Or a little slower, but ultimately short:

SELECT influencer_id, growth(followers ORDER BY date)
FROM   influencer_follower_daily
WHERE  date >= '2020-05-23'
AND    date <  '2020-05-30'
GROUP  BY 1
ORDER  BY 1;

db<>fiddle here

4. Performance optimization for many rows per group

With many rows per group / partition, other query techniques can be (a lot) faster. Techniques along these lines:

Optimize GROUP BY query to retrieve latest row per user

If that applies, I suggest you start a new question disclosing exact table definition(s) and cardinalities ...

Closely related:

Get values from first and last row per group

PostgreSQL: joining arrays within group by clause

Use something like TOP with GROUP BY

Best performance in sampling repeated value from a grouped column


问:
pdf 1.8.1 Flutter - Unable to display the document
I was trying to use PDF library for Flutter using the package here

the idea is to create something like this:  which is the example in the package's page.

the problem is that if I run the Demo example there, it works exactly as the example, which is fine.

demo example

But if I create a new project and COPY/PASTE all *.dart files and pubspec.yaml : it doesn't work. The script creates the file, I can downloading it or print it as well, but doesn't show the file.

I'm not using project with more information, I'm just copying the same code to a clean project and I'm also getting packages in pubspec.yaml

did someone has the same problem? I will post an image below.

in addition: I'M RUNNING BOTH PROJECTS AS FLUTTER WEB, IN CHROME

thank you for your help!! :)

below a 'hello world' code that showed me the same error..

```<code>import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter/material.dart';
import 'package:printing/printing.dart';
import 'dart:typed_data';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final pw.Document doc = pw.Document();

  @override
  Widget build(BuildContext context) {
    Future<Uint8List> generateDocument(PdfPageFormat format) async {
      doc.addPage(pw.Page(
          pageFormat: PdfPageFormat.standard,
          build: (pw.Context context) {
            return pw.Center(
              child: pw.Text("Hello World"),
            ); // Center
          })); // Page
      return doc.save();
    }

    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: PdfPreview(
          maxPageWidth: 700,
          build: generateDocument,
        ),
      ),
    );
  }
}
</code>```

答:
did you add the javascript code?
you should add the code in the index.html.

for example)
like this,

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="Rakuraku Flutter.">

  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="rakuraku">
  <link rel="apple-touch-icon" href="/icons/Icon-192.png">

  <link rel="shortcut icon" type="image/png" href="/favicon.png"/>

  <title>rakuraku</title>
  <link rel="manifest" href="/manifest.json">

```

Body:
I was trying to use PDF library for Flutter using the package here

the idea is to create something like this:  which is the example in the package's page.

the problem is that if I run the Demo example there, it works exactly as the example, which is fine.

demo example

But if I create a new project and COPY/PASTE all *.dart files and pubspec.yaml : it doesn't work. The script creates the file, I can downloading it or print it as well, but doesn't show the file.

I'm not using project with more information, I'm just copying the same code to a clean project and I'm also getting packages in pubspec.yaml

did someone has the same problem? I will post an image below.

in addition: I'M RUNNING BOTH PROJECTS AS FLUTTER WEB, IN CHROME

thank you for your help!! :)

below a 'hello world' code that showed me the same error..

import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter/material.dart';
import 'package:printing/printing.dart';
import 'dart:typed_data';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final pw.Document doc = pw.Document();

  @override
  Widget build(BuildContext context) {
    Future<Uint8List> generateDocument(PdfPageFormat format) async {
      doc.addPage(pw.Page(
          pageFormat: PdfPageFormat.standard,
          build: (pw.Context context) {
            return pw.Center(
              child: pw.Text("Hello World"),
            ); // Center
          })); // Page
      return doc.save();
    }

    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Material App Bar'),
        ),
        body: PdfPreview(
          maxPageWidth: 700,
          build: generateDocument,
        ),
      ),
    );
  }
}

Body:
did you add the javascript code?
you should add the code in the index.html.

for example)
like this,

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="Rakuraku Flutter.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="rakuraku">
  <link rel="apple-touch-icon" href="/icons/Icon-192.png">

  <!-- Favicon -->
  <link rel="shortcut icon" type="image/png" href="/favicon.png"/>

  <title>rakuraku</title>
  <link rel="manifest" href="/manifest.json">
</head>
<body id="flutter">
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
  <script>
    if ('serviceWorker' in navigator) {
      window.addEventListener('load', function () {
        navigator.serviceWorker.register('/flutter_service_worker.js');
      });
    }
  </script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.4.456/pdf.min.js"></script>
  <script type="text/javascript">
     pdfjsLib.GlobalWorkerOptions.workerSrc = "//cdnjs.cloudflare.com/ajax/libs/pdf.js/2.4.456/pdf.worker.min.js";
  </script>
  <script src="main.dart.js" type="application/javascript"></script>
</body>
</html>


问:
Dart: hard to understand anonymous functions
I am a very newbie in Dart and have big trouble to understand the "shortcut" of Dart code.
One of them is the "(...) {...}".
Could you take a look at the attached screenshot and help me to understand what are the "(..)" in blue and red rectangles?
Thank you!

child: Switch(
  value: isSwitched,
  onChanged: (value) {
    setState(() {
      isSwitched = value;
      print(isSwitched);
    });
  },
  activeTrackColor: Colors.lightGreenAccent,
  activeColor: Colors.green,
),
```

答:
These functions are called anonymous functions.

The onChange function took a function as an argument. And run that function with an argument it already has.

void fn(value) {
  // setState code
}
// which you can use as
onChanged: fn,
```

<p>But declaring a new function just to use at that one place can be tiresome and inefficient. That's why anonymous functions are useful. So you can write the previous code with anonymous functions as</p>

<pre class="lang-dart prettyprint-override"><code>onChanged: () { // the same as function fn but with no name or declaration
  // setState code
}
</code>```

The same goes for setState function. But it takes a function with no arguments.

Body:
These functions are called anonymous functions.

The onChange function took a function as an argument. And run that function with an argument it already has.

void fn(value) {
  // setState code
}
// which you can use as
onChanged: fn,

But declaring a new function just to use at that one place can be tiresome and inefficient. That's why anonymous functions are useful. So you can write the previous code with anonymous functions as

onChanged: () { // the same as function fn but with no name or declaration
  // setState code
}

The same goes for setState function. But it takes a function with no arguments.


答:
I think your input data is numbers[n] where n = 9.

Simple instructions

The last part of algorithm:

if (count == 2) {
    printf("Yes\n");
} else {
    printf("No\n");
}
return 0;
```

<p>This code is <code>O(1)</code>, <code>printf</code>, <code>if-else</code>, <code>return</code> aren't scale with <code>numbers</code>.</p>

<p>These lines (were taken out of context) have <code>O(1)</code> for the same reason.</p>

```int numbers[9] = {1, 5, 7, 8, 9, 14, 21};
int check = 50;

int count = 0;
```

```int squared = numbers[i]*numbers[i];
    int target = check - squared;
```

```if (numbers[j]*numbers[j] == target) {
    count++;
}
```

<p>Everything that doesn't scale with input data has <code>O(1)</code>.</p>

<h1>Loops make complexity</h1>

<pre class="lang-cpp prettyprint-override"><code>for (int i = 0; i < n; i++) {
    // task
}
</code>```

Common loop runs task n times and it means that the complexity of this loop is O(N) * complexity(task).

In your algorithm are nested loops and it means.

int k = n;
for (int i = 0; i < n; i++) {
    for (int j = i; j < k; j++) // task
        O(1);
}
```

Task's complexity is O(k * 1) = O(k) = O(n).

Loop's complexity is O(n * complexity(task)) = O(n * k) = O (n^2)

Title: What is the time complexity of this code, and could you explain how you calculated it?

Body:
The code below I found the time complexity to be n^2 if that is correct?

int numbers[9] = {1, 5, 7, 8, 9, 14, 21};
int check = 50;

int count = 0;
for (int i = 0; i < 9; i++) {
    int squared = numbers[i]*numbers[i];
    int target = check - squared;
    for (int j = i; j < 9; j++) {
        if (numbers[j]*numbers[j] == target) {
            count++;
        }
    }
}
if (count == 2) {
    printf("Yes\n");
} else {
    printf("No\n");
}
return 0;

Body:
I think your input data is numbers[n] where n = 9.

Simple instructions

The last part of algorithm:

if (count == 2) {
    printf("Yes\n");
} else {
    printf("No\n");
}
return 0;

This code is O(1), printf, if-else, return aren't scale with numbers.

These lines (were taken out of context) have O(1) for the same reason.

int numbers[9] = {1, 5, 7, 8, 9, 14, 21};
int check = 50;

int count = 0;

int squared = numbers[i]*numbers[i];
    int target = check - squared;

if (numbers[j]*numbers[j] == target) {
    count++;
}

Everything that doesn't scale with input data has O(1).

Loops make complexity

for (int i = 0; i < n; i++) {
    // task
}

Common loop runs task n times and it means that the complexity of this loop is O(N) * complexity(task).

In your algorithm are nested loops and it means.

int k = n;
for (int i = 0; i < n; i++) {
    for (int j = i; j < k; j++) // task
        O(1);
}

Task's complexity is O(k * 1) = O(k) = O(n).

Loop's complexity is O(n * complexity(task)) = O(n * k) = O (n^2)


问:
How do I run a terminal inside of Vim?
I am used to Emacs, but I am trying out Vim to see which one I like better.

One thing that I like about Emacs is the ability to run a terminal inside Emacs. Is this possible inside of Vim? I know that you can execute commands from Vim, but I would like to be able to run a terminal inside of a tab.

答:
Split the screen and run command term ++curwin to run the terminal inside the Vim buffer. Following command does both and worked for me:

```<code>:bo 10sp | term ++curwin
</code>```

Title: How do I run a terminal inside of Vim?

Body:
Split the screen and run command term ++curwin to run the terminal inside the Vim buffer. Following command does both and worked for me:

:bo 10sp | term ++curwin


问:
How can I combine three inputs into one variable and use it to fetch data from a database using Django?
I am working on my first Django project and learning a lot along the way. So far, I have set up a very simple website and am having trouble with the next steps. Through this project, I am hoping to achieve a website that provides users with reliable resources based on how they answer the three questions they are asked.

Website Explanation: The user opens the website and is prompted to click a button to go to the first step. The first step asks the user to choose the subject they would like a resource on (for now, all of the listed subjects are related to cooking). Then, they choose their level of expertise (beginner, intermediate, advanced). Finally, they choose a preferred medium for their resource (article/blog, video, book). Based on the subject, their level of expertise, and their preferred medium, the last page will give the user a resource that is retrieved from a linked database.

Where I Am Stuck: So far, I have created five pages (home page, one page for each question, and a results page) and have set up the choices for each question. Now, I am having trouble finding a way to combine the user's three answers into one variable, which I will use to fetch data from a connected database and display the respective resources.

For reference, I have included code from my "views.py" file and "Subject Page" file (this page is Step 1 of the process where the user chooses a subject. The format for the other two questions is very similar to this one, which is why I only included the code for this page). If you are willing to help, please feel free to request any other references I may be able to provide. Also, though I am not yet at that step, I'm open to guidance on connecting my website to a database. As always, any help/guidance would be much appreciated! Thank you :)

views.py code:

```<code>from django.shortcuts import render
from django.http import HttpResponse

def HomePage(request):
    return render(request, 'ResourceApp/HomePage.html')

def SubjectPage(request):
    return render(request, 'ResourceApp/SubjectPage.html')

def LevelPage(request):
    return render(request, 'ResourceApp/LevelPage.html')

def MediumPage(request):
    return render(request, 'ResourceApp/MediumPage.html')

def ResultsPage(request):
    return render(request, 'ResourceApp/ResultsPage.html')
</code>```

Subject Page code:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Subject | Tools For Fools</title>
</head>
<body>

<h1> Step 1 </h1>
<form action="http://127.0.0.1:8000/level/">
  <label for="Subject">Choose a Subject:</label>
  <select id="Subject" name="Subject">
    <option value="Knife Skills">Knife Skills</option>
    <option value="Culinary Terms">Culinary Terms</option>
    <option value="Recipes">Recipes</option>
  </select>
  <input type="Submit">
</form>

</body>
</html>
</code>```

Error

views.py file urls.py file
Cookies

答:
In your urls.py include:

```<code>urlpatterns = [
   path('level/',views.LevelPage,name='levelpage'),
   path('medium/',views.MediumPage,name='mediumpage'),
   path('results/',views.ResultsPage,name='rpage'),

]
</code>```

change your views.py to:

```<code>from django.shortcuts import render
from django.http import HttpResponse

def HomePage(request):
    return render(request, 'ResourceApp/HomePage.html')

def SubjectPage(request):
    return render(request, 'ResourceApp/SubjectPage.html')
def LevelPage(request):
    subject = request.GET.get('Subject')
    response = render(request, 'ResourceApp/LevelPage.html')
    response.set_cookie('subject',subject)
    return  response

def MediumPage(request):
    level = request.GET.get('level')
    response = render(request, 'ResourceApp/MediumPage.html')
    response.set_cookie('level',level)
    return  response

def ResultsPage(request):
    medium = request.GET.get('medium')
    results = request.COOKIES.get('subject') + request.COOKIES.get('level') + request.COOKIES.get('medium')
    return render(request, 'ResourceApp/ResultsPage.html')
</code>```

Body:
I am working on my first Django project and learning a lot along the way. So far, I have set up a very simple website and am having trouble with the next steps. Through this project, I am hoping to achieve a website that provides users with reliable resources based on how they answer the three questions they are asked.

Website Explanation: The user opens the website and is prompted to click a button to go to the first step. The first step asks the user to choose the subject they would like a resource on (for now, all of the listed subjects are related to cooking). Then, they choose their level of expertise (beginner, intermediate, advanced). Finally, they choose a preferred medium for their resource (article/blog, video, book). Based on the subject, their level of expertise, and their preferred medium, the last page will give the user a resource that is retrieved from a linked database.

Where I Am Stuck: So far, I have created five pages (home page, one page for each question, and a results page) and have set up the choices for each question. Now, I am having trouble finding a way to combine the user's three answers into one variable, which I will use to fetch data from a connected database and display the respective resources.

For reference, I have included code from my "views.py" file and "Subject Page" file (this page is Step 1 of the process where the user chooses a subject. The format for the other two questions is very similar to this one, which is why I only included the code for this page). If you are willing to help, please feel free to request any other references I may be able to provide. Also, though I am not yet at that step, I'm open to guidance on connecting my website to a database. As always, any help/guidance would be much appreciated! Thank you :)

views.py code:

from django.shortcuts import render
from django.http import HttpResponse

def HomePage(request):
    return render(request, 'ResourceApp/HomePage.html')

def SubjectPage(request):
    return render(request, 'ResourceApp/SubjectPage.html')

def LevelPage(request):
    return render(request, 'ResourceApp/LevelPage.html')

def MediumPage(request):
    return render(request, 'ResourceApp/MediumPage.html')

def ResultsPage(request):
    return render(request, 'ResourceApp/ResultsPage.html')

Subject Page code:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Subject | Tools For Fools</title>

 Step 1

<form action="http://127.0.0.1:8000/level/">
  Choose a Subject:
  <select id="Subject" name="Subject">
    <option value="Knife Skills">Knife Skills</option>
    <option value="Culinary Terms">Culinary Terms</option>
    <option value="Recipes">Recipes</option>
  </select>
  <input type="Submit">
</form>

Error

views.py file urls.py file
Cookies

Body:
In your urls.py include:

urlpatterns = [
   path('level/',views.LevelPage,name='levelpage'),
   path('medium/',views.MediumPage,name='mediumpage'),
   path('results/',views.ResultsPage,name='rpage'),

]

change your views.py to:

from django.shortcuts import render
from django.http import HttpResponse

def HomePage(request):
    return render(request, 'ResourceApp/HomePage.html')

def SubjectPage(request):
    return render(request, 'ResourceApp/SubjectPage.html')
def LevelPage(request):
    subject = request.GET.get('Subject')
    response = render(request, 'ResourceApp/LevelPage.html')
    response.set_cookie('subject',subject)
    return  response

def MediumPage(request):
    level = request.GET.get('level')
    response = render(request, 'ResourceApp/MediumPage.html')
    response.set_cookie('level',level)
    return  response

def ResultsPage(request):
    medium = request.GET.get('medium')
    results = request.COOKIES.get('subject') + request.COOKIES.get('level') + request.COOKIES.get('medium')
    return render(request, 'ResourceApp/ResultsPage.html')


问:
What is the time complexity of this code, and could you explain how you calculated it?
The code below I found the time complexity to be n^2 if that is correct?</p>

```<code>int numbers[9] = {1, 5, 7, 8, 9, 14, 21};
int check = 50;

int count = 0;
for (int i = 0; i < 9; i++) {
    int squared = numbers[i]*numbers[i];
    int target = check - squared;
    for (int j = i; j < 9; j++) {
        if (numbers[j]*numbers[j] == target) {
            count++;
        }
    }
}
if (count == 2) {
    printf("Yes\n");
} else {
    printf("No\n");
}
return 0;
</code>```

答:
It can be understood in such a way:

Change the 9 into int n = 9;, and

```<code>for i = 0,   inner loop 0, 1, 2, ...., n - 1
for i = 1,   inner loop    1, 2, ...., n - 1
for i = 2,   inner loop       2, ...., n - 1
......
for i = n-1, inner loop                n - 1
</code>```

So all of operation takes about n * n / 2 = O(n^2)

The Big O notation might be helpful.

Body:
It can be understood in such a way:

Change the 9 into int n = 9;, and

for i = 0,   inner loop 0, 1, 2, ...., n - 1
for i = 1,   inner loop    1, 2, ...., n - 1
for i = 2,   inner loop       2, ...., n - 1
......
for i = n-1, inner loop                n - 1

So all of operation takes about n * n / 2 = O(n^2)

The Big O notation might be helpful.


问:
How to ignore everything after the first character input
I would like to get rid of everything after the first char of a user input.

Everything is working fine, but I'm handling edge cases and if a user types something for example 'nfff' it would cause two functions to occur, when 'n' is entered as an input and when 'f' is entered as an input. I am aware that this can be solved using if (str[0] == 'n') { function() }, but I'd rather not use more memory with string.

Is there a more efficient way to discard everything after the first character?

答:
```<code>#include <iostream>     // std::cin, std::cout
#include <fstream>      // std::ifstream

int main () {
  char str[2];

  std::cout << "Enter str ";
  std::cin.get (str,2);    // get c-string
  std::cout <<str<<std::endl;

  return 0;
}
</code>```

Use istream::get to do the trick! Size of 2 will make sure that str is null terminated.

Body:
#include <iostream>     // std::cin, std::cout
#include <fstream>      // std::ifstream

int main () {
  char str[2];

  std::cout << "Enter str ";
  std::cin.get (str,2);    // get c-string
  std::cout <<str<<std::endl;

  return 0;
}

Use istream::get to do the trick! Size of 2 will make sure that str is null terminated.