问:
Devise scoped member routes issue
I'm using devise for sign up and ActiveStorage for image upload. For the delete/purge function to work I have this route

```<code>  devise_scope :user do
    scope module: :users do
      resources :registrations do
        member do
          delete :delete_image_attachment
        end
      end
    end
  end
</code>```

But another place in my routes file I have this route

```<code>  devise_for :users, controllers: {:registrations => "users/registrations"
  }
</code>```

It makes some of my pages not working. I have read somewhere that it's because registrations are declared two times. How can I make it work?
Any help would be much appreciated

答: If you use resources :registrations, only: [] do... that will create the parent route that you need without overwriting any of the routes provided by devise. Allowing you to make your nested routes :D

Title: Devise scoped member routes issue

Body:
I'm using devise for sign up and ActiveStorage for image upload. For the delete/purge function to work I have this route

  devise_scope :user do
    scope module: :users do
      resources :registrations do
        member do
          delete :delete_image_attachment
        end
      end
    end
  end

But another place in my routes file I have this route

  devise_for :users, controllers: {:registrations => "users/registrations"
  }

It makes some of my pages not working. I have read somewhere that it's because registrations are declared two times. How can I make it work?
Any help would be much appreciated


来源: stackexchange

问:
Run two scripts simultaneously in tkinter
I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish.
Here's the code:</p>

```<code>import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")

def clicked():
     os.system('python inference.py')
     os.system('python extract_frames.py')

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()
</code>```

答:
Try adjusting it as thus:</p>

```<code>import tkinter
import os
from subprocess import call
import threading

window = tkinter.Tk()
window.title("GUI")

def clicked():
    #os.system('python inference.py')
    #os.system('python extract_frames.py')

    # I used the threading approach

    threading.Thread(target=call, args=("python inference.py" ,), ).start()
    threading.Thread(target=call, args=("python extract_frames.py" ,), ).start()

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish.
Here's the code:

import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")

def clicked():
     os.system('python inference.py')
     os.system('python extract_frames.py')

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()

Body:
Try adjusting it as thus:

import tkinter
import os
from subprocess import call
import threading

window = tkinter.Tk()
window.title("GUI")

def clicked():
    #os.system('python inference.py')
    #os.system('python extract_frames.py')

    # I used the threading approach

    threading.Thread(target=call, args=("python inference.py" ,), ).start()
    threading.Thread(target=call, args=("python extract_frames.py" ,), ).start()

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()


问:
ggplot2 plot an angle between two lines
I would like to plot an angle between two lines using ggplot2, meaning something similar to the bold red line in the plot below. Is there an easy solution to this?

Data and code to make the plot without the red line:

```<code>library(tidyverse)

df <- tibble(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5))

ggplot(
  df, aes(x, y, group = line))+
  geom_path()
</code>```

答:
Here is a solution with geom_arc of the ggforce package.

```<code>library(ggplot2)
library(ggforce)

angle <- function(p, c){
  M <- p - c
  Arg(complex(real = M[1], imaginary = M[2]))
}

O <- c(1,1)
P1 <- c(5,3)
P2 <- c(3,5)
a1 <- angle(P1, O)
a2 <- angle(P2, O)

df <- data.frame(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5)
)

ggplot(df, aes(x, y, group = line)) +
  geom_path() +
  geom_arc(aes(x0 = 1, y0 = 1, r = 1, start = a1, end = a2),
           color="red", size = 2, inherit.aes = FALSE)
</code>```

The arc does not look like a true arc circle. That's because the aspect ratio is not set to 1. To set the aspect ratio to 1:

```<code>ggplot(df, aes(x, y, group = line)) +
  geom_path() +
  geom_arc(aes(x0 = 1, y0 = 1, r = 1, start = a1, end = a2),
           color="red", size = 2, inherit.aes = FALSE) +
  coord_fixed()
</code>```

Title: ggplot2 plot an angle between two lines

Body:
I would like to plot an angle between two lines using ggplot2, meaning something similar to the bold red line in the plot below. Is there an easy solution to this?

Data and code to make the plot without the red line:

library(tidyverse)

df <- tibble(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5))

ggplot(
  df, aes(x, y, group = line))+
  geom_path()

Body:
Here is a solution with geom_arc of the ggforce package.

library(ggplot2)
library(ggforce)

angle <- function(p, c){
  M <- p - c
  Arg(complex(real = M[1], imaginary = M[2]))
}

O <- c(1,1)
P1 <- c(5,3)
P2 <- c(3,5)
a1 <- angle(P1, O)
a2 <- angle(P2, O)

df <- data.frame(
  line = c("A", "A", "B", "B"),
  x = c(1, 5, 1, 3),
  y = c(1, 3, 1, 5)
)

ggplot(df, aes(x, y, group = line)) +
  geom_path() +
  geom_arc(aes(x0 = 1, y0 = 1, r = 1, start = a1, end = a2),
           color="red", size = 2, inherit.aes = FALSE)

The arc does not look like a true arc circle. That's because the aspect ratio is not set to 1. To set the aspect ratio to 1:

ggplot(df, aes(x, y, group = line)) +
  geom_path() +
  geom_arc(aes(x0 = 1, y0 = 1, r = 1, start = a1, end = a2),
           color="red", size = 2, inherit.aes = FALSE) +
  coord_fixed()


问:
Row wise outlier/anomaly detection based on the values given in one column (in array format)
I have been trying to find a way through Python or R where in the csv file that I have, the script should go through each row and try to detect outliers or anomalies based on the array values in one of the columns.

The issue is quite complex according to me and I have exhausted myself trying to go through methods which detect anomalies or outliers.

Should I look into Machine Learning for such an issue?

There is already a question posted for similar kind of thing but it has not been answered correctly (I feel), the image of the data given there can be used to describe any plausible answer.

Thanks

I would like to find the outliers in the Values column, for example, in the first row 142 would be an outlier when compared to other values in the cell, i want something which would go ID wise (row by row) and write the outliers to a new file with all these columns in place

答:
Maybe an entropy based approach would  work here: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.380.4114&rep=rep1&type=pdf

In short, entropy is the measure of disorder. So you can "measure" the disorder of your rows by calculating the row entropy. It is a relative measure so you will have to try and determine what is precise for your case (this is not an exact science).

Here is an example:

```<code>from scipy.stats import entropy

def my_entropy(labels, base = None):
    value,counts = np.unique(labels, return_counts=True)
    return entropy(counts, base=base)

ls = [ [1,0,1,0,1,0,1,0,1,1,1,1], [1,0,1,0,1,0,1,0,1,1,9,1] , [1,0,1,'A',1,0,1,0,1,1,1,1], [1,0,1,0,5,0,1,0,7,1,0,1] ]

res = []
for labels in ls:
    res.append(my_entropy(labels))

print(res)
#[0.6365141682948128, 0.887694275799104, 0.8239592165010823, 1.14370838942625]
</code>```

res here ranks the list based on the disorder. In the first case we only have zeros and ones so the entropy is the lowest. Different outliers introduced in other 3 lists noticeably increase the entropy. So one can use entropy here as a quality measure.

Body:
Maybe an entropy based approach would  work here: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.380.4114&rep=rep1&type=pdf

In short, entropy is the measure of disorder. So you can "measure" the disorder of your rows by calculating the row entropy. It is a relative measure so you will have to try and determine what is precise for your case (this is not an exact science).

Here is an example:

from scipy.stats import entropy

def my_entropy(labels, base = None):
    value,counts = np.unique(labels, return_counts=True)
    return entropy(counts, base=base)

ls = [ [1,0,1,0,1,0,1,0,1,1,1,1], [1,0,1,0,1,0,1,0,1,1,9,1] , [1,0,1,'A',1,0,1,0,1,1,1,1], [1,0,1,0,5,0,1,0,7,1,0,1] ]

res = []
for labels in ls:
    res.append(my_entropy(labels))

print(res)
#[0.6365141682948128, 0.887694275799104, 0.8239592165010823, 1.14370838942625]

res here ranks the list based on the disorder. In the first case we only have zeros and ones so the entropy is the lowest. Different outliers introduced in other 3 lists noticeably increase the entropy. So one can use entropy here as a quality measure.


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
Doing this alone you will obtain many harmful habits. It's much better to get an internship with a company that has high competence in C++ development and train under guidance.

C++ is like a grenade without a safety pin – looks cool and you've heard that all "real professionals" use it, but you don't know when it is to explode. A tremendous amount of features that can be used for good or for evil without knowing whether it's really good or evil. That's why guidance is a must here.

OwnerDisplayName: climatewarrior

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
How to start GUI from command line in Android-x86
I managed to get Android-x86 running in VMware player, but if I need to go to the command line by pressing Alt+F1 I cannot go back to the GUI. How do I restart the GUI from the command line?</p>

答:
To start the GUI, I had to select VboxVGA instead of VMSVGA in the VirtualBox display settings of the virtual machine.

Note: This is a solution to make it work with VirtualBox in case it helps someone who finds this question. It is possible that the solution to make it work with VMware player is similar.

I also found this information here:

Mandatory: Unless guest additions are installed, change the default
VMSVGA to VBoxVGA.


问:
Progress uploading files with formidable
I'm using node.js-expresss backend with formidable package. I tried to implement a progress bar and decided to used formidable & websockets:

```<code>const create = (req, res, io) => {
  logger.debug(`EXEC create material`)
  const form = new formidable.IncomingForm()
  form.encoding = 'utf-8'
  form.keepExtensions = true
  form.multiples = true
  form.maxFileSize = 600 * 1024 * 1024 // 600MB instead of 200MB (default value)
  // form.uploadDir = `${__dirname}/uploads`
  let oldValue = 0
  form.on('progress', (bytesReceived, bytesExpected) => {
    let currentValue = (parseFloat(bytesReceived) / parseFloat(bytesExpected)) * 100
    if ((currentValue - oldValue) > 1 || currentValue === 100) {
      oldValue = currentValue
      io.emit('FILE_UPLOAD_STATUS', currentValue)
      console.log('FILE_UPLOAD_STATUS', currentValue)
    }
  })
...
</code>```

However it seeems to process files and show progress once all files are uploaded? Files can be quite big so I see a progress bar empty in the browser, till the end when it goes from 0% to 100% in a really short period of time.

Should I change my code and get the progress from the xhr request?

答:
Finally I decided to move it to js inside browser successfully. Using axios as it's the easiest/fastest way to deal with progress. This is my code in case of interest (React app):</p>

```<code>axios.request({
      method: "POST",
      url: `${PRIVATE_API_ROOT}/materials`,
      data: formData,
      headers: { Authorization: `Bearer ${token}` },
      onUploadProgress: ProgressEvent => {
        this.setState({
          progressStatus: parseFloat(ProgressEvent.loaded / ProgressEvent.total * 100).toFixed(2),
        })
      }
    }).then(data => {
      this.setState({
        progressStatus: 100,
        loading: false,
        error: ''
      })
    }).catch(function (error) {
      //handle error
      this.setState({ error: error.message })
    });
```
</code>```

Body:
I'm using node.js-expresss backend with formidable package. I tried to implement a progress bar and decided to used formidable & websockets:

const create = (req, res, io) => {
  logger.debug(`EXEC create material`)
  const form = new formidable.IncomingForm()
  form.encoding = 'utf-8'
  form.keepExtensions = true
  form.multiples = true
  form.maxFileSize = 600 * 1024 * 1024 // 600MB instead of 200MB (default value)
  // form.uploadDir = `${__dirname}/uploads`
  let oldValue = 0
  form.on('progress', (bytesReceived, bytesExpected) => {
    let currentValue = (parseFloat(bytesReceived) / parseFloat(bytesExpected)) * 100
    if ((currentValue - oldValue) > 1 || currentValue === 100) {
      oldValue = currentValue
      io.emit('FILE_UPLOAD_STATUS', currentValue)
      console.log('FILE_UPLOAD_STATUS', currentValue)
    }
  })
...

However it seeems to process files and show progress once all files are uploaded? Files can be quite big so I see a progress bar empty in the browser, till the end when it goes from 0% to 100% in a really short period of time.

Should I change my code and get the progress from the xhr request?

Body:
Finally I decided to move it to js inside browser successfully. Using axios as it's the easiest/fastest way to deal with progress. This is my code in case of interest (React app):

axios.request({
      method: "POST",
      url: `${PRIVATE_API_ROOT}/materials`,
      data: formData,
      headers: { Authorization: `Bearer ${token}` },
      onUploadProgress: ProgressEvent => {
        this.setState({
          progressStatus: parseFloat(ProgressEvent.loaded / ProgressEvent.total * 100).toFixed(2),
        })
      }
    }).then(data => {
      this.setState({
        progressStatus: 100,
        loading: false,
        error: ''
      })
    }).catch(function (error) {
      //handle error
      this.setState({ error: error.message })
    });
```


问:
SwiftUI - How can I get multiline text to wrap in a UITextView without scrolling?
I am using the UIViewRepresentable wrapper to create a bindable multiline UITextVIew since there is still no multiline support for the native SwiftUI TextField. It all works fine as long as isScrollEnabled = true is set on the UITextView.

Is there a way to get the text to wrap without the UITextView being scrollable?

import SwiftUI

struct TextfieldIssue: View {
  @State var text: String = "Hello, I am some long text that will wrap if isScrollEnabled is set to true, but not if isScrollEnabled is set to false"

  var body: some View {
    MultilineTextField(text: $text)
  }
}

struct MultilineTextField: UIViewRepresentable {

  private let view = UITextView()

  @Binding var text: String

  func makeUIView(context: UIViewRepresentableContext<MultilineTextField>) -> UITextView {

    view.isEditable = true
    view.font = UIFont.systemFont(ofSize: 24)

    // Text wraps fine as long as this is true
    view.isScrollEnabled = true

    // Text does not wrap if this is uncommented
//    view.isScrollEnabled = false

    view.text = text
    view.delegate = context.coordinator

    return view
  }

  func updateUIView(_ uiView: UITextView, context: UIViewRepresentableContext<MultilineTextField>) {
    uiView.text = text
  }

  func makeCoordinator() -> TextFieldCoordinator {
    let coordinator = TextFieldCoordinator(self)
    self.view.delegate = coordinator

    return coordinator
  }
}

class TextFieldCoordinator : NSObject, UITextViewDelegate {

  var parent: MultilineTextField

  init(_ multilineTextField: MultilineTextField) {
    self.parent = multilineTextField
  }

  func textViewDidChange(_ textView: UITextView) {
    self.parent.text = textView.text
  }
}

struct TextfieldIssue_Previews: PreviewProvider {
    static var previews: some View {
        TextfieldIssue()
    }
}
```

答:
Just add this to makeUIView and the text will wrap.

```<code>view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
</code>```

Here's the full updated makeUIView function:

func makeUIView(context: UIViewRepresentableContext<MultilineTextField>) -> UITextView {

    view.isEditable = true
    view.font = UIFont.systemFont(ofSize: 24)
    view.isScrollEnabled = false
    view.view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
    view.delegate = context.coordinator
    view.text = text

    return view
  }
```

Body:
Just add this to makeUIView and the text will wrap.

view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

Here's the full updated makeUIView function:

func makeUIView(context: UIViewRepresentableContext<MultilineTextField>) -> UITextView {

    view.isEditable = true
    view.font = UIFont.systemFont(ofSize: 24)
    view.isScrollEnabled = false
    view.view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
    view.delegate = context.coordinator
    view.text = text

    return view
  }


问:
How to combine results of two queries into a single dataset
I have two queries :
Queries Simplified excluding Joins

```<code>Query 1 : select ProductName,NumberofProducts (in inventory) from Table1.....;
Query 2 : select ProductName, NumberofProductssold from Table2......;
</code>```

I would like to know how I can get an output as :

```<code>ProductName NumberofProducts(in inventory)  ProductName NumberofProductsSold
</code>```

The relationships used for getting the outputs for each query are different.
I need the output this way for my SSRS report .

(I tried the union statement but it doesnt work for the output I want to see. )

答:
Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:

```<code>select
  (select count(*) c from v$session where program = 'w3wp.exe') w3wp,
  (select count(*) c from v$session) total,
  sysdate
from dual;
</code>```

which gives the following one-row output:

```<code>W3WP   TOTAL  SYSDATE
-----  -----  -------------------
   14    290  2020/02/18 10:45:07
</code>```

(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)

Body:
I have two queries :
Queries Simplified excluding Joins

Query 1 : select ProductName,NumberofProducts (in inventory) from Table1.....;
Query 2 : select ProductName, NumberofProductssold from Table2......;

I would like to know how I can get an output as :

ProductName NumberofProducts(in inventory)  ProductName NumberofProductsSold

The relationships used for getting the outputs for each query are different.
I need the output this way for my SSRS report .

(I tried the union statement but it doesnt work for the output I want to see. )

Body:
Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:

select
  (select count(*) c from v$session where program = 'w3wp.exe') w3wp,
  (select count(*) c from v$session) total,
  sysdate
from dual;

which gives the following one-row output:

W3WP   TOTAL  SYSDATE
-----  -----  -------------------
   14    290  2020/02/18 10:45:07

(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)


问:
Angular 8 - Upload file along with form and send to server
I have a reactive form in Angular 8. On form submission, I need to post the values along with the uploaded file to an API. But I am not quite sure of how to post the file along with values.

```<code><form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">
    <div>
        <label for="desc">Description</label>
        <input type="text" id="desc" formControlName="desc"/>
    </div>
    <div>
        <label for="summary">Summary</label>
        <textarea id="summary" formControlName="summary"></textarea>
    </div>
    <div formGroupName="contact">
        <div>
            <label for="name">Name</label>
            <input type="text" id="name" required formControlName="name"/>
        </div>
        <div>
            <label for="email">Email</label>
            <input type="email" id="email" formControlName="email"/>
        </div>
    </div>
    <div>
        <label for="file">Upload File</label>
        <input type="file" id="file" formControlName="file">
    </div>
    <button type="submit">Submit</button>
</form>
</code>```

In component

```<code>constructor(public httpService: HttpRequestService) { }

onSubmit() {
   this.httpService.postData(this.detailsForm.value).then(
      (result) => {
        this.jsonResponse = result;
      },
      (err) => {
        this.errorResponse = 'Sorry, there was an error processing your request!';
      }
   )
}
</code>```

In service

```<code>postData(detailsData) {
    const headers = new HttpHeaders(
      { 'Content-Type': 'multipart/form-data' }
    );
    return new Promise((resolve, reject) =>{
      this.http.post('http://localhost:3000/postData', detailsData, { headers: headers })
      .subscribe(res => resolve(res), err => reject(err))
    });
}
</code>```

In backend, just for testing purpose

```<code>const express = require("express");
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());
// Configuring body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.listen(3000, () => {
 console.log("Server running on port 3000");
});

app.post("/postData", (req,res) => {
    console.log(req.body);
});
</code>```

All the values are logged, but for file I am only getting the path value. How do I get the contents of file(I need to upload and send Excel File).

答:
Here's what I normally do when I want to send a file to the backend.

Html element

```<code>        <div class="form-group">
          <input style="color:transparent;" onchange="this.style.color = 'black';" type="file"
            (change)="onImageChange($event)" #bannerPhoto />
        </div>
</code>```

component.ts

```<code>onImageChange(event) {
const reader = new FileReader();
if (event.target.files && event.target.files.length) {
  const [file] = event.target.files;
  reader.readAsDataURL(file);
  reader.onload = () => {
    this.addEventForm.patchValue({
      banner: reader.result
    });
    this.formData.append('banner', event.target.files[0], event.target.files[0].name);
  };
}}
</code>```

Here's the type of formData and addEventForm variables:

```<code>  addEventForm: FormGroup;
  formData: FormData;
</code>```

How I'm calling the API:

```<code>    this.eventService.add(this.formData)
        .subscribe(/*Your code goes here*/)
</code>```

Body:
I have a reactive form in Angular 8. On form submission, I need to post the values along with the uploaded file to an API. But I am not quite sure of how to post the file along with values.

<form [formGroup]="detailsForm" (ngSubmit)="onSubmit()">

        Description
        <input type="text" id="desc" formControlName="desc"/>

        Summary
        <textarea id="summary" formControlName="summary"></textarea>

            Name
            <input type="text" id="name" required formControlName="name"/>

            Email
            <input type="email" id="email" formControlName="email"/>

        Upload File
        <input type="file" id="file" formControlName="file">

    <button type="submit">Submit</button>
</form>

In component

constructor(public httpService: HttpRequestService) { }

onSubmit() {
   this.httpService.postData(this.detailsForm.value).then(
      (result) => {
        this.jsonResponse = result;
      },
      (err) => {
        this.errorResponse = 'Sorry, there was an error processing your request!';
      }
   )
}

In service

postData(detailsData) {
    const headers = new HttpHeaders(
      { 'Content-Type': 'multipart/form-data' }
    );
    return new Promise((resolve, reject) =>{
      this.http.post('http://localhost:3000/postData', detailsData, { headers: headers })
      .subscribe(res => resolve(res), err => reject(err))
    });
}

In backend, just for testing purpose

const express = require("express");
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());
// Configuring body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.listen(3000, () => {
 console.log("Server running on port 3000");
});

app.post("/postData", (req,res) => {
    console.log(req.body);
});

All the values are logged, but for file I am only getting the path value. How do I get the contents of file(I need to upload and send Excel File).

Body:
Here's what I normally do when I want to send a file to the backend.

Html element

        <div class="form-group">
          <input style="color:transparent;" onchange="this.style.color = 'black';" type="file"
            (change)="onImageChange($event)" #bannerPhoto />
        </div>

component.ts

onImageChange(event) {
const reader = new FileReader();
if (event.target.files && event.target.files.length) {
  const [file] = event.target.files;
  reader.readAsDataURL(file);
  reader.onload = () => {
    this.addEventForm.patchValue({
      banner: reader.result
    });
    this.formData.append('banner', event.target.files[0], event.target.files[0].name);
  };
}}

Here's the type of formData and addEventForm variables:

  addEventForm: FormGroup;
  formData: FormData;

How I'm calling the API:

    this.eventService.add(this.formData)
        .subscribe(/*Your code goes here*/)


问:
java.lang.ExceptionInInitializerError groovy compiler loading error
I am getting below error when I executing my JUnit test case. I am using Expectations plugin for Grails Domain Test case.

BuildConfig.groovy file code:

```<code>plugins {
   compile ":domain-expectations:0.6.1"
}
</code>```

Error which I am getting:

```<code>java.lang.ExceptionInInitializerError
    at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:61)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:72)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:159)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.lonecyprus.grails.test.Specification.<clinit>(Specification.groovy)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at junit.framework.TestSuite.createTest(TestSuite.java:63)
    at junit.framework.TestSuite.addTestMethod(TestSuite.java:310)
    at junit.framework.TestSuite.addTestsFromTestCase(TestSuite.java:153)
    at junit.framework.TestSuite.<init>(TestSuite.java:132)
    at org.junit.internal.runners.JUnit38ClassRunner.<init>(JUnit38ClassRunner.java:72)
    at org.junit.internal.builders.JUnit3Builder.runnerForClass(JUnit3Builder.java:11)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Caused by: groovy.lang.GroovyRuntimeException: Conflicting module versions. Module [groovy-all is loaded in version 2.3.10 and you are trying to load version 2.3.7
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl$DefaultModuleListener.onModule(MetaClassRegistryImpl.java:509)
    at org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner.scanExtensionModuleFromProperties(ExtensionModuleScanner.java:77)
    at org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner.scanExtensionModuleFromMetaInf(ExtensionModuleScanner.java:71)
    at org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner.scanClasspathModules(ExtensionModuleScanner.java:53)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:110)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:71)
    at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:33)
    ... 29 more
</code>```

答: For this 1st of you have chack the version of groovy in Maven Dependencies library and Built path. Version of groovy should be match so that this error will go else error will come because of version conflict.

Body:
I am getting below error when I executing my JUnit test case. I am using Expectations plugin for Grails Domain Test case.

BuildConfig.groovy file code:

plugins {
   compile ":domain-expectations:0.6.1"
}

Error which I am getting:

java.lang.ExceptionInInitializerError
    at org.codehaus.groovy.runtime.InvokerHelper.<clinit>(InvokerHelper.java:61)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallStaticSite(CallSiteArray.java:72)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallSite(CallSiteArray.java:159)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.lonecyprus.grails.test.Specification.<clinit>(Specification.groovy)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at junit.framework.TestSuite.createTest(TestSuite.java:63)
    at junit.framework.TestSuite.addTestMethod(TestSuite.java:310)
    at junit.framework.TestSuite.addTestsFromTestCase(TestSuite.java:153)
    at junit.framework.TestSuite.<init>(TestSuite.java:132)
    at org.junit.internal.runners.JUnit38ClassRunner.<init>(JUnit38ClassRunner.java:72)
    at org.junit.internal.builders.JUnit3Builder.runnerForClass(JUnit3Builder.java:11)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:26)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Caused by: groovy.lang.GroovyRuntimeException: Conflicting module versions. Module [groovy-all is loaded in version 2.3.10 and you are trying to load version 2.3.7
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl$DefaultModuleListener.onModule(MetaClassRegistryImpl.java:509)
    at org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner.scanExtensionModuleFromProperties(ExtensionModuleScanner.java:77)
    at org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner.scanExtensionModuleFromMetaInf(ExtensionModuleScanner.java:71)
    at org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner.scanClasspathModules(ExtensionModuleScanner.java:53)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:110)
    at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.<init>(MetaClassRegistryImpl.java:71)
    at groovy.lang.GroovySystem.<clinit>(GroovySystem.java:33)
    ... 29 more


问:
Mongodb: How can I find the nested group that maximizes the values max/min length and calculate the average?
I have a collection with trainings (T) that contains an exercises array and I would like find the nested group that maximizes the values max/min length and calculate the average. The collection is such as:

[{
    "_id" : ObjectId("5e456e6b33fef4299aa75a7e"),
    "title" : "Training aaa and bbb",
    "exercises" : [{
            "title" : "aaa exercise",
            "goals" : ["aaa"],
            "length" : 10
     },{
            "title" : "bbb exercise",
            "goals" : ["bbb"],
            "length" : 5
     }],
    "createdBy" : "dummy"
},{
    "_id" : ObjectId("5e456e7f33fef4299aa75a7f"),
    "title" : "Training aaa, ccc",
    "exercises" : [{
            "title" : "aaa exercise",
            "goals" : ["aaa"],
            "length" : 5
        },{
            "title" : "aaa exercise",
            "goals" : ["aaa"],
            "length" : 10
        },{
            "title" : "ccc exercise",
            "goals" : ["ccc"],
            "length" : 5
    }],
    "createdBy" : "dummy"
},{
    "_id" : ObjectId("5e49b282e0a271e9f57648ff"),
    "title" : "Training aaa 2",
    "exercises" : [{
            "title" : "aaa",
            "goals" : ["aaa"],
            "length" : 5
    },{
            "title" : "ccc exercise",
            "goals" : ["ccc"],
            "length" : 10
    }],
    "createdBy" : "dummy"
}]
```

<p>I would like finding the min/max/avg by goal and training. With the before values, expected values should fit with:</p>

<pre class="lang-javascript prettyprint-override"><code>[{
    _id: "aaa"
    min: 5,  // T1: 5
    max: 15, // T2: 5 + 10
    avg: 10  // T1,T2,T3: (10+15+5)/3 = 10
},{
    _id: "bbb",
    min: 5,  // T1: 5
    max: 5,  // T1: 5
    avg: 5   // T1: 5/1 = 5
},{
    _id: "ccc",
    min: 5,  // T2: 5
    max: 10, // T3: 10
    avg: 5   // T2,T3: (5+10)/2 = 7,5
}]
</code>```

In this example, aaa was train 10 minutes in the first training, 15 in the second and 5 in the third one. So min=5, max=15, avg: (10+15+5)/3 = 10

I tried the following, but I did not get the expected result although it is close:

db.getCollection('trainings').aggregate([
    {$match : {"createdBy" : "dummy" } },
    {$unwind: "$exercises"},
    {$unwind: "$exercises.goals" },
    {$group: {
        _id: "$exercises.goals",
        count: { $sum: 1 },
        lengthAvg: {$avg: "$exercises.length"},
        lengthMin: {$min: "$exercises.length"},
        lengthMax: {$max: "$exercises.length"},
        lengthSum: {$sum: "$exercises.length"}
        }
    }
])
```

I think the issues is with $unwind stage that deconstructs the exercises and group by training is lost. But I am not sure how change it.

答:
You were touching the solution with your query. The trick is to group first by training to get sum of goals inside each trainning, then group by goals to get needed metrics.

```<code>db.collection.aggregate([
  {
    $match: {
      "createdBy": "dummy"
    }
  },
  {
    $unwind: "$exercises"
  },
  {
    $unwind: "$exercises.goals"
  },
  {
    $group: {
      _id: {
        trainingId: "$_id",
        goal: "$exercises.goals",

      },
      totalPerTraining: {
        $sum: "$exercises.length"
      }
    }
  },
 {
    $group: {
      _id: "$_id.goal",
      lengthMin: {
        $min: "$totalPerTraining"
      },
      lengthMax: {
        $max: "$totalPerTraining"
      },
      lengthAvg: {
        $avg: "$totalPerTraining"
      },
      count: {
        $sum: 1
      },
      lengthSum: {
        $sum: "$totalPerTraining"
      }
    }
  }
])
</code>```

You can test it here

---EDIT---

Although the previous aggregation will perfectly work, it can consume a lot of resources by unwinding twice. I highly recommand for this kind of needs to use map/reduce approach, more efficient in your case.

```<code>  map = function () {
    var trainingSums = {};
    this.exercises.forEach(function (exercise) {
      exercise.goals.forEach(function (goal) {
        if (trainingSums[goal] == null) {
          trainingSums[goal] = 0;
        }
        trainingSums[goal] += exercise.length;
      })
    });

    for (property in trainingSums) {
      print(trainingSums);
      emit(property, trainingSums[property]);
    }
  };
  reduce = function (key, values) {
    var reducedValues = {};
    reducedValues.sum = values.reduce((a, b) => a + b, 0);
    reducedValues.min = Math.min(...values);
    reducedValues.max = Math.max(...values);
    reducedValues.avg = values.reduce((a, b) => a + b, 0) / values.length;
    reducedValues.count = values.length;
    return reducedValues;
  };
  finalize = function (key, reducedValue) {
    var finalValue = {};
    if (!isObject(reducedValue)) {
      finalValue.sum = reducedValue;
      finalValue.min = reducedValue;
      finalValue.max = reducedValue;
      finalValue.avg = reducedValue;
      finalValue.count = 1;
    } else
      finalValue = reducedValue;
    return finalValue;
  };
</code>```

The map function is calculating the sum for each goals in a training, then emit this.

The reduce function is calculating your metrics.

The finalize function is here to define metrics when a goal was found only once in all traings (like your 'ccc' goal in example), because in this case the reduce function will not be applied.

For those keys that have multiple values, MongoDB applies the reduce phase, which collects and condenses the aggregated data.

Body:
I have a collection with trainings (T) that contains an exercises array and I would like find the nested group that maximizes the values max/min length and calculate the average. The collection is such as:

[{
    "_id" : ObjectId("5e456e6b33fef4299aa75a7e"),
    "title" : "Training aaa and bbb",
    "exercises" : [{
            "title" : "aaa exercise",
            "goals" : ["aaa"],
            "length" : 10
     },{
            "title" : "bbb exercise",
            "goals" : ["bbb"],
            "length" : 5
     }],
    "createdBy" : "dummy"
},{
    "_id" : ObjectId("5e456e7f33fef4299aa75a7f"),
    "title" : "Training aaa, ccc",
    "exercises" : [{
            "title" : "aaa exercise",
            "goals" : ["aaa"],
            "length" : 5
        },{
            "title" : "aaa exercise",
            "goals" : ["aaa"],
            "length" : 10
        },{
            "title" : "ccc exercise",
            "goals" : ["ccc"],
            "length" : 5
    }],
    "createdBy" : "dummy"
},{
    "_id" : ObjectId("5e49b282e0a271e9f57648ff"),
    "title" : "Training aaa 2",
    "exercises" : [{
            "title" : "aaa",
            "goals" : ["aaa"],
            "length" : 5
    },{
            "title" : "ccc exercise",
            "goals" : ["ccc"],
            "length" : 10
    }],
    "createdBy" : "dummy"
}]

I would like finding the min/max/avg by goal and training. With the before values, expected values should fit with:

[{
    _id: "aaa"
    min: 5,  // T1: 5
    max: 15, // T2: 5 + 10
    avg: 10  // T1,T2,T3: (10+15+5)/3 = 10
},{
    _id: "bbb",
    min: 5,  // T1: 5
    max: 5,  // T1: 5
    avg: 5   // T1: 5/1 = 5
},{
    _id: "ccc",
    min: 5,  // T2: 5
    max: 10, // T3: 10
    avg: 5   // T2,T3: (5+10)/2 = 7,5
}]

In this example, aaa was train 10 minutes in the first training, 15 in the second and 5 in the third one. So min=5, max=15, avg: (10+15+5)/3 = 10

I tried the following, but I did not get the expected result although it is close:

db.getCollection('trainings').aggregate([
    {$match : {"createdBy" : "dummy" } },
    {$unwind: "$exercises"},
    {$unwind: "$exercises.goals" },
    {$group: {
        _id: "$exercises.goals",
        count: { $sum: 1 },
        lengthAvg: {$avg: "$exercises.length"},
        lengthMin: {$min: "$exercises.length"},
        lengthMax: {$max: "$exercises.length"},
        lengthSum: {$sum: "$exercises.length"}
        }
    }
])

I think the issues is with $unwind stage that deconstructs the exercises and group by training is lost. But I am not sure how change it.

Body:
You were touching the solution with your query. The trick is to group first by training to get sum of goals inside each trainning, then group by goals to get needed metrics.

db.collection.aggregate([
  {
    $match: {
      "createdBy": "dummy"
    }
  },
  {
    $unwind: "$exercises"
  },
  {
    $unwind: "$exercises.goals"
  },
  {
    $group: {
      _id: {
        trainingId: "$_id",
        goal: "$exercises.goals",

      },
      totalPerTraining: {
        $sum: "$exercises.length"
      }
    }
  },
 {
    $group: {
      _id: "$_id.goal",
      lengthMin: {
        $min: "$totalPerTraining"
      },
      lengthMax: {
        $max: "$totalPerTraining"
      },
      lengthAvg: {
        $avg: "$totalPerTraining"
      },
      count: {
        $sum: 1
      },
      lengthSum: {
        $sum: "$totalPerTraining"
      }
    }
  }
])

You can test it here

---EDIT---

Although the previous aggregation will perfectly work, it can consume a lot of resources by unwinding twice. I highly recommand for this kind of needs to use map/reduce approach, more efficient in your case.

  map = function () {
    var trainingSums = {};
    this.exercises.forEach(function (exercise) {
      exercise.goals.forEach(function (goal) {
        if (trainingSums[goal] == null) {
          trainingSums[goal] = 0;
        }
        trainingSums[goal] += exercise.length;
      })
    });

    for (property in trainingSums) {
      print(trainingSums);
      emit(property, trainingSums[property]);
    }
  };
  reduce = function (key, values) {
    var reducedValues = {};
    reducedValues.sum = values.reduce((a, b) => a + b, 0);
    reducedValues.min = Math.min(...values);
    reducedValues.max = Math.max(...values);
    reducedValues.avg = values.reduce((a, b) => a + b, 0) / values.length;
    reducedValues.count = values.length;
    return reducedValues;
  };
  finalize = function (key, reducedValue) {
    var finalValue = {};
    if (!isObject(reducedValue)) {
      finalValue.sum = reducedValue;
      finalValue.min = reducedValue;
      finalValue.max = reducedValue;
      finalValue.avg = reducedValue;
      finalValue.count = 1;
    } else
      finalValue = reducedValue;
    return finalValue;
  };

The map function is calculating the sum for each goals in a training, then emit this.

The reduce function is calculating your metrics.

The finalize function is here to define metrics when a goal was found only once in all traings (like your 'ccc' goal in example), because in this case the reduce function will not be applied.

For those keys that have multiple values, MongoDB applies the reduce phase, which collects and condenses the aggregated data.


问:
How to parse json Data into dynamic collection view sections and cells in swift
This is the json response that I am getting from postman after making network request

```<code>[
    {
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-25",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

   {
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-25",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

{
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-25",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

{
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-24",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

{
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-24",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    }]
</code>```

This is my Model struct where I am parsing my json data

```<code>struct jobsData:Decodable
{
    let employeeName:String?
    let startTime:String?
    let endTime:String?
    var startDate:String?

    init(employeeName:String?=nil,
         startTime:String?=nil,
         endTime:String?=nil,
         startDate:String?=nil){

        self.employeeName=employeeName
        self.startTime=startTime
        self.endTime=endTime
        self.startDate=startDate
    }}
</code>```

I am using json decoder to decode the data coming after urlSession request
now I need to manipulate the response in such a way that the number of sections of uicollectionview will be the startDate and its header text will be its text e.g, in above case there will be two sections of uicollectionview. each section's items will be the no of objects in json response that corresponds to that date like in above case there will be three items in section with date 2020-02-25 and two items in section with date 2020-02-24. the problem I am having is that I don't know the no of sections and no of items in each sections as the data is dynamic that is coming from an api. how can I manipulate the json response to append them in uicollectionview like I stated.
https://stackoverflow.com/a/49397623
this link was helpful but I don't know how to sort my data as in above link there was only two keys one for sorting and other for collectionview data but I have multiple keys.

Edited:
This is my collectionview data source function. How can I show the data in different sections

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)as! AvailableJobsCell
    let sTime=self.timeInAmPm(String: UserInformation[indexPath.item].startTime!)
    let eTime=self.timeInAmPm(String: UserInformation[indexPath.item].endTime!)
    cell.jobAddedTime.text="\(sTime) - \(eTime)"
    cell.jobTitle.text=UserInformation[indexPath.item].employeeName!
    cell.schoolName.text="\(UserInformation[indexPath.item].organizationName ?? "")\n\(UserInformation[indexPath.item].organizationAddress ?? "")"
    cell.jobNo.text=UserInformation[indexPath.item].confirmationNumber!
    cell.personOnHiatus.text=UserInformation[indexPath.item].positionDescription!
    cell.index=indexPath
    cell.delegate=self
        return cell
}
</code>```

UserInformation is of type [JobsData]

答:
First of all declare the struct with uppercased name, with non-optional members and without the init method.

```<code>struct JobsData : Decodable
{
    let employeeName : String
    let startTime : String
    let endTime : String
    var startDate : String
}
</code>```

To group the data declare a Section struct

```<code>struct Section
{
    let title : String
    let jobsData : [JobsData]
}
</code>```

and declare the data source array

```<code>var sections = [Section]()
</code>```

After decoding the array

```<code>let jobsDataArray = try JSONDecoder().decode([JobsData].self, from: data)
</code>```

group it with Dictionary(grouping:by:), map it to a Section array and sort it

```<code>let grouped = Dictionary(grouping: jobsDataArray, by: {$0.startDate})
self.sections = grouped.map{Section(title: $0.key, jobsData: $0.value)}
                      .sorted{$0.title < $1.title}
</code>```

You can even sort the JobsData items in the sections simultaneously for example by startTime

```<code>self.sections = grouped.map{Section(title: $0.key, jobsData: $0.value.sorted{$0.startTime < $1.startTime})}
                      .sorted{$0.title < $1.title}
</code>```

To display the sections implement the datasource methods

```<code>override func numberOfSections(in collectionView: UICollectionView) -> Int
    return sections.count
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return sections[section].jobsData.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! AvailableJobsCell
    let jobData = sections[indexPath.section].jobsData[indexPath.item]
    let sTime = self.timeInAmPm(String: jobData.startTime)
    let eTime = self.timeInAmPm(String: jobData.endTime)
    cell.jobAddedTime.text = "\(sTime) - \(eTime)"
    cell.jobTitle.text = jobData.employeeName
    cell.schoolName.text = "\(jobData.organizationName ?? "")\n\(jobData.organizationAddress ?? "")"
    cell.jobNo.text = jobData.confirmationNumber!
    cell.personOnHiatus.text = jobData.positionDescription!
    cell.index = indexPath
    cell.delegate = self
    return cell
}
</code>```

Body:
This is the json response that I am getting from postman after making network request

[
    {
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-25",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

   {
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-25",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

{
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-25",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

{
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-24",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    },

{
        "employeeName": "Find a Sub ",
        "startDate": "2020-02-24",
        "startTime": "09:00:00",
        "endTime": "16:00:00"
    }]

This is my Model struct where I am parsing my json data

struct jobsData:Decodable
{
    let employeeName:String?
    let startTime:String?
    let endTime:String?
    var startDate:String?

    init(employeeName:String?=nil,
         startTime:String?=nil,
         endTime:String?=nil,
         startDate:String?=nil){

        self.employeeName=employeeName
        self.startTime=startTime
        self.endTime=endTime
        self.startDate=startDate
    }}

I am using json decoder to decode the data coming after urlSession request
now I need to manipulate the response in such a way that the number of sections of uicollectionview will be the startDate and its header text will be its text e.g, in above case there will be two sections of uicollectionview. each section's items will be the no of objects in json response that corresponds to that date like in above case there will be three items in section with date 2020-02-25 and two items in section with date 2020-02-24. the problem I am having is that I don't know the no of sections and no of items in each sections as the data is dynamic that is coming from an api. how can I manipulate the json response to append them in uicollectionview like I stated.
https://stackoverflow.com/a/49397623
this link was helpful but I don't know how to sort my data as in above link there was only two keys one for sorting and other for collectionview data but I have multiple keys.

Edited:
This is my collectionview data source function. How can I show the data in different sections

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)as! AvailableJobsCell
    let sTime=self.timeInAmPm(String: UserInformation[indexPath.item].startTime!)
    let eTime=self.timeInAmPm(String: UserInformation[indexPath.item].endTime!)
    cell.jobAddedTime.text="\(sTime) - \(eTime)"
    cell.jobTitle.text=UserInformation[indexPath.item].employeeName!
    cell.schoolName.text="\(UserInformation[indexPath.item].organizationName ?? "")\n\(UserInformation[indexPath.item].organizationAddress ?? "")"
    cell.jobNo.text=UserInformation[indexPath.item].confirmationNumber!
    cell.personOnHiatus.text=UserInformation[indexPath.item].positionDescription!
    cell.index=indexPath
    cell.delegate=self
        return cell
}

UserInformation is of type [JobsData]

Body:
First of all declare the struct with uppercased name, with non-optional members and without the init method.

struct JobsData : Decodable
{
    let employeeName : String
    let startTime : String
    let endTime : String
    var startDate : String
}

To group the data declare a Section struct

struct Section
{
    let title : String
    let jobsData : [JobsData]
}

and declare the data source array

var sections = [Section]()

After decoding the array

let jobsDataArray = try JSONDecoder().decode([JobsData].self, from: data)

group it with Dictionary(grouping:by:), map it to a Section array and sort it

let grouped = Dictionary(grouping: jobsDataArray, by: {$0.startDate})
self.sections = grouped.map{Section(title: $0.key, jobsData: $0.value)}
                      .sorted{$0.title < $1.title}

You can even sort the JobsData items in the sections simultaneously for example by startTime

self.sections = grouped.map{Section(title: $0.key, jobsData: $0.value.sorted{$0.startTime < $1.startTime})}
                      .sorted{$0.title < $1.title}

To display the sections implement the datasource methods

override func numberOfSections(in collectionView: UICollectionView) -> Int
    return sections.count
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return sections[section].jobsData.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! AvailableJobsCell
    let jobData = sections[indexPath.section].jobsData[indexPath.item]
    let sTime = self.timeInAmPm(String: jobData.startTime)
    let eTime = self.timeInAmPm(String: jobData.endTime)
    cell.jobAddedTime.text = "\(sTime) - \(eTime)"
    cell.jobTitle.text = jobData.employeeName
    cell.schoolName.text = "\(jobData.organizationName ?? "")\n\(jobData.organizationAddress ?? "")"
    cell.jobNo.text = jobData.confirmationNumber!
    cell.personOnHiatus.text = jobData.positionDescription!
    cell.index = indexPath
    cell.delegate = self
    return cell
}


问:
empty textbox controls after the data is inserted / saved/ submitted in a c# winform application
I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:

```<code>textbox1.Text="";
</code>```

But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?

Please guide.

答:
If you have all the textboxes on a form without panels or group boxes, you can do this:

```<code>foreach (var conrol in Controls)
{
    var textbox = conrol as TextBox;
    if (textbox != null)
        textbox.Clear();
}
</code>```

If you have a panel, use panel.Controls instead.

Body:
I need to empty all the textbox controls after the SAVE button is clicked but the user. I have around 10 of them. How do i clear text from them all simultaneously. I just know about:

textbox1.Text="";

But, if i do this, then i need to repeat this for the no. of textbox controls on my Form, that would be a labor task instead of programmer?

Please guide.

Body:
If you have all the textboxes on a form without panels or group boxes, you can do this:

foreach (var conrol in Controls)
{
    var textbox = conrol as TextBox;
    if (textbox != null)
        textbox.Clear();
}

If you have a panel, use panel.Controls instead.


问:
Can we search all the public post referring a particular keyword using Facebook Graph API?
I need to get all facebook posts with the sdk by searching with one word</p>

答:
There is no way to do this, for normal 3rd-party apps.

What you can search for via Graph API, is quite limited - https://developers.facebook.com/docs/graph-api/advanced#search

(This used to include other stuff before, searching for users, etc., but most of that has since been removed.)

There is the Public Feed API - but that is not available to normal 3rd-party apps, https://developers.facebook.com/docs/public_feed/:

Access to the Public Feed API is restricted to a limited set of media publishers and usage requires prior approval by Facebook. You cannot apply to use the API at this time.


问:
Which one will give fast result in laravel eloquent?
Which eloquent statement will give a fast result?</p>

```<code>$getData = User::selectRaw('user_name')->where('user_id',1)->first();

$getData = User::where('user_id',1)->first();
</code>```

答: In this case, the difference on performance is negligible. To make the query faster, you need the field user_id to be indexed in your database.

Body:
Which eloquent statement will give a fast result?

$getData = User::selectRaw('user_name')->where('user_id',1)->first();

$getData = User::where('user_id',1)->first();


问:
neo4j sink connector - Avro - unknown magic byte
I am facing the below error.while adding the neo4j sink connector in confluent platform.

Caused by: org.apache.kafka.connect.errors.DataException:
  JsonConverter with schemas.enable requires "schema" and "payload"
  fields and may not contain additional fields. If you are trying to
  deserialize plain JSON data, set schemas.enable=false in your
  converter configuration.  at
  org.apache.kafka.connect.json.JsonConverter.toConnectData(JsonConverter.java:359)

please check the below configuration part:

```<code>curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-book/config -H "Content-Type: application/json" -d '{

    "topics": "pls.bookneo",
    "connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
    "key.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "false",
    "neo4j.server.uri": "bolt://localhost:7687",
    "neo4j.authentication.basic.username": "neo4j",
    "neo4j.authentication.basic.password": "*****"

}'
</code>```

Updated changes as follows :
curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-book/config -H "Content-Type: application/json" -d '{

```<code>"topics": "pulseTest.bookneo",
"connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
"key.converter.schema.registry.url": "http://localhost:8081",
"value.converter.schema.registry.url": "http://localhost:8081",
"key.converter": "org.apache.kafka.connect.storage.StringConverter",
"value.converter": "io.confluent.connect.avro.AvroConverter",
"key.converter.schemas.enable":"false",
"value.converter.schemas.enable":"true",
"neo4j.server.uri": "bolt://localhost:7687",
"neo4j.authentication.basic.username": "neo4j",
"neo4j.authentication.basic.password": "pulse",
"neo4j.encryption.enabled": false,
"neo4j.topic.cdc.schema": "pulseTest.bookneo"
</code>```

}'

now facing the issue :

```<code>Caused by: org.apache.kafka.connect.errors.DataException: Failed to deserialize data for topic pulseTest.bookneo to Avro:
    at io.confluent.connect.avro.AvroConverter.toConnectData(AvroConverter.java:110)
    at org.apache.kafka.connect.storage.Converter.toConnectData(Converter.java:86)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.lambda$convertAndTransformRecord$2(WorkerSinkTask.java:488)
    at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:128)
    at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:162)
    ... 13 more
Caused by: org.apache.kafka.common.errors.SerializationException: Unknown magic byte!

</code>```

Now,My connector is running properly but the node is created blank in neo4j.

curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-projectp/config -H "Content-Type: application/json" -d '{

```<code>"topics": "projectsp",
"connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schema.registry.url": "http://localhost:8081",
"value.converter.schemas.enable": false,
"key.converter":"org.apache.kafka.connect.json.JsonConverter",
"errors.tolerance": "all",
"neo4j.server.uri": "bolt://localhost:7687",
"neo4j.authentication.basic.username": "neo4j",
"neo4j.authentication.basic.password": "pulse",
"neo4j.encryption.enabled": false,
"neo4j.topic.cypher.projectsp": " MERGE (p:projects{projectname:coalesce(event.projectname,0),count:coalesce(event.count,0)})  "
</code>```

}'

this is my cypher query :
" MERGE (p:projects{projectname:coalesce(event.projectname,0),count:coalesce(event.count,0)})  "

I have attached the data coming from the topic

答:
You're using the JsonConverter in your key too, so need to specify schemas.enable there as well:

```<code>curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-book/config -H "Content-Type: application/json" -d '{
    "topics": "pls.bookneo",
    "connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
    "key.converter":"org.apache.kafka.connect.json.JsonConverter",
    "key.converter.schemas.enable": "false",
    "value.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "false",
    "neo4j.server.uri": "bolt://localhost:7687",
    "neo4j.authentication.basic.username": "neo4j",
    "neo4j.authentication.basic.password": "*****"

}'
</code>```

To learn more about converters see https://www.confluent.io/blog/kafka-connect-deep-dive-converters-serialization-explained/

Body:
I am facing the below error.while adding the neo4j sink connector in confluent platform.

Caused by: org.apache.kafka.connect.errors.DataException:
  JsonConverter with schemas.enable requires "schema" and "payload"
  fields and may not contain additional fields. If you are trying to
  deserialize plain JSON data, set schemas.enable=false in your
  converter configuration.  at
  org.apache.kafka.connect.json.JsonConverter.toConnectData(JsonConverter.java:359)

please check the below configuration part:

curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-book/config -H "Content-Type: application/json" -d '{

    "topics": "pls.bookneo",
    "connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
    "key.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "false",
    "neo4j.server.uri": "bolt://localhost:7687",
    "neo4j.authentication.basic.username": "neo4j",
    "neo4j.authentication.basic.password": "*****"

}'

Updated changes as follows :
curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-book/config -H "Content-Type: application/json" -d '{

"topics": "pulseTest.bookneo",
"connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
"key.converter.schema.registry.url": "http://localhost:8081",
"value.converter.schema.registry.url": "http://localhost:8081",
"key.converter": "org.apache.kafka.connect.storage.StringConverter",
"value.converter": "io.confluent.connect.avro.AvroConverter",
"key.converter.schemas.enable":"false",
"value.converter.schemas.enable":"true",
"neo4j.server.uri": "bolt://localhost:7687",
"neo4j.authentication.basic.username": "neo4j",
"neo4j.authentication.basic.password": "pulse",
"neo4j.encryption.enabled": false,
"neo4j.topic.cdc.schema": "pulseTest.bookneo"

}'

now facing the issue :

Caused by: org.apache.kafka.connect.errors.DataException: Failed to deserialize data for topic pulseTest.bookneo to Avro:
    at io.confluent.connect.avro.AvroConverter.toConnectData(AvroConverter.java:110)
    at org.apache.kafka.connect.storage.Converter.toConnectData(Converter.java:86)
    at org.apache.kafka.connect.runtime.WorkerSinkTask.lambda$convertAndTransformRecord$2(WorkerSinkTask.java:488)
    at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:128)
    at org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:162)
    ... 13 more
Caused by: org.apache.kafka.common.errors.SerializationException: Unknown magic byte!

Now,My connector is running properly but the node is created blank in neo4j.

curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-projectp/config -H "Content-Type: application/json" -d '{

"topics": "projectsp",
"connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schema.registry.url": "http://localhost:8081",
"value.converter.schemas.enable": false,
"key.converter":"org.apache.kafka.connect.json.JsonConverter",
"errors.tolerance": "all",
"neo4j.server.uri": "bolt://localhost:7687",
"neo4j.authentication.basic.username": "neo4j",
"neo4j.authentication.basic.password": "pulse",
"neo4j.encryption.enabled": false,
"neo4j.topic.cypher.projectsp": " MERGE (p:projects{projectname:coalesce(event.projectname,0),count:coalesce(event.count,0)})  "

}'

this is my cypher query :
" MERGE (p:projects{projectname:coalesce(event.projectname,0),count:coalesce(event.count,0)})  "

I have attached the data coming from the topic

Body:
You're using the JsonConverter in your key too, so need to specify schemas.enable there as well:

curl -X PUT http://localhost:8083/connectors/Neo4j-Sink-Connect-book/config -H "Content-Type: application/json" -d '{
    "topics": "pls.bookneo",
    "connector.class": "streams.kafka.connect.sink.Neo4jSinkConnector",
    "key.converter":"org.apache.kafka.connect.json.JsonConverter",
    "key.converter.schemas.enable": "false",
    "value.converter":"org.apache.kafka.connect.json.JsonConverter",
    "value.converter.schemas.enable": "false",
    "neo4j.server.uri": "bolt://localhost:7687",
    "neo4j.authentication.basic.username": "neo4j",
    "neo4j.authentication.basic.password": "*****"

}'

To learn more about converters see https://www.confluent.io/blog/kafka-connect-deep-dive-converters-serialization-explained/


问:
when to use tap() and when to use map() in RxJS
A the document describes the tap() with following code:

import { fromEvent } from 'rxjs';
import { tap, map } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const positions = clicks.pipe(
  tap(ev => console.log(ev)),
  map(ev => ev.clientX),
);
positions.subscribe(x => console.log(x));
```

but I do not understand why to use tap. Is it just logging. The explanation says

Map every click to the clientX position of that click, while also
logging the click event

答:
Tap

Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source

Example:

```<code>tap(value => console.log(value))
</code>```

Map

Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.

Example:

```<code>map(value => 'prefix' + value)
</code>```

Why not to use map or other operators for side effects like log

You can use map, scan and any other operator that gets a function and returns an individual result to implement side effects. This will make your code very hard to understand/debug/find bugs in the future. Provided that, in general it is not good to use side effects in pipes. Logging can be an exception if you need/want it and don't want to have lot's of subscriptions for every logging point. Therefore tap can be useful. You could adapt this to the following steps:

Try to avoid as many side effects as possible

If you need some (logging) use tap to clarify that there is an side effect

Example for how you could but should not

```<code>switchMap(value => {
  console.log(value); // Side effect 1
  const newValue = foo(value);
  console.log(newValue); // Side effect 2
  return of(newValue);
})
</code>```

Example of how you could do and should

```<code>tap(console.log), // Side effect 1
switchMap(value => of(foo(value))),
tap(console.log) // Side effect 2
</code>```

Last word: When you write initially code that brings not much of an benefit. The larget your project gets and the moment other people try to find bugs it will improve saved time a lot.

Body:
A the document describes the tap() with following code:

import { fromEvent } from 'rxjs';
import { tap, map } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const positions = clicks.pipe(
  tap(ev => console.log(ev)),
  map(ev => ev.clientX),
);
positions.subscribe(x => console.log(x));

but I do not understand why to use tap. Is it just logging. The explanation says

Map every click to the clientX position of that click, while also
logging the click event

Body:
Tap

Perform a side effect for every emission on the source Observable, but return an Observable that is identical to the source

Example:

tap(value => console.log(value))

Map

Applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.

Example:

map(value => 'prefix' + value)

Why not to use map or other operators for side effects like log

You can use map, scan and any other operator that gets a function and returns an individual result to implement side effects. This will make your code very hard to understand/debug/find bugs in the future. Provided that, in general it is not good to use side effects in pipes. Logging can be an exception if you need/want it and don't want to have lot's of subscriptions for every logging point. Therefore tap can be useful. You could adapt this to the following steps:

Try to avoid as many side effects as possible

If you need some (logging) use tap to clarify that there is an side effect

Example for how you could but should not

switchMap(value => {
  console.log(value); // Side effect 1
  const newValue = foo(value);
  console.log(newValue); // Side effect 2
  return of(newValue);
})

Example of how you could do and should

tap(console.log), // Side effect 1
switchMap(value => of(foo(value))),
tap(console.log) // Side effect 2

Last word: When you write initially code that brings not much of an benefit. The larget your project gets and the moment other people try to find bugs it will improve saved time a lot.


问:
Detect OCaml version when compiling C
I am working on some code that mixes OCaml and C, the functions caml_release_runtime_system() and caml_acquire_runtime_system() were introduced in OCaml 3.12 (they were called something else in earlier versions) but I would like to be compatible back to 3.10 if possible, is there an #ifdef I can use for that? I have had a look through the headers (in /usr/lib/ocaml/caml on my Debian system) and can't find anything that looks like it might. Thanks!

UPDATE: this is what I did

This is what I did:

```<code>#if OCAML_VERSION_MINOR >= 12
#include <caml/threads.h>
#else
#include <caml/signals.h>
#endif

#ifndef caml_acquire_runtime_system
#define caml_acquire_runtime_system caml_leave_blocking_section
#define caml_release_runtime_system caml_enter_blocking_section
#endif
</code>```

答:
caml/threads.h:

```<code>#define caml_acquire_runtime_system caml_leave_blocking_section
#define caml_release_runtime_system caml_enter_blocking_section
</code>```

So simply add that same lines to your C code (guarded with #ifndef caml_acquire_runtime_system) and spare your build system (and users) from depending on external utilities and version numbers.

Title: Detect OCaml version when compiling C

Body:
I am working on some code that mixes OCaml and C, the functions caml_release_runtime_system() and caml_acquire_runtime_system() were introduced in OCaml 3.12 (they were called something else in earlier versions) but I would like to be compatible back to 3.10 if possible, is there an #ifdef I can use for that? I have had a look through the headers (in /usr/lib/ocaml/caml on my Debian system) and can't find anything that looks like it might. Thanks!

UPDATE: this is what I did

This is what I did:

#if OCAML_VERSION_MINOR >= 12
#include <caml/threads.h>
#else
#include <caml/signals.h>
#endif

#ifndef caml_acquire_runtime_system
#define caml_acquire_runtime_system caml_leave_blocking_section
#define caml_release_runtime_system caml_enter_blocking_section
#endif

Body:
caml/threads.h:

#define caml_acquire_runtime_system caml_leave_blocking_section
#define caml_release_runtime_system caml_enter_blocking_section

So simply add that same lines to your C code (guarded with #ifndef caml_acquire_runtime_system) and spare your build system (and users) from depending on external utilities and version numbers.


问:
react filtering an object of arrays
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

```<code> this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}
</code>```

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

```<code>var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });
</code>```

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

答:
You can use Object.entries and Object.fromEntries.

```<code>const filteredObject = Object.fromEntries(
    Object.entries(searchParams)
        .filter(([key, value]) => value !== "")
);
</code>```

Will create anew object with all the keys for which the value was "" removed.

Title: react filtering an object of arrays

Body:
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

 this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

Body:
You can use Object.entries and Object.fromEntries.

const filteredObject = Object.fromEntries(
    Object.entries(searchParams)
        .filter(([key, value]) => value !== "")
);

Will create anew object with all the keys for which the value was "" removed.


问:
Converting a pandas dataframe to JSON file
I am trying to convert a pandas DataFrame to JSON file. Following image shows my data:
Screenshot of the dataset from Ms. excel

I am using the following code:

```<code>import pandas as pd

os.chdir("G:\\My Drive\\LEC dashboard\\EnergyPlus simulation files\\DEC\\Ahmedabad\\Adaptive set point\\CSV")

df = pd.read_csv('Adap_40-_0_0.1_1.5_0.6.csv')
df2 = df.filter(like = '[C](Hourly)',axis =1)
df3 = df.filter(like = '[C](Hourly:ON)',axis =1)
df4 = df.filter(like = '[%](Hourly)',axis =1)
df5 = df.filter(like = '[%](Hourly:ON)',axis =1)

df6 = pd.concat([df2,df3,df4,df5],axis=1)
df6.to_json("123.json",orient='columns')
</code>```

I the output, I am getting a dictionary in of values. However, I need a list as value.

The output I am getting: The JSON output I am getting by using above code

The out put that is desired: The output that is desired.

I have tried different orientations of json but nothing works.

答:
There is a built-in function of pandas called to_json:

```<code>df.to_json(r'Path_to_file\file_name.json')
</code>```

Take a look at the documentation if you need more specifics: https://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.to_json.html

Body:
I am trying to convert a pandas DataFrame to JSON file. Following image shows my data:
Screenshot of the dataset from Ms. excel

I am using the following code:

import pandas as pd

os.chdir("G:\\My Drive\\LEC dashboard\\EnergyPlus simulation files\\DEC\\Ahmedabad\\Adaptive set point\\CSV")

df = pd.read_csv('Adap_40-_0_0.1_1.5_0.6.csv')
df2 = df.filter(like = '[C](Hourly)',axis =1)
df3 = df.filter(like = '[C](Hourly:ON)',axis =1)
df4 = df.filter(like = '[%](Hourly)',axis =1)
df5 = df.filter(like = '[%](Hourly:ON)',axis =1)

df6 = pd.concat([df2,df3,df4,df5],axis=1)
df6.to_json("123.json",orient='columns')

I the output, I am getting a dictionary in of values. However, I need a list as value.

The output I am getting: The JSON output I am getting by using above code

The out put that is desired: The output that is desired.

I have tried different orientations of json but nothing works.

Body:
There is a built-in function of pandas called to_json:

df.to_json(r'Path_to_file\file_name.json')

Take a look at the documentation if you need more specifics: https://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.to_json.html


问:
Run two scripts simultaneously in tkinter
I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish.
Here's the code:</p>

```<code>import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")

def clicked():
     os.system('python inference.py')
     os.system('python extract_frames.py')

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()
</code>```

答:
Your code will look something like this.Its just a simple implementation.</p>

```<code>from threading import Thread
import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")
def fun1():
     os.system('python inference.py')
def fun2():
     os.system('python extract_frames.py')

def clicked():
     Thread(target = fun1).start()
     Thread(target = fun2).start()

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()
</code>```

Body:
I need two scripts two run simultaneously on click of a single button. Cannot use two buttons because the gui freezes after the first button click and waits for the first program to finish.
Here's the code:

import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")

def clicked():
     os.system('python inference.py')
     os.system('python extract_frames.py')

    # I used the subprocess approach also but it still waits for the first program to finish

    subprocess.run("python inference.py  & python extract_frames.py",shell=True)

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()

Body:
Your code will look something like this.Its just a simple implementation.

from threading import Thread
import tkinter
import os
import subprocess

window = tkinter.Tk()
window.title("GUI")
def fun1():
     os.system('python inference.py')
def fun2():
     os.system('python extract_frames.py')

def clicked():
     Thread(target = fun1).start()
     Thread(target = fun2).start()

bt = tkinter.Button(window,text="Click Here to start detecting",command=clicked).pack()

window.geometry('400x400')
window.mainloop()


问:
How to build a Docker-in-Docker image for Docker EE on Windows?
I'm planning to build Docker EE images in dynamic Jenkins agent running in Kubernetes pods and therefore need either

a Docker image providing both the Jenkins Agent functionality and Docker. Currently I'm using jenkins/jnlp-agent:latest-windows as image to run on a Windows LTSC node pool which seems to provide the Jenkins agent functionality adequately or

a way to extend jenkins/jnlp-agent:latest-windows so that it allows to run Docker as well. My naive approach

```<code>FROM jenkins/jnlp-agent:latest-windows
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'SilentlyContinue'; $ProgressPreference = 'SilentlyContinue';"]

USER ContainerAdministrator

COPY install-docker.ps1 .
RUN ./install-docker.ps1
RUN Remove-Item install-docker.ps1
</code>```

with install-docker.ps1 containing

```<code>Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction Continue
Install-Module -Name DockerMsftProvider -Repository PSGallery -Force -ErrorAction Continue
Install-Package -Force -ErrorAction Continue -Name docker -ProviderName DockerMsftProvider
</code>```

following https://learn.microsoft.com/en-us/virtualization/windowscontainers/quick-start/set-up-environment?tabs=Windows-Server fails due to

```<code>> Start-Service Docker
Start-Service : Failed to start service 'Docker Engine (Docker)'.
At line:1 char:1
+ Start-Service Docker
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand
</code>```

or

a Docker-in-Docker Container for Docker EE on Windows which exposes a Docker TCP socket and allows the Jenkins agent container to connect to it.

The setup should run on Windows Server 2019 node pools provided by Google Kubernetes Engine. I'm aware that Windows Pools are beta currently.

In case someone has an idea how to get the second approach working, it'd still be necessary to run the setup as user jenkins rather than container administrator in order to increase security.

答:
Try to create a service in the Dockerfile.

```<code>RUN powershell New-Service -Name “RSDataQualityWorkerPool” -BinaryPathName “C:\WWW\WinServices\RSDataQualityWorkerPool\RSDataQualityWorkerPool.exe”
</code>```

Start it in the running container.

```<code>Start-Service -Name “RSDataQualityWorkerPool”
</code>```

Take a look here: windows-jnlp-jenkins, docker-service-on-windows.

Body:
I'm planning to build Docker EE images in dynamic Jenkins agent running in Kubernetes pods and therefore need either

a Docker image providing both the Jenkins Agent functionality and Docker. Currently I'm using jenkins/jnlp-agent:latest-windows as image to run on a Windows LTSC node pool which seems to provide the Jenkins agent functionality adequately or

a way to extend jenkins/jnlp-agent:latest-windows so that it allows to run Docker as well. My naive approach

FROM jenkins/jnlp-agent:latest-windows
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'SilentlyContinue'; $ProgressPreference = 'SilentlyContinue';"]

USER ContainerAdministrator

COPY install-docker.ps1 .
RUN ./install-docker.ps1
RUN Remove-Item install-docker.ps1

with install-docker.ps1 containing

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -ErrorAction Continue
Install-Module -Name DockerMsftProvider -Repository PSGallery -Force -ErrorAction Continue
Install-Package -Force -ErrorAction Continue -Name docker -ProviderName DockerMsftProvider

following https://learn.microsoft.com/en-us/virtualization/windowscontainers/quick-start/set-up-environment?tabs=Windows-Server fails due to

> Start-Service Docker
Start-Service : Failed to start service 'Docker Engine (Docker)'.
At line:1 char:1
+ Start-Service Docker
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
   ServiceCommandException
    + FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand

or

a Docker-in-Docker Container for Docker EE on Windows which exposes a Docker TCP socket and allows the Jenkins agent container to connect to it.

The setup should run on Windows Server 2019 node pools provided by Google Kubernetes Engine. I'm aware that Windows Pools are beta currently.

In case someone has an idea how to get the second approach working, it'd still be necessary to run the setup as user jenkins rather than container administrator in order to increase security.

Body:
Try to create a service in the Dockerfile.

RUN powershell New-Service -Name “RSDataQualityWorkerPool” -BinaryPathName “C:\WWW\WinServices\RSDataQualityWorkerPool\RSDataQualityWorkerPool.exe”

Start it in the running container.

Start-Service -Name “RSDataQualityWorkerPool”

Take a look here: windows-jnlp-jenkins, docker-service-on-windows.


问:
React Navigation: StackNavigator transition for Android
I am using this library https://reactnavigation.org/docs/intro/ to build android by react-native. I can make the navigation happens on android device but how I can make the screen slide in from the right and fade in from the left. It seems that this behaviour happens on iOS device but not in Android. Is there any animation configuration for android app?

Please see below animation. This is recorded in iOS.

答:
you need to import StackViewTransitionConfigs from 'react-navigation-stack'
then, override the transitionConfing function.</p>

```<code>const myStack = createStackNavigator({
    Screen1,
    Screen2,
    Screen3
},{
    transitionConfig: () => StackViewTransitionConfigs.SlideFromRightIOS
}
</code>```

Body:
you need to import StackViewTransitionConfigs from 'react-navigation-stack'
then, override the transitionConfing function.

const myStack = createStackNavigator({
    Screen1,
    Screen2,
    Screen3
},{
    transitionConfig: () => StackViewTransitionConfigs.SlideFromRightIOS
}


问:
Make elements of container fill height of container by wrapping
I have an issue with trying to make the items within a container take up the space the way i want. The main issue seems to be that flex box and css grid are made adjust to changes in width and not height, where as i need the opposite behaviour.This is basically what I want my elements to do

Check the desired effect here.

I have tried using both flex box and css grid.
This is my current code, also containing some residue of my previous attempt. It just makes the images display in their actual size.
The media-container's height is changed via javascript.

.display-img {
  padding:0px;
  margin-top:-4px;
  margin-bottom:-4px;
  flex:0 1 auto;
  height:auto;
}

.media-container{
  width: auto;
  height:800px;
  display:flex;
  //grid-template-rows: repeat(auto-fit,auto);
  //grid-template-columns: repeat(auto-fit,minmax(200px,0.5fr));
  flex-direction: row;
  align-items: flex-start;
  flex-wrap: wrap;
  visibility: hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="media-container">
  <img class="display-img" src="assets/projects/feierlichkeiten/23.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/22.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/21.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/20.png"></img>
  <img class="display-img" src="assets/projects/feierlichkeiten/19.png"></img>
</div></code>```

Thanks to everyone who has some idea.

答:
For your desired effect, lets use a container with a media 'child', where each child have its content.

```<code><div class="media-container">
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/160">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/160/90">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/150/40">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/160/100">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/100/290">
    </div>
</div>
</code>```

The rule youre searching for  was the 'flex-wrap: wrap'

```<code>.media-container{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    width: 100%;
}

.media-container .media{
    width: 33%;
}
</code>```

You can play with values and match the more suitable for you.

And please use Webpack for css prefixes

Body:
I have an issue with trying to make the items within a container take up the space the way i want. The main issue seems to be that flex box and css grid are made adjust to changes in width and not height, where as i need the opposite behaviour.This is basically what I want my elements to do

Check the desired effect here.

I have tried using both flex box and css grid.
This is my current code, also containing some residue of my previous attempt. It just makes the images display in their actual size.
The media-container's height is changed via javascript.

.display-img {
  padding:0px;
  margin-top:-4px;
  margin-bottom:-4px;
  flex:0 1 auto;
  height:auto;
}

.media-container{
  width: auto;
  height:800px;
  display:flex;
  //grid-template-rows: repeat(auto-fit,auto);
  //grid-template-columns: repeat(auto-fit,minmax(200px,0.5fr));
  flex-direction: row;
  align-items: flex-start;
  flex-wrap: wrap;
  visibility: hidden;
}

Thanks to everyone who has some idea.

Body:
For your desired effect, lets use a container with a media 'child', where each child have its content.

<div class="media-container">
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/160">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/160/90">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/150/40">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/160/100">
    </div>
    <div class='media'>
        <img class="display-img" src="https://picsum.photos/100/290">
    </div>
</div>

The rule youre searching for  was the 'flex-wrap: wrap'

.media-container{
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    width: 100%;
}

.media-container .media{
    width: 33%;
}

You can play with values and match the more suitable for you.

And please use Webpack for css prefixes


问:
Laravel add error message to validator in custom form request
I have a custom form request where I do some extra validation logic and I want to add an error if my logic fails but I get this error:

Call to a member function errors() on null

Here is my custom Request:

```<code>if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
    if (
        !Auth::attempt([
            'email' => $this->get('email'),
            'password' => $this->get('current_password'),
            'status' => 'pending'
        ])
    ) {
        $this->validator->errors()->add('current_password', 'Something is wrong with this field!');
    }
}

return [
    'first_name' => 'required|min:1|max:190',
];
</code>```

EDIT complete class

```<code>class ProfileRequest extends FormRequest
{
    public function authorize()
    {
        return Auth::check();
    }

    public function rules()
    {
        if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
            if (
                !Auth::attempt([
                'email' => $this->get('email'),
                'password' => $this->get('current_password'),
                'status' => 'pending'
                ])
            ) {
                $this->validator->getMessageBag()->add('current_password', 'Something is wrong with this field!');
            }
        }

        return [
            'first_name'       => 'required|min:1|max:190',
        ];
    }
}
</code>```

答:
I think you need to add the hook withValidator as laravel doc suggested.

```<code>public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}
</code>```

Body:
I have a custom form request where I do some extra validation logic and I want to add an error if my logic fails but I get this error:

Call to a member function errors() on null

Here is my custom Request:

if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
    if (
        !Auth::attempt([
            'email' => $this->get('email'),
            'password' => $this->get('current_password'),
            'status' => 'pending'
        ])
    ) {
        $this->validator->errors()->add('current_password', 'Something is wrong with this field!');
    }
}

return [
    'first_name' => 'required|min:1|max:190',
];

EDIT complete class

class ProfileRequest extends FormRequest
{
    public function authorize()
    {
        return Auth::check();
    }

    public function rules()
    {
        if (!empty($this->get('new_password')) && !empty($this->get('current_password'))) {
            if (
                !Auth::attempt([
                'email' => $this->get('email'),
                'password' => $this->get('current_password'),
                'status' => 'pending'
                ])
            ) {
                $this->validator->getMessageBag()->add('current_password', 'Something is wrong with this field!');
            }
        }

        return [
            'first_name'       => 'required|min:1|max:190',
        ];
    }
}

Body:
I think you need to add the hook withValidator as laravel doc suggested.

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}