问:
pass a whole string as argument between python and bash
```<code>cat /tmp/testme
#!/usr/bin/env  python3
import sys
print(sys.argv[0])
print(sys.argv[1])
</code>```

It is simple ,just to print argument passed from bash to python.

```<code>x="i am a book"
/tmp/testme "i am a book"
/tmp/testme
i am a book
</code>```

The string i am a book can passed into python program as a whole string.

```<code>/tmp/testme  ${x}
/tmp/testme
i
echo ${x}
i am a book
</code>```

Why python can't deal with ${x} i am a book as a whole,it get only the first character in the string as argument.

答:
When you execute the line /tmp/testme  ${x}, bash will expand the contents of x, and will ultimately execute /tmp/testme i am a book. Therefore, sys.argv will become ['/tmp/testme', 'i', 'am', 'a', 'book'].

To achieve the desired behaviour, ${x} should be quoted, like "${x}". Then bash will execute /tmp/testme 'i am a book'.

Here is an example with a bash script. With set -x, bash will print commands and their arguments as they are executed, after all variables have been evaluated.

```<code>$ cat testme
#!/usr/bin/env python3
import sys
print(sys.argv)

$ cat exampleBashScript.sh
#!/usr/bin/env bash
set -x

x="i am a book"
./testme ${x}
./testme "${x}"

$ ./exampleBashScript.sh
+ x='i am a book'
+ ./testme i am a book
['./testme', 'i', 'am', 'a', 'book']
+ ./testme 'i am a book'
['./testme', 'i am a book']
</code>```

Body:
cat /tmp/testme
#!/usr/bin/env  python3
import sys
print(sys.argv[0])
print(sys.argv[1])

It is simple ,just to print argument passed from bash to python.

x="i am a book"
/tmp/testme "i am a book"
/tmp/testme
i am a book

The string i am a book can passed into python program as a whole string.

/tmp/testme  ${x}
/tmp/testme
i
echo ${x}
i am a book

Why python can't deal with ${x} i am a book as a whole,it get only the first character in the string as argument.

Body:
When you execute the line /tmp/testme  ${x}, bash will expand the contents of x, and will ultimately execute /tmp/testme i am a book. Therefore, sys.argv will become ['/tmp/testme', 'i', 'am', 'a', 'book'].

To achieve the desired behaviour, ${x} should be quoted, like "${x}". Then bash will execute /tmp/testme 'i am a book'.

Here is an example with a bash script. With set -x, bash will print commands and their arguments as they are executed, after all variables have been evaluated.

$ cat testme
#!/usr/bin/env python3
import sys
print(sys.argv)

$ cat exampleBashScript.sh
#!/usr/bin/env bash
set -x

x="i am a book"
./testme ${x}
./testme "${x}"

$ ./exampleBashScript.sh
+ x='i am a book'
+ ./testme i am a book
['./testme', 'i', 'am', 'a', 'book']
+ ./testme 'i am a book'
['./testme', 'i am a book']


来源: stackexchange

问:
How to edit private member of vector in a Class function?
I was working on my work, and it was to input some scores and print out scores, rankings, and pass/fail. I was working with C++ 17, and there was an error on editing my rank.

I've tried to put my vector in a 'setRankPass' function on header file, but it doesn't work at all.

header file

```<code>#pragma once
#include <vector>

class Score {
public:
    Score(int score)
        : _score{ score } {
    }
    int getScore() {
        return _score;
    }
    int getRank() {
        return _rank;
    }
    bool getPass() {
        return _pass;
    }
    void setRankPass(const std::vector<int>* scores, int size) {
        for (int i{ 0 }; i < size; i++) {
            _rank = rank[i];
        }

        double average = static_cast<double>(_rank) / size * 100;
        if (average <= 10) {
            _pass = true;
        }
        else {
            _pass = false;
        }
    }
private:
    int _score{ 0 };
    int _rank{ 0 };
    bool _pass{ false };
};
</code>```

cpp file

```<code>#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include "Score.h"
using namespace std;
    int main() {
        int enter{ 0 };
        int counter{ 0 };
        vector<Score> v;
        vector<int> s;
        while (enter != -1) {
            cout << "Enter score(-1 to quit): ";
            cin >> enter;
            if (enter == -1)
                break;
            v.push_back(Score(enter));
            counter++;
        }
        int cnt;
        vector<int>rank;
        for (int i = 0; i < v.size(); i++) {
            cnt = 0;
            for (int j = 0; j < v.size(); j++) {
                if (v[i].getScore() < v[j].getScore()) {
                    cnt++;
                }
            }
            rank.push_back(cnt + 1);
        }
        cout << endl;

        for (int a{ 0 }; a < v.size(); a++) {
            v[a].setRankPass(&rank, counter);
        }

        for (int k{ 0 }; k < v.size(); k++) {
            cout << setw(5) << v[k].getScore() << setw(5) << v[k].getRank() << setw(5) << v[k].getPass() << endl;
        }
        return 0;
    }
</code>```

I had some error on _rank = rank[i]. It was error E0441 There is no argument list for class template "std::rank" and Error C2065 'rank': Undeclared identifier. I expected that instances on vector rank would be assigned to each _rank. How can I solve the problem?

答:
You have no rank vector variable in this scope:

```<code>void setRankPass(const std::vector<int>* scores, int size) {
    for (int i{ 0 }; i < size; i++) {
        _rank = rank[i];
    }

    double average = static_cast<double>(_rank) / size * 100;
    if (average <= 10) {
        _pass = true;
    }
    else {
        _pass = false;
    }
}
</code>```

You call the function like this:

```<code>for (int a{ 0 }; a < v.size(); a++) {
    v[a].setRankPass(&rank, counter);
}
</code>```

But the variable you have in the serRankPass scope is scores. I assume you meant to do something like that:

```<code>void setRankPass(const std::vector<int> &rank, int size) { // Pay attention to & and not * (reference instead of pointer)
    _rank = 0; // initialize to 0 and not junk value
    for (int i{ 0 }; i < size; i++) {
        _rank += rank[i]; // += instead of = (add and not overwrite)
    }

    double average = static_cast<double>(_rank) / size * 100;
    if (average <= 10) {
        _pass = true;
    }
    else {
        _pass = false;
    }
}
</code>```

Pay attention that after this fix, you'll have to change the following line inside your main:

```<code>v[a].setRankPass(&rank, counter);
</code>```

to this line:

```<code>v[a].setRankPass(rank, counter);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was working on my work, and it was to input some scores and print out scores, rankings, and pass/fail. I was working with C++ 17, and there was an error on editing my rank.

I've tried to put my vector in a 'setRankPass' function on header file, but it doesn't work at all.

header file

#pragma once
#include <vector>

class Score {
public:
    Score(int score)
        : _score{ score } {
    }
    int getScore() {
        return _score;
    }
    int getRank() {
        return _rank;
    }
    bool getPass() {
        return _pass;
    }
    void setRankPass(const std::vector<int>* scores, int size) {
        for (int i{ 0 }; i < size; i++) {
            _rank = rank[i];
        }

        double average = static_cast<double>(_rank) / size * 100;
        if (average <= 10) {
            _pass = true;
        }
        else {
            _pass = false;
        }
    }
private:
    int _score{ 0 };
    int _rank{ 0 };
    bool _pass{ false };
};

cpp file

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include "Score.h"
using namespace std;
    int main() {
        int enter{ 0 };
        int counter{ 0 };
        vector<Score> v;
        vector<int> s;
        while (enter != -1) {
            cout << "Enter score(-1 to quit): ";
            cin >> enter;
            if (enter == -1)
                break;
            v.push_back(Score(enter));
            counter++;
        }
        int cnt;
        vector<int>rank;
        for (int i = 0; i < v.size(); i++) {
            cnt = 0;
            for (int j = 0; j < v.size(); j++) {
                if (v[i].getScore() < v[j].getScore()) {
                    cnt++;
                }
            }
            rank.push_back(cnt + 1);
        }
        cout << endl;

        for (int a{ 0 }; a < v.size(); a++) {
            v[a].setRankPass(&rank, counter);
        }

        for (int k{ 0 }; k < v.size(); k++) {
            cout << setw(5) << v[k].getScore() << setw(5) << v[k].getRank() << setw(5) << v[k].getPass() << endl;
        }
        return 0;
    }

I had some error on _rank = rank[i]. It was error E0441 There is no argument list for class template "std::rank" and Error C2065 'rank': Undeclared identifier. I expected that instances on vector rank would be assigned to each _rank. How can I solve the problem?

Body:
You have no rank vector variable in this scope:

void setRankPass(const std::vector<int>* scores, int size) {
    for (int i{ 0 }; i < size; i++) {
        _rank = rank[i];
    }

    double average = static_cast<double>(_rank) / size * 100;
    if (average <= 10) {
        _pass = true;
    }
    else {
        _pass = false;
    }
}

You call the function like this:

for (int a{ 0 }; a < v.size(); a++) {
    v[a].setRankPass(&rank, counter);
}

But the variable you have in the serRankPass scope is scores. I assume you meant to do something like that:

void setRankPass(const std::vector<int> &rank, int size) { // Pay attention to & and not * (reference instead of pointer)
    _rank = 0; // initialize to 0 and not junk value
    for (int i{ 0 }; i < size; i++) {
        _rank += rank[i]; // += instead of = (add and not overwrite)
    }

    double average = static_cast<double>(_rank) / size * 100;
    if (average <= 10) {
        _pass = true;
    }
    else {
        _pass = false;
    }
}

Pay attention that after this fix, you'll have to change the following line inside your main:

v[a].setRankPass(&rank, counter);

to this line:

v[a].setRankPass(rank, counter);


问:
Click event on a slider goes at the end of the array
I am trying to create a simple slider using javascript.
So far, here is my code :

html:

```<code>  <div class="carousel-container">

    <div class="slides-container">
      <div class="slide">
        <img src="assets/images/image-1.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-3.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-2.jpg" alt="">
      </div>
      <div class="slide">
        <img src="assets/images/image-3.jpg" alt="">
      </div>
    </div>

  </div>

  <div class="carousel-nav">
    <button class="button-previous">Previous</button>
    <button class="button-next">Next</button>
  </div>
</code>```

Js :

```<code>    const slides = document.querySelectorAll('.slide')
    const slidesContainer = document.querySelector('.slides-container')
    const slidesCount = slides.length
    const slideWidth = slides[0].clientWidth

    const prevButton = document.querySelector('.button-previous')
    const nextButton = document.querySelector('.button-next')

    function nextSlide(slide) {
      for (slide = 0; slide < slidesCount; slide++) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
      }
    }

    nextButton.addEventListener('click', function() {
      nextSlide()
    })
</code>```

The issue I have is that when I click on the next button, the slider goes all the way at the end of my array, thus skipping all the images in between.

What would be the best way to have my for loop stop at each image and go again when the button is clicked?

答:
I might not exactly understand what you try to do or why you intend to use a for loop but if it's just about selecting the next slide you may go with this:

```<code>var currentSlide = 0;

function nextSlide() {
  //make sure currentSlide is in range
  currentSlide = (currentSlide >= slidesCount) ? 0 : ++currentSlide;

  slidesContainer.style.transform = 'translateX(-' + (currentSlide * slideWidth) + 'px)';
}

nextButton.addEventListener('click', nextSlide);
</code>```

or a little bit more flexible:

```<code>var currentSlide = 0;

function nextSlide(direction /* Number */) {
  if(!direction) direction = 1; //default

  setSlide(currentSlide + direction % slidesCount);
}

function setSlide(index) {
  if(index === currentSlide) return;

  //make sure index is in range
  while(index >= slidesCount) index -= slidesCount;
  while(index < 0) index += slidesCount;

  slidesContainer.style.transform = 'translateX(-' + (index * slideWidth) + 'px)';

  currentSlide = index;
}

nextButton.addEventListener('click', function() {
  nextSlide(this.dataset["direction"]); //by using data you don't need two different button classes
});
</code>```

But if you insist on using a loop I'm afraid to tell that it's inappropriate in this case since the calculation of translateX is based on a given value.

Body:
I am trying to create a simple slider using javascript.
So far, here is my code :

html:

    <button class="button-previous">Previous</button>
    <button class="button-next">Next</button>

Js :

    const slides = document.querySelectorAll('.slide')
    const slidesContainer = document.querySelector('.slides-container')
    const slidesCount = slides.length
    const slideWidth = slides[0].clientWidth

    const prevButton = document.querySelector('.button-previous')
    const nextButton = document.querySelector('.button-next')

    function nextSlide(slide) {
      for (slide = 0; slide < slidesCount; slide++) {
        slidesContainer.style.transform = 'translateX(-' + (slide * slideWidth) + 'px)'
      }
    }

    nextButton.addEventListener('click', function() {
      nextSlide()
    })

The issue I have is that when I click on the next button, the slider goes all the way at the end of my array, thus skipping all the images in between.

What would be the best way to have my for loop stop at each image and go again when the button is clicked?

Body:
I might not exactly understand what you try to do or why you intend to use a for loop but if it's just about selecting the next slide you may go with this:

var currentSlide = 0;

function nextSlide() {
  //make sure currentSlide is in range
  currentSlide = (currentSlide >= slidesCount) ? 0 : ++currentSlide;

  slidesContainer.style.transform = 'translateX(-' + (currentSlide * slideWidth) + 'px)';
}

nextButton.addEventListener('click', nextSlide);

or a little bit more flexible:

var currentSlide = 0;

function nextSlide(direction /* Number */) {
  if(!direction) direction = 1; //default

  setSlide(currentSlide + direction % slidesCount);
}

function setSlide(index) {
  if(index === currentSlide) return;

  //make sure index is in range
  while(index >= slidesCount) index -= slidesCount;
  while(index < 0) index += slidesCount;

  slidesContainer.style.transform = 'translateX(-' + (index * slideWidth) + 'px)';

  currentSlide = index;
}

nextButton.addEventListener('click', function() {
  nextSlide(this.dataset["direction"]); //by using data you don't need two different button classes
});

But if you insist on using a loop I'm afraid to tell that it's inappropriate in this case since the calculation of translateX is based on a given value.


问:
Firebase cloud functions ts2532,7005
I have been watching Cloud Functions videos
and I still got issues so I decided to ask here

and I have already checked this out link: Firebase Cloud Functions Object possibly 'undefined'

but the problem is still not working

first of all, I do not want to delete "strict mode" in tsconfig.json

here is my code

```<code>export const onBostonWeatherUpdate =
functions.firestore.document("cities-weather/boston-ma-
us").onUpdate(change => {
if (change.after) {
const after = change.after.data()
const payload = {
    data: {
        temp: String(after.temp),
        conditions : after.conditions
    }
}
return admin.messaging().sendToTopic("weather_boston-ma-us", payload)
.catch(error =>
    console.error("FCM failed", error))
}
else{
    return null
}
})
</code>```

this makes ts(2532) Object is possibly 'undefined'.
and I do not want to use "after!" either because what if it`s really undefined in some case

and

```<code>.then(citySnapshots => {
    const results = []
    citySnapshots.forEach(citySnap => {
        const data = citySnap.data()
        results.push(data)
    })
    response.send(results)
})
</code>```

this makes ts(7034) Variable 'results' implicitly has an 'any[]' type.

I really have been stuck for this for long time

now please somebody help me

答:
On this line:

```<code>const after = change.after.data()
</code>```

data() can return undefined if the snapshot doesn't exist.  You need to check for that case before using after.

Title: Firebase cloud functions ts2532,7005

Body:
I have been watching Cloud Functions videos
and I still got issues so I decided to ask here

and I have already checked this out link: Firebase Cloud Functions Object possibly 'undefined'

but the problem is still not working

first of all, I do not want to delete "strict mode" in tsconfig.json

here is my code

export const onBostonWeatherUpdate =
functions.firestore.document("cities-weather/boston-ma-
us").onUpdate(change => {
if (change.after) {
const after = change.after.data()
const payload = {
    data: {
        temp: String(after.temp),
        conditions : after.conditions
    }
}
return admin.messaging().sendToTopic("weather_boston-ma-us", payload)
.catch(error =>
    console.error("FCM failed", error))
}
else{
    return null
}
})

this makes ts(2532) Object is possibly 'undefined'.
and I do not want to use "after!" either because what if it`s really undefined in some case

and

.then(citySnapshots => {
    const results = []
    citySnapshots.forEach(citySnap => {
        const data = citySnap.data()
        results.push(data)
    })
    response.send(results)
})

this makes ts(7034) Variable 'results' implicitly has an 'any[]' type.

I really have been stuck for this for long time

now please somebody help me

Body:
On this line:

const after = change.after.data()

data() can return undefined if the snapshot doesn't exist.  You need to check for that case before using after.


问:
Exception: Illuminate \ Broadcasting \ BroadcastException No message in PusherBroadcaster.php:119
Laravel 5.8

I am new to this whole pusher functionality and I've been following this tutorial and trying it out,

Create Web Notifications Using Laravel and Pusher Channels.

I've followed it step-by-step and when I get to the step to manually test the event by visiting the test url, I receive the following exception:

Illuminate \ Broadcasting \ BroadcastException
  No message

C:\wamp\www\ares\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php

Here is the code:

```<code>    $response = $this->pusher->trigger(
        $this->formatChannels($channels), $event, $payload, $socket, true
    );

    if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
        || $response === true) {
        return;
    }

    throw new BroadcastException( // <-- Exception at this line
        is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
    );
}

/**
 * Get the Pusher SDK instance.
 *
 * @return \Pusher\Pusher
 */
public function getPusher()
{
    return $this->pusher;
}
}
</code>```

I've looked at a few other stack overflow articles which talk about changing encrypted: true to encrypted: false but that does not seem to affect anything.

答:
I started working on Laravel 4 days ago and I came across this same problem when I was implementing a real-time chat application. After searching for many days, I discovered that this may vary depending on the version of Laravel you are running. If it is 5.8, you can fix this by adding the following code in the pusher.options array of the file config/broadcasting.php:

```<code>'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ],
</code>```

After adding this , your pusher array in the config/broadcasting.php should look like this.

```<code>'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true,
            'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ],
        ],
    ],
</code>```

You can then run php artisan config:cache(which may not be necessary in some cases) and finally run php artisan serve.You can consult your app in the pusher website and see the events you receive after sending your messages.
Hope it helps!!

Body:
Laravel 5.8

I am new to this whole pusher functionality and I've been following this tutorial and trying it out,

Create Web Notifications Using Laravel and Pusher Channels.

I've followed it step-by-step and when I get to the step to manually test the event by visiting the test url, I receive the following exception:

Illuminate \ Broadcasting \ BroadcastException
  No message

C:\wamp\www\ares\vendor\laravel\framework\src\Illuminate\Broadcasting\Broadcasters\PusherBroadcaster.php

Here is the code:

    $response = $this->pusher->trigger(
        $this->formatChannels($channels), $event, $payload, $socket, true
    );

    if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
        || $response === true) {
        return;
    }

    throw new BroadcastException( // <-- Exception at this line
        is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
    );
}

/**
 * Get the Pusher SDK instance.
 *
 * @return \Pusher\Pusher
 */
public function getPusher()
{
    return $this->pusher;
}
}

I've looked at a few other stack overflow articles which talk about changing encrypted: true to encrypted: false but that does not seem to affect anything.

Body:
I started working on Laravel 4 days ago and I came across this same problem when I was implementing a real-time chat application. After searching for many days, I discovered that this may vary depending on the version of Laravel you are running. If it is 5.8, you can fix this by adding the following code in the pusher.options array of the file config/broadcasting.php:

'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ],

After adding this , your pusher array in the config/broadcasting.php should look like this.

'pusher' => [
        'driver' => 'pusher',
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'app_id' => env('PUSHER_APP_ID'),
        'options' => [
            'cluster' => env('PUSHER_APP_CLUSTER'),
            'encrypted' => true,
            'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ],
        ],
    ],

You can then run php artisan config:cache(which may not be necessary in some cases) and finally run php artisan serve.You can consult your app in the pusher website and see the events you receive after sending your messages.
Hope it helps!!


问:
MySQL query doesn't work anymore, probably wrong syntax
I have a problem with MySQL syntax I mean the query I am using did work fine before refactoring a function, program is compiling successfully... just a query doesn't work.

I've tried to play with quotation marks and apostrophes but it's still doesn't work.
This is my query:

```<code>string add_query = "INSERT INTO `table`(
    `col1`, `col2`, `col3`, `col4`, `col5`, `col6`, `col7`, `col8`, `col9`,
    `col10`, `col11`, `col12`, `col13`, `col14`, `col15`, `col16`, `col17`,
    `col18`, `col19`, `col20`, `col21`, `col22`)
    VALUES (
    NULL, '" + var1 + "', '" + var2 + "', '" + var3 + "', '" + var4 + "', '" +
    var5 + "', '" + var6 + "', '" + var7 + "', 0, NULL, NULL, '" + var8 + "', '" +
    var9 + "', '" + var10 + "', '" + var11 + "', '" + var12 + "', '" + var13 +
    "', '" + var14 + "', '" + var15 + "', '" + var16 + "','" + var17 + "', '" +
    var18 + "');";
</code>```

I've got just this error:

```<code>Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1
</code>```

I don't have any idea how to fix it.

All help or any idea is welcome.
Sorry for bad english, it's my second language.

//EDIT
This is my cout which works perfectly in MySQL Workbench but not through my program:

```<code>INSERT INTO `table`(`col1`, `col2`, `col3`, `col4`, `col5`,
                    `col6`, `col7`, `col8`,  `col9`, `col10`,
                    `col11`, `col12`, `col13`, `col14`, `col15`,
                    `col16`, `col17`, `col18`, `col19`, `col20`,
                    `col21`, `col22`)
VALUES (NULL, 'var1', 'var2', 'var3', 'var4', 'var5', '',
       'var6', 0, NULL, NULL,  'var7', 'var8', 'var9', ' ',
       'var10', 'var11',    'var12', 'var13', 'var14', 'var15', 'var16');
</code>```

答:
There are multiple problems with the construction of the initial string, I'm not sure if the code included in the question is exactly the same as is in your program.

This program:

```<code>#include <iostream>

int main()
{
    std::string var1 = "var1",
            var2 = "var2",
            var3 = "var3",
            var4 = "var4",
            var5 = "var5",
            var6 = "var6",
            var7 = "var7",
            var8 = "var8",
            var9 = "var9",
            var10 = "var10",
            var11 = "var11",
            var12 = "var12",
            var13 = "var13",
            var14 = "var14",
            var15 = "var15",
            var16 = "var16",
            var17 = "var17",
            var18 = "var18";
    std::string add_query = "INSERT INTO `table`(\
    `row1`, `row2`, `row3`, `row4`, `row5`, `row6`, `row7`, `row8`, `row9`,\
    `row10`, `row11`, `row12`, `row13`, `row14`, `row15`, `row16`, `row17`,\
    `row18`, `row19`, `row20`, `row21`, `row22`)\
    VALUES ( NULL, '" + var1 + "', '" + var2 + "', '" + var3 + "', '" + var4 + "', '" +
    var5 + "', '" + var6 + "', '" + var7 + "', 0, NULL, NULL, '" + var8 + "', '" +
    var9 + "', '" + var10 + "', '" + var11 + "', '" + var12 + "', '" + var13 +
    "', '" + var14 + "', '" + var15 + "', '" + var16 + "','" + var17 + "', '" +
    var18 + "');";

    std::cout << add_query << '\n';
    return 0;
}
</code>```

Produces this output:

```<code>INSERT INTO `table`(    `row1`, `row2`, `row3`, `row4`, `row5`, `row6`, `row7`, `row8`, `row9`,    `row10`, `row11`, `row12`, `row13`, `row14`, `row15`, `row16`, `row17`,    `row18`, `row19`, `row20`, `row21`, `row22`)    VALUES ( NULL, 'var1', 'var2', 'var3', 'var4', 'var5', 'var6', 'var7', 0, NULL, NULL, 'var8', 'var9', 'var10', 'var11', 'var12', 'var13', 'var14', 'var15', 'var16','var17', 'var18');
</code>```

which seems to be well formed SQL, though the final semicolon is not required by some APIs.

Body:
I have a problem with MySQL syntax I mean the query I am using did work fine before refactoring a function, program is compiling successfully... just a query doesn't work.

I've tried to play with quotation marks and apostrophes but it's still doesn't work.
This is my query:

string add_query = "INSERT INTO `table`(
    `col1`, `col2`, `col3`, `col4`, `col5`, `col6`, `col7`, `col8`, `col9`,
    `col10`, `col11`, `col12`, `col13`, `col14`, `col15`, `col16`, `col17`,
    `col18`, `col19`, `col20`, `col21`, `col22`)
    VALUES (
    NULL, '" + var1 + "', '" + var2 + "', '" + var3 + "', '" + var4 + "', '" +
    var5 + "', '" + var6 + "', '" + var7 + "', 0, NULL, NULL, '" + var8 + "', '" +
    var9 + "', '" + var10 + "', '" + var11 + "', '" + var12 + "', '" + var13 +
    "', '" + var14 + "', '" + var15 + "', '" + var16 + "','" + var17 + "', '" +
    var18 + "');";

I've got just this error:

Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''' at line 1

I don't have any idea how to fix it.

All help or any idea is welcome.
Sorry for bad english, it's my second language.

//EDIT
This is my cout which works perfectly in MySQL Workbench but not through my program:

INSERT INTO `table`(`col1`, `col2`, `col3`, `col4`, `col5`,
                    `col6`, `col7`, `col8`,  `col9`, `col10`,
                    `col11`, `col12`, `col13`, `col14`, `col15`,
                    `col16`, `col17`, `col18`, `col19`, `col20`,
                    `col21`, `col22`)
VALUES (NULL, 'var1', 'var2', 'var3', 'var4', 'var5', '',
       'var6', 0, NULL, NULL,  'var7', 'var8', 'var9', ' ',
       'var10', 'var11',    'var12', 'var13', 'var14', 'var15', 'var16');

Body:
There are multiple problems with the construction of the initial string, I'm not sure if the code included in the question is exactly the same as is in your program.

This program:

#include <iostream>

int main()
{
    std::string var1 = "var1",
            var2 = "var2",
            var3 = "var3",
            var4 = "var4",
            var5 = "var5",
            var6 = "var6",
            var7 = "var7",
            var8 = "var8",
            var9 = "var9",
            var10 = "var10",
            var11 = "var11",
            var12 = "var12",
            var13 = "var13",
            var14 = "var14",
            var15 = "var15",
            var16 = "var16",
            var17 = "var17",
            var18 = "var18";
    std::string add_query = "INSERT INTO `table`(\
    `row1`, `row2`, `row3`, `row4`, `row5`, `row6`, `row7`, `row8`, `row9`,\
    `row10`, `row11`, `row12`, `row13`, `row14`, `row15`, `row16`, `row17`,\
    `row18`, `row19`, `row20`, `row21`, `row22`)\
    VALUES ( NULL, '" + var1 + "', '" + var2 + "', '" + var3 + "', '" + var4 + "', '" +
    var5 + "', '" + var6 + "', '" + var7 + "', 0, NULL, NULL, '" + var8 + "', '" +
    var9 + "', '" + var10 + "', '" + var11 + "', '" + var12 + "', '" + var13 +
    "', '" + var14 + "', '" + var15 + "', '" + var16 + "','" + var17 + "', '" +
    var18 + "');";

    std::cout << add_query << '\n';
    return 0;
}

Produces this output:

INSERT INTO `table`(    `row1`, `row2`, `row3`, `row4`, `row5`, `row6`, `row7`, `row8`, `row9`,    `row10`, `row11`, `row12`, `row13`, `row14`, `row15`, `row16`, `row17`,    `row18`, `row19`, `row20`, `row21`, `row22`)    VALUES ( NULL, 'var1', 'var2', 'var3', 'var4', 'var5', 'var6', 'var7', 0, NULL, NULL, 'var8', 'var9', 'var10', 'var11', 'var12', 'var13', 'var14', 'var15', 'var16','var17', 'var18');

which seems to be well formed SQL, though the final semicolon is not required by some APIs.


问:
Ajax reloading content in Bootstrap tab
The problem seems to lie in a few places. To start my charts I am trying to bring up in the third tab won't display the JavaScript tied to the div. I believe this is because they're set to inactive in the HTML class, which then doesn't load the charts
 to display the charts.

I'm not sure the method to go about fixing this, I have looked into DOM events and Ajax load functions. But I'm not sure if that's actually the correct answer.

The ways I have tried to fix this are by making the tab active which works. But say in the future I want graphs on all three tabs, it still only loads the active tab. Also, I have tried to put the apex charts graph JS code in my click function, which also works. But again it if you click on the tabs in the order of 1 -> 2 -> 3 you will have loaded 3 charts.

All of this is using Apex charts, Bootstrap, PHP and JS.

```<code><!-- Nav tabs -->
<ul class="nav nav-tabs">
    <li class="nav-item"><a class="nav-link active" href="#home">Home</a></li>
    <li class="nav-item"><a class="nav-link" href="#menu1">Menu 1</a></li>
    <li class="nav-item"><a class="nav-link" href="#menu2">Menu 2</a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
    <div id="home" class="container tab-pane active"><br>
        <h3>HOME</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
    <div id="menu1" class="container tab-pane fade"><br>
        <h3>Menu 1</h3>
        <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>
    <div id="menu2" class="container tab-pane fade"><br>
        <div class="row">
            <div class="col-lg-6">
                <h3>Income categories</h3>
                <div id="chart"></div>
            </div>
            <div class="col-lg-6">
                <h3>Expense categories</h3>
                <div id="chart2"></div>
            </div>
        </div>
    </div>
</div>
<script>
$(document).ready(function(){
  $(".nav-tabs a").click(function(){
    $(this).tab('show');
  });
});
</script>
</body>
</html>
<!--Loads in the bar chart for analytics-->
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<?php include($_SERVER['DOCUMENT_ROOT'] . "/Management/scripts/incomegraph.php"); ?>
</code>```

This is the Apex Charts

```<code>var options = {
    chart: {
        height: 350,
        type: 'bar',
    },
    plotOptions: {
        bar: {
            horizontal: true,
        }
    },
    dataLabels: {
        enabled: true
    },
    series: [{
        data: [
            400,
            430,
            448,
            470,
            540]
    }],
    xaxis: {
        categories: [
            'Management Income',
            'Late Fee Income',
            'Application Fee Income',
            'Convience Fees',
            'Laundry',],
    }
}
var chart = new ApexCharts(document.querySelector("#chart"),options);

chart.render();

var options = {
    chart: {
        height: 350,
        type: 'bar',
    },
    plotOptions: {
        bar: {
            horizontal: true,
        }
    },
    dataLabels: {
        enabled: true
    },
    series: [{
        data: [400, 430, 448, 470, 540]
    }],
    xaxis: {
        categories: [
            'Legal fees',
            'Utilities',
            'Cleaning and Maintenance',
            'Wages and Salaries',
            'Repairs',],
    }
}
var chart = new ApexCharts(document.querySelector("#chart2"),options);

chart.render();
</code>```

The only error message I get is as followed:

```<code>TypeError: Cannot read property 'forEach' of undefined
    at i.value (apexcharts:6)
    at i.value (apexcharts:6)
    at apexcharts:6
    at it (apexcharts:6)
    at new $ (apexcharts:6)
    at i.value (apexcharts:6)
    at apexcharts:6
</code>```

I have looked at the post for help but none have sufficient answer
Bootstrap load AJAX content in Inactive Tab
Reloading Content of Ajax Tab
bootstrap popover: reload content with ajax

答:
It was a bug in ApexCharts which is recently fixed and released in v3.7.1
Please update ApexCharts to 3.7.1 and hopefully, the issue will resolve itself.</p>

Title: Ajax reloading content in Bootstrap tab

Body:
The problem seems to lie in a few places. To start my charts I am trying to bring up in the third tab won't display the JavaScript tied to the div. I believe this is because they're set to inactive in the HTML class, which then doesn't load the charts
 to display the charts.

I'm not sure the method to go about fixing this, I have looked into DOM events and Ajax load functions. But I'm not sure if that's actually the correct answer.

The ways I have tried to fix this are by making the tab active which works. But say in the future I want graphs on all three tabs, it still only loads the active tab. Also, I have tried to put the apex charts graph JS code in my click function, which also works. But again it if you click on the tabs in the order of 1 -> 2 -> 3 you will have loaded 3 charts.

All of this is using Apex charts, Bootstrap, PHP and JS.

Home

Menu 1

Menu 2

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Income categories

Expense categories

<?php include($_SERVER['DOCUMENT_ROOT'] . "/Management/scripts/incomegraph.php"); ?>

This is the Apex Charts

var options = {
    chart: {
        height: 350,
        type: 'bar',
    },
    plotOptions: {
        bar: {
            horizontal: true,
        }
    },
    dataLabels: {
        enabled: true
    },
    series: [{
        data: [
            400,
            430,
            448,
            470,
            540]
    }],
    xaxis: {
        categories: [
            'Management Income',
            'Late Fee Income',
            'Application Fee Income',
            'Convience Fees',
            'Laundry',],
    }
}
var chart = new ApexCharts(document.querySelector("#chart"),options);

chart.render();

var options = {
    chart: {
        height: 350,
        type: 'bar',
    },
    plotOptions: {
        bar: {
            horizontal: true,
        }
    },
    dataLabels: {
        enabled: true
    },
    series: [{
        data: [400, 430, 448, 470, 540]
    }],
    xaxis: {
        categories: [
            'Legal fees',
            'Utilities',
            'Cleaning and Maintenance',
            'Wages and Salaries',
            'Repairs',],
    }
}
var chart = new ApexCharts(document.querySelector("#chart2"),options);

chart.render();

The only error message I get is as followed:

TypeError: Cannot read property 'forEach' of undefined
    at i.value (apexcharts:6)
    at i.value (apexcharts:6)
    at apexcharts:6
    at it (apexcharts:6)
    at new $ (apexcharts:6)
    at i.value (apexcharts:6)
    at apexcharts:6

I have looked at the post for help but none have sufficient answer
Bootstrap load AJAX content in Inactive Tab
Reloading Content of Ajax Tab
bootstrap popover: reload content with ajax


问:
How to modify the default output of flask when it receives a request
Generally, when flask gets a requests, it prints something like this:

127.0.0.1 - - [01/Jun/2019 18:35:45] "GET /generateNodesDataTest HTTP/1.1" 404 -

I don't want the entire path to be printed for each request. How can I modify that behavior?

答:
The logging message you see comes from Flask's default handler.

But the default handler can be configured or even removed:

```<code>from flask.logging import default_handler
app.logger.removeHandler(default_handler)
</code>```

Body:
The logging message you see comes from Flask's default handler.

But the default handler can be configured or even removed:

from flask.logging import default_handler
app.logger.removeHandler(default_handler)


问:
Populate pandas dataframe using column and row indices as variables

Overview

How do you populate a pandas dataframe using math which uses column and row indices as variables.

Setup

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

df = pd.DataFrame(index = range(5), columns = ['Combo_Class0', 'Combo_Class1', 'Combo_Class2', 'Combo_Class3', 'Combo_Class4'])
</code>```

Objective

Each cell in df = row index * (column index + 2)

Attempt 1

You can use this solution to produce the following code:

```<code>row = 0
for i in range(5):
    row = row + 1
    df.loc[i] = [(row)*(1+2), (row)*(2+2), (row)*(3+2), (row)*(4+2), (row)*(4+2), (row)*(5+2)]
</code>```

Attempt 2

This solution seemed relevant as well, although I believe I've read you're not supposed to loop through dataframes. Besides, I'm not seeing how to loop through rows and columns:

```<code>for i, j in df.iterrows():
    df.loc[i] = i
</code>```

答:
You can leverage broadcasting for a more efficient approach:

```<code>ix = (df.index+1).to_numpy() # .values for pandas 0.24<
df[:] = ix[:,None] * (ix+2)
</code>```

```<code>print(df)

        Combo_Class0  Combo_Class1  Combo_Class2  Combo_Class3  Combo_Class4
0             3             4             5             6             7
1             6             8            10            12            14
2             9            12            15            18            21
3            12            16            20            24            28
4            15            20            25            30            35
</code>```

Body:
Overview

How do you populate a pandas dataframe using math which uses column and row indices as variables.

Setup

import pandas as pd
import numpy as np

df = pd.DataFrame(index = range(5), columns = ['Combo_Class0', 'Combo_Class1', 'Combo_Class2', 'Combo_Class3', 'Combo_Class4'])

Objective

Each cell in df = row index * (column index + 2)

Attempt 1

You can use this solution to produce the following code:

row = 0
for i in range(5):
    row = row + 1
    df.loc[i] = [(row)*(1+2), (row)*(2+2), (row)*(3+2), (row)*(4+2), (row)*(4+2), (row)*(5+2)]

Attempt 2

This solution seemed relevant as well, although I believe I've read you're not supposed to loop through dataframes. Besides, I'm not seeing how to loop through rows and columns:

for i, j in df.iterrows():
    df.loc[i] = i

Body:
You can leverage broadcasting for a more efficient approach:

ix = (df.index+1).to_numpy() # .values for pandas 0.24<
df[:] = ix[:,None] * (ix+2)

print(df)

        Combo_Class0  Combo_Class1  Combo_Class2  Combo_Class3  Combo_Class4
0             3             4             5             6             7
1             6             8            10            12            14
2             9            12            15            18            21
3            12            16            20            24            28
4            15            20            25            30            35


问:
Allow Spring to have multiple WebMvcConfigurer implementations in different jars
When using Spring Web, in this case for rest endpoints & using Spring Boot 2, I can configure interceptors for my app using by implementing the WebMvcConfigurer interface:

@Configuration
public class SpringWebConfig implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor).addPathPatterns("/api/endpoint/**");
    }
}
```

I added this interceptor to most of my apps in an automatic fashion by doing the following:

Create a "common-jar", and put the above interface under package

com.company.api.

In every app, add the package com.company.api to
the api scan.

This common package also contains the Interceptor and utility classes to make this interceptor work, so in effect, adding this common-jar would automatically add he interceptor to all operations in the app, which is a similar concept as to what Spring itself does: adding dependencies changes the default configuration of Spring.

The problem I'm facing now is this approach cannot be extended to a second interceptor in a second jar, because I already used the WebMvcConfigurer implementation. and I cannot have two.

I was thinking about maybe using some kind of composite-configurer pattern where we loop over every configurer, collect all interceptors, and then add them once, but unfortunately Spring doesn't allow this. What are my options?

Currently, the approach I took is duplicating the WebMvcConfigurer interface in every app that requires it. I feel sad when something changes, and I have to change the same snippet of code in every single app.

答:
If I understand your question correctly , basically you want to define some common Interceptors in multiple JARs such that an application can activate these Interceptors by simply including these JARs into their app ?

I was thinking about maybe using some kind of composite-configurer
  pattern where we loop over every configurer, collect all interceptors,
  and then add them once, but unfortunately Spring doesn't allow this.
  What are my options?

Well, if implementation A returns a registry with only interceptor A,
  and implementation B returns a registry with only interceptor B, would
  spring combine both registries into one super registry containing both
  A and B, or would it just pick one, or would it throw an error that
  there was no unique bean definition ?

Actually , Spring has already implement this feature. When there are multiple WebMvcConfigurer beans , Spring simply loop them one by one and calls their configuration methods. So the end-result is that InterceptorRegistry will contain all interceptors.

If the client application need to activate certain WebMvcConfigurer only, it can simply exclude those JARs containing the WebMvcConfigurer that they don't want.

To take this idea further which allow the application to control which Interceptors to activate down to interceptor level , you could even do the following in each common JAR :

```<code>@Configuration
public class SpringWebConfig implements WebMvcConfigurer {

    //Make sure the HandlerInterceptor implementation in this JAR is a bean (e.g mark it as @Component)
    @Autowired
    private List<HandlerInterceptor> interceptors;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        for(HandlerInterceptor interceptor : interceptors){
            registry.addInterceptor(interceptor).addPathPatterns("/api/endpoint/**");
        }
    }
}
</code>```

In the client application , use includeFilters / excludeFilters in @ComponentScan to customise which to interceptors to include. For example, to disable certain Interceptors, you could do :

```<code>@ComponentScan(
    basePackages = {"com.company.api"},
    excludeFilters={
         @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=com.company.common.jar1.Inteceptor1.class) ,
         @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=com.company.common.jar2.Inteceptor1.class)
    })
</code>```

Body:
When using Spring Web, in this case for rest endpoints & using Spring Boot 2, I can configure interceptors for my app using by implementing the WebMvcConfigurer interface:

@Configuration
public class SpringWebConfig implements WebMvcConfigurer
{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor).addPathPatterns("/api/endpoint/**");
    }
}

I added this interceptor to most of my apps in an automatic fashion by doing the following:

Create a "common-jar", and put the above interface under package

com.company.api.

In every app, add the package com.company.api to
the api scan.

This common package also contains the Interceptor and utility classes to make this interceptor work, so in effect, adding this common-jar would automatically add he interceptor to all operations in the app, which is a similar concept as to what Spring itself does: adding dependencies changes the default configuration of Spring.

The problem I'm facing now is this approach cannot be extended to a second interceptor in a second jar, because I already used the WebMvcConfigurer implementation. and I cannot have two.

I was thinking about maybe using some kind of composite-configurer pattern where we loop over every configurer, collect all interceptors, and then add them once, but unfortunately Spring doesn't allow this. What are my options?

Currently, the approach I took is duplicating the WebMvcConfigurer interface in every app that requires it. I feel sad when something changes, and I have to change the same snippet of code in every single app.

Body:
If I understand your question correctly , basically you want to define some common Interceptors in multiple JARs such that an application can activate these Interceptors by simply including these JARs into their app ?

I was thinking about maybe using some kind of composite-configurer
  pattern where we loop over every configurer, collect all interceptors,
  and then add them once, but unfortunately Spring doesn't allow this.
  What are my options?

Well, if implementation A returns a registry with only interceptor A,
  and implementation B returns a registry with only interceptor B, would
  spring combine both registries into one super registry containing both
  A and B, or would it just pick one, or would it throw an error that
  there was no unique bean definition ?

Actually , Spring has already implement this feature. When there are multiple WebMvcConfigurer beans , Spring simply loop them one by one and calls their configuration methods. So the end-result is that InterceptorRegistry will contain all interceptors.

If the client application need to activate certain WebMvcConfigurer only, it can simply exclude those JARs containing the WebMvcConfigurer that they don't want.

To take this idea further which allow the application to control which Interceptors to activate down to interceptor level , you could even do the following in each common JAR :

@Configuration
public class SpringWebConfig implements WebMvcConfigurer {

    //Make sure the HandlerInterceptor implementation in this JAR is a bean (e.g mark it as @Component)
    @Autowired
    private List<HandlerInterceptor> interceptors;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        for(HandlerInterceptor interceptor : interceptors){
            registry.addInterceptor(interceptor).addPathPatterns("/api/endpoint/**");
        }
    }
}

In the client application , use includeFilters / excludeFilters in @ComponentScan to customise which to interceptors to include. For example, to disable certain Interceptors, you could do :

@ComponentScan(
    basePackages = {"com.company.api"},
    excludeFilters={
         @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=com.company.common.jar1.Inteceptor1.class) ,
         @ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=com.company.common.jar2.Inteceptor1.class)
    })


问:
Is it possible to add a function to expand and/or collapse all accordion in a click?
I'm currently setting up an FAQ page and I need to add a function to expand/collapse all answers in a click of a button. If expand link/button is clicked, it will show all contents of the accordion and then, the label 'Expand All' will be replaced with 'Collapse All' and the function will be vice versa.

I'm not sure if tweaking the current JS will do.

```<code>//hides a accordion panel
function close(opts) {
    opened = $(document).find('.' + opts.cssOpen);
    $.each(opened, function() {
        //give the proper class to the linked element
        $(this).addClass(opts.cssClose).removeClass(opts.cssOpen);
        opts.animateClose($(this), opts);
    });
}

//opens a accordion panel
function open($this, opts) {
    close(opts);
    //give the proper class to the linked element
    $this.removeClass(opts.cssClose).addClass(opts.cssOpen);

    //open the element
    opts.animateOpen($this, opts);

    //do cookies if plugin available
    if (useCookies(opts)) {
        // split the cookieOpen string by ","
        id = $this.attr('id');
        setCookie(id, opts);
    }
}

//toggle a accordion on an event
function toggle($this, opts) {
    // close the only open item
    if ($this.hasClass(opts.cssOpen))
    {
        close(opts);
        //do cookies if plugin available
        if (useCookies(opts)) {
            // split the cookieOpen string by ","
            setCookie('', opts);
        }
        return false;
    }
    close(opts);
    //open a closed element
    open($this, opts);
    return false;
}
</code>```

Expected results will be similar to https://www.gucci.com/int/en/st/faq

答:
You can get the same functionality using jquery and bootstrap code below:

html code

```<code><div class="container">
  <div class="accordion-option">
    <h3 class="title">Lorem Ipsum</h3>
    <a href="javascript:void(0)" class="toggle-accordion active" accordion-id="#accordion"></a>
  </div>
  <div class="clearfix"></div>
  <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingOne">
        <h4 class="panel-title">
        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
        <div class="panel-body">
          labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingTwo">
        <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit,
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingThree">
        <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
      </div>
      <div id="collapseThree" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingThree">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

Css Code:

```<code>body {
  color: #6a6c6f;
  background-color: #f1f3f6;
  margin-top: 30px;
}

.container {
  max-width: 960px;
}

.panel-default>.panel-heading {
  color: #333;
  background-color: #fff;
  border-color: #e4e5e7;
  padding: 0;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.panel-default>.panel-heading a {
  display: block;
  padding: 10px 15px;
}

.panel-default>.panel-heading a:after {
  content: "";
  position: relative;
  top: 1px;
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  float: right;
  transition: transform .25s linear;
  -webkit-transition: -webkit-transform .25s linear;
}

.panel-default>.panel-heading a[aria-expanded="true"] {
  background-color: #eee;
}

.panel-default>.panel-heading a[aria-expanded="true"]:after {
  content: "\2212";
  -webkit-transform: rotate(180deg);
  transform: rotate(180deg);
}

.panel-default>.panel-heading a[aria-expanded="false"]:after {
  content: "\002b";
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}

.accordion-option {
  width: 100%;
  float: left;
  clear: both;
  margin: 15px 0;
}

.accordion-option .title {
  font-size: 20px;
  font-weight: bold;
  float: left;
  padding: 0;
  margin: 0;
}

.accordion-option .toggle-accordion {
  float: right;
  font-size: 16px;
  color: #6a6c6f;
}

.accordion-option .toggle-accordion:before {
  content: "Expand All";
}

.accordion-option .toggle-accordion.active:before {
  content: "Collapse All";
}
</code>```

Javascript code:

```<code>$(document).ready(function() {

  $(".toggle-accordion").on("click", function() {
    var accordionId = $(this).attr("accordion-id"),
      numPanelOpen = $(accordionId + ' .collapse.in').length;

    $(this).toggleClass("active");

    if (numPanelOpen == 0) {
      openAllPanels(accordionId);
    } else {
      closeAllPanels(accordionId);
    }
  })

  openAllPanels = function(aId) {
    console.log("setAllPanelOpen");
    $(aId + ' .panel-collapse:not(".in")').collapse('show');
  }
  closeAllPanels = function(aId) {
    console.log("setAllPanelclose");
    $(aId + ' .panel-collapse.in').collapse('hide');
  }

});
</code>```

You have to use bootstarp 3.3.6 for the given code, These code used in my old project In which I have used bootstrap 3.3.6, Or you can modify for bootstrap 4.

Bootstrap css link:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</code>```

jQuery and bootstrap js link

```<code><script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</code>```

Body:
I'm currently setting up an FAQ page and I need to add a function to expand/collapse all answers in a click of a button. If expand link/button is clicked, it will show all contents of the accordion and then, the label 'Expand All' will be replaced with 'Collapse All' and the function will be vice versa.

I'm not sure if tweaking the current JS will do.

//hides a accordion panel
function close(opts) {
    opened = $(document).find('.' + opts.cssOpen);
    $.each(opened, function() {
        //give the proper class to the linked element
        $(this).addClass(opts.cssClose).removeClass(opts.cssOpen);
        opts.animateClose($(this), opts);
    });
}

//opens a accordion panel
function open($this, opts) {
    close(opts);
    //give the proper class to the linked element
    $this.removeClass(opts.cssClose).addClass(opts.cssOpen);

    //open the element
    opts.animateOpen($this, opts);

    //do cookies if plugin available
    if (useCookies(opts)) {
        // split the cookieOpen string by ","
        id = $this.attr('id');
        setCookie(id, opts);
    }
}

//toggle a accordion on an event
function toggle($this, opts) {
    // close the only open item
    if ($this.hasClass(opts.cssOpen))
    {
        close(opts);
        //do cookies if plugin available
        if (useCookies(opts)) {
            // split the cookieOpen string by ","
            setCookie('', opts);
        }
        return false;
    }
    close(opts);
    //open a closed element
    open($this, opts);
    return false;
}

Expected results will be similar to https://www.gucci.com/int/en/st/faq

Body:
You can get the same functionality using jquery and bootstrap code below:

html code

<div class="container">
  <div class="accordion-option">
    <h3 class="title">Lorem Ipsum</h3>
    <a href="javascript:void(0)" class="toggle-accordion active" accordion-id="#accordion"></a>
  </div>
  <div class="clearfix"></div>
  <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingOne">
        <h4 class="panel-title">
        <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
      </h4>
      </div>
      <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
        <div class="panel-body">
          labore sustainable VHS.
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingTwo">
        <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </a>
      </h4>
      </div>
      <div id="collapseTwo" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingTwo">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit,
        </div>
      </div>
    </div>
    <div class="panel panel-default">
      <div class="panel-heading" role="tab" id="headingThree">
        <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="true" aria-controls="collapseThree">
          Collapsible Group Item #3
        </a>
      </h4>
      </div>
      <div id="collapseThree" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingThree">
        <div class="panel-body">
          Anim pariatur cliche reprehenderit
        </div>
      </div>
    </div>
  </div>
</div>

Css Code:

body {
  color: #6a6c6f;
  background-color: #f1f3f6;
  margin-top: 30px;
}

.container {
  max-width: 960px;
}

.panel-default>.panel-heading {
  color: #333;
  background-color: #fff;
  border-color: #e4e5e7;
  padding: 0;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.panel-default>.panel-heading a {
  display: block;
  padding: 10px 15px;
}

.panel-default>.panel-heading a:after {
  content: "";
  position: relative;
  top: 1px;
  display: inline-block;
  font-family: 'Glyphicons Halflings';
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  float: right;
  transition: transform .25s linear;
  -webkit-transition: -webkit-transform .25s linear;
}

.panel-default>.panel-heading a[aria-expanded="true"] {
  background-color: #eee;
}

.panel-default>.panel-heading a[aria-expanded="true"]:after {
  content: "\2212";
  -webkit-transform: rotate(180deg);
  transform: rotate(180deg);
}

.panel-default>.panel-heading a[aria-expanded="false"]:after {
  content: "\002b";
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}

.accordion-option {
  width: 100%;
  float: left;
  clear: both;
  margin: 15px 0;
}

.accordion-option .title {
  font-size: 20px;
  font-weight: bold;
  float: left;
  padding: 0;
  margin: 0;
}

.accordion-option .toggle-accordion {
  float: right;
  font-size: 16px;
  color: #6a6c6f;
}

.accordion-option .toggle-accordion:before {
  content: "Expand All";
}

.accordion-option .toggle-accordion.active:before {
  content: "Collapse All";
}

Javascript code:

$(document).ready(function() {

  $(".toggle-accordion").on("click", function() {
    var accordionId = $(this).attr("accordion-id"),
      numPanelOpen = $(accordionId + ' .collapse.in').length;

    $(this).toggleClass("active");

    if (numPanelOpen == 0) {
      openAllPanels(accordionId);
    } else {
      closeAllPanels(accordionId);
    }
  })

  openAllPanels = function(aId) {
    console.log("setAllPanelOpen");
    $(aId + ' .panel-collapse:not(".in")').collapse('show');
  }
  closeAllPanels = function(aId) {
    console.log("setAllPanelclose");
    $(aId + ' .panel-collapse.in').collapse('hide');
  }

});

You have to use bootstarp 3.3.6 for the given code, These code used in my old project In which I have used bootstrap 3.3.6, Or you can modify for bootstrap 4.

Bootstrap css link:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

jQuery and bootstrap js link

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>


问:
Update the viewController from the controller in MVC with SWIFT
I'm creating an app with swift. The app get weather from openweathermap.com api in the class WeatherDataModel then when the data are loaded, the model ask the viewController to update the datas

I'm on Xcode 10.2.1 with swift 5

I've create a protocol called in the model to update the data but the updateDisplayDelegate?.updateWeatherDataOnDisplay() is always nil and even if I get the data from the JSON in the console it won't update on the screen

class WeatherDataModel {

  var updateDisplayDelegate: ProtocolUpdateDisplay?

  func updateWeaterData(json : JSON) {
    updateDisplayDelegate?.updateWeatherDataOnDisplay()
  }
}

public protocol ProtocolUpdateDisplay {
    func updateWeatherDataOnDisplay()
}

class MainViewController: UIViewController {
  let weatherDataModel = WeatherDataModel()

  override func viewDidLoad() {
     super.viewDidLoad()
     weatherDataModel.updateDisplayDelegate = self
  }

extension MainViewController: ProtocolUpdateDisplay {

    func updateWeatherDataOnDisplay() {
        cityLabel.text = weatherDataModel.city
        tempLabel.text = weatherDataModel.temperature
        weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
    }
}

```

答:
You should not use delegation pattern for model. Consider using notification:

```<code>func updateWeaterData(json : JSON) {
    NotificationCenter.default.post(Notification(name: Notification.Name("WeatherDidUpdate")))
}
</code>```

and observe in any controller you want to respond to this notification:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(updateWeatherDataOnDisplay(_:)), name: Notification.Name("WeatherDidUpdate"), object: nil)
}

@objc func updateWeatherDataOnDisplay(_ notification: Notification) {
    cityLabel.text = weatherDataModel.city
    tempLabel.text = weatherDataModel.temperature
    weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}
</code>```

and remove observer at last:

```<code>deinit {
    NotificationCenter.default.removeObserver(self)
}
</code>```

Body:
You should not use delegation pattern for model. Consider using notification:

func updateWeaterData(json : JSON) {
    NotificationCenter.default.post(Notification(name: Notification.Name("WeatherDidUpdate")))
}

and observe in any controller you want to respond to this notification:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(updateWeatherDataOnDisplay(_:)), name: Notification.Name("WeatherDidUpdate"), object: nil)
}

@objc func updateWeatherDataOnDisplay(_ notification: Notification) {
    cityLabel.text = weatherDataModel.city
    tempLabel.text = weatherDataModel.temperature
    weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}

and remove observer at last:

deinit {
    NotificationCenter.default.removeObserver(self)
}


问:
Why does HttpRequest not work on Windows but works on Mac?
My partner who uses a Mac can run the program without any problem but when I try to run it it gives

WebException: The remote server returned an error: (400) Bad Request.

I've tried to copy the request URL (after the string is built) and the browser gives me the expected answer.

The code is this:

```<code>double SearchLatitude = 41.480687;
double SearchLongitude = -8.527346;
double Radius = 10; // km
int maxResults = 5;
string bingMapsKey = "MyKey";
string requestUrl = string.Format("http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs" +
            "?spatialFilter=nearby({0},{1},{2})&$filter=EntityTypeID Eq 5400&$top={3}&key={4}", SearchLatitude, SearchLongitude, Radius, maxResults,bingMapsKey);

HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
</code>```

Could this be a Windows problem?

答:
First thing to check is the regional settings (1.2 vs 1,2). </p>

<p>And always best to use </p>

```<code>//string requestUrl = string.Format("http://spatial.virtualearth.net/REST/...", ...);
  string requestUrl = string.Format(CultureInfo.InvariantCulture, "http://spatial.virtualearth.net/REST/...", ...);
</code>```

Body:
My partner who uses a Mac can run the program without any problem but when I try to run it it gives

WebException: The remote server returned an error: (400) Bad Request.

I've tried to copy the request URL (after the string is built) and the browser gives me the expected answer.

The code is this:

double SearchLatitude = 41.480687;
double SearchLongitude = -8.527346;
double Radius = 10; // km
int maxResults = 5;
string bingMapsKey = "MyKey";
string requestUrl = string.Format("http://spatial.virtualearth.net/REST/v1/data/c2ae584bbccc4916a0acf75d1e6947b4/NavteqEU/NavteqPOIs" +
            "?spatialFilter=nearby({0},{1},{2})&$filter=EntityTypeID Eq 5400&$top={3}&key={4}", SearchLatitude, SearchLongitude, Radius, maxResults,bingMapsKey);

HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;

Could this be a Windows problem?

Body:
First thing to check is the regional settings (1.2 vs 1,2).

And always best to use

//string requestUrl = string.Format("http://spatial.virtualearth.net/REST/...", ...);
  string requestUrl = string.Format(CultureInfo.InvariantCulture, "http://spatial.virtualearth.net/REST/...", ...);


问:
Obj Parser scanf giving strange results
I'm making a parser for .obj files . I'm using scanf but I'm getting really strange results.

```<code>void loader::readIn()
{
    //!takes in the all the data and
    //!puts in string first.
    std::string myString;     //!save string
    float tmpX,tmpY,tmpZ;     //!storing the floats in here .
    while(!myFile.eof())
    {

        std::getline(myFile,myString);                 //!intake string
        if(myString[0] == 'v' && myString[1] == ' ')   //!check value
            {
                    scanf_s(myString.c_str(), "v %f %f %f" ,&tmpX,&tmpY,&tmpZ);
                    std::cout<< tmpX <<" "<< tmpY <<" "<<tmpZ <<std::endl;
            }
    }
}
</code>```

This is my code.

Below this is what i am trying to read in

```<code>v  0.0  0.0  0.0
v  0.0  0.0  1.0
v  0.0  1.0  0.0
v  0.0  1.0  1.0
v  1.0  0.0  0.0
v  1.0  0.0  1.0
v  1.0  1.0  0.0
v  1.0  1.0  1.0
</code>```

And this is the result when I cout the answers.

```<code>-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
</code>```

Grateful for any help.

答:
Let me shortly explain to you the problem. First, and as commenters have written, you should not use any scanf-type function in C++. And even not in C. They are error prone and insecure (candidate for cyber attacs). Please use C++ iostreams for input and output from/to streams.

Then, I am programming in C++ since the language exists. I never heard of scanf_s. So, wow, thank you for making me aware. Reading the documentation, you would even not need it for your implementation. You try to read 3 floats, so, the _s version will not help you here.

Then, and this is the major bug, you are using scanf instead of sscanf. Scanf reads from stdin and not from string, as you expected. I was first wondering, why the function does not block and waits for user input. But it is of course clear why not. Your assumed input string is used as the formatting string. And, according to the defined behavior, the function does not detect formatting fields and stops immediately.

If you would have checked the return value of the function  (what you should do), then you would have detected that.

Then, you did never initialize the 3 float values. You should always initialize variables. But now, the variables contain random values. And there is never an assignment by scanf. So, the output is random.

Hope, I could explain the problem

ContentLicense: CC BY-SA 3.0

Title: Obj Parser scanf giving strange results

Body:
I'm making a parser for .obj files . I'm using scanf but I'm getting really strange results.

void loader::readIn()
{
    //!takes in the all the data and
    //!puts in string first.
    std::string myString;     //!save string
    float tmpX,tmpY,tmpZ;     //!storing the floats in here .
    while(!myFile.eof())
    {

        std::getline(myFile,myString);                 //!intake string
        if(myString[0] == 'v' && myString[1] == ' ')   //!check value
            {
                    scanf_s(myString.c_str(), "v %f %f %f" ,&tmpX,&tmpY,&tmpZ);
                    std::cout<< tmpX <<" "<< tmpY <<" "<<tmpZ <<std::endl;
            }
    }
}

This is my code.

Below this is what i am trying to read in

v  0.0  0.0  0.0
v  0.0  0.0  1.0
v  0.0  1.0  0.0
v  0.0  1.0  1.0
v  1.0  0.0  0.0
v  1.0  0.0  1.0
v  1.0  1.0  0.0
v  1.0  1.0  1.0

And this is the result when I cout the answers.

-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008
-1.07374e+008 -1.07374e+008 -1.07374e+008

Grateful for any help.


问:
Trying to list user favourities from API, getting "TypeError: null is not an object (evaluating 'firebase.auth().currentUser.uid')
I am creating an App (React Native) which is connecting to API and allowing user to add object recieved from API to its favourities. I have followed this tutorial but I am getting yellow warning "Possible Unhandled Promise Rejsction (id:0): TypeError: null is not an object (evaluating 'firebase.auth().currentUser.uid'). Data is adding to database but it is not listing (showing) in my app.

Home.js (in which I want my favorities to be listed)

```<code>import * as firebase from 'firebase';
import {Container, Content, ListItem} from 'native-base';

var data = []
var currentUser

class Home extends React.Component {

constructor(props){
   super(props)

    this.ds = new ListView.DataSource({rowHasChanged:(r1,r2) => r1 !==r2})

    this.state = {
        listViewData : data
    }
}
componentDidMount(){

    this.getPlants()
}

getPlants = async()=>{

    currentUser = await firebase.auth().currentUser

    var that = this

    firebase.database().ref(currentUser.uid).child('plantList').on('child_added',function(data){

        var newData = [...that.state.listViewData]
        newData.push(data)

        that.setState({ listViewData: newData})
    })
}
render(){
 return(
<Container style={{ flex: 1, backgroundColor: 'yellow'}}>
                <Content>
                    <ListView
                        enableEmptySections
                        dataSource = {this.ds.cloneWithRows(this.state.listViewData)}
                        renderRow={data =>

                            <ListItem>
                                <Text> {data.val().namePlant}</Text>
                            </ListItem>
                        }
                    />
                </Content>
            </Container>
     );}
}

export default Home;
</code>```

App.js

```<code>import * as firebase from 'firebase';
firebase.auth().signInWithEmailAndPassword("mail@gmail.com","password")

...

export default class App extends Component {

  constructor (props) {
super(props);

    if (!firebase.apps.length) { firebase.initializeApp(config.FirebaseConfig); }
}
  render() {

    return <AppContainer  />;
  }
}
</code>```

Plant.js (which is printing printing data of particular object from API and adding it to database)

```<code>import * as firebase from 'firebase';

var currentUser
class CatalogPlant extends React.Component {

  addToFavourites = async(scname) =>{

//get current user
currentUser = await firebase.auth().currentUser

//get unique key
var databaseRef = await firebase.database().ref(currentUser.uid).child('plantList').push()

//update plant name at the unique key
databaseRef.set({
  'namePlant': scname

})

  }

// part of code which connects to API and gets the data...
</code>```

答:
It seems like your user is not signed in to the app yet. In that case firebase.auth().currentUser is null, so when you do firebase.auth().currentUser.uid, you are calling uid on null.

The simple way to fix this is to always check for null after calling firebase.auth().currentUser. So:

```<code>currentUser = firebase.auth().currentUser

if (currentUser != null) {
    var that = this

    firebase.database().ref(user.uid).child('plantList').on('child_added',function(data){

    ...
</code>```

Note that I also removed the await from before firebase.auth().currentUser. Since firebase.auth().currentUser is not an asynchronous operation, there no need (nor use) for await here.

The better solution is to use an auth state listener, as also shown in this example from the RNFirebase documentation:

```<code>componentDidMount() {
  this.unsubscriber = firebase.auth().onAuthStateChanged((user) => {
    this.setState({ user });
  });
}
</code>```

So in your case that would translate to:

```<code>componentDidMount(){
  firebase.auth().onAuthStateChanged((user) => {

    if (user != null) {
      var that = this

       firebase.database().ref(currentUser.uid).child('plantList').on('child_added',function(data){

          var newData = [...that.state.listViewData]
          newData.push(data)

          that.setState({ listViewData: newData})
      })
    }
  })
}
</code>```

Signing in, or restoring the authentication state when the app restarts, is an asynchronous operation. So simply calling firebase.auth().currentUser may miss the fact that the user signed in. By using onAuthStateChanged, Firebase will call your code whenever the authentication state changes, which is the perfect moment to do things that depend on authentication state, such as (in your case) listening for data for that user).

Body:
I am creating an App (React Native) which is connecting to API and allowing user to add object recieved from API to its favourities. I have followed this tutorial but I am getting yellow warning "Possible Unhandled Promise Rejsction (id:0): TypeError: null is not an object (evaluating 'firebase.auth().currentUser.uid'). Data is adding to database but it is not listing (showing) in my app.

Home.js (in which I want my favorities to be listed)

import * as firebase from 'firebase';
import {Container, Content, ListItem} from 'native-base';

var data = []
var currentUser

class Home extends React.Component {

constructor(props){
   super(props)

    this.ds = new ListView.DataSource({rowHasChanged:(r1,r2) => r1 !==r2})

    this.state = {
        listViewData : data
    }
}
componentDidMount(){

    this.getPlants()
}

getPlants = async()=>{

    currentUser = await firebase.auth().currentUser

    var that = this

    firebase.database().ref(currentUser.uid).child('plantList').on('child_added',function(data){

        var newData = [...that.state.listViewData]
        newData.push(data)

        that.setState({ listViewData: newData})
    })
}
render(){
 return(
<Container style={{ flex: 1, backgroundColor: 'yellow'}}>
                <Content>
                    <ListView
                        enableEmptySections
                        dataSource = {this.ds.cloneWithRows(this.state.listViewData)}
                        renderRow={data =>

                            <ListItem>
                                <Text> {data.val().namePlant}</Text>
                            </ListItem>
                        }
                    />
                </Content>
            </Container>
     );}
}

export default Home;

App.js

import * as firebase from 'firebase';
firebase.auth().signInWithEmailAndPassword("mail@gmail.com","password")

...

export default class App extends Component {

  constructor (props) {
super(props);

    if (!firebase.apps.length) { firebase.initializeApp(config.FirebaseConfig); }
}
  render() {

    return <AppContainer  />;
  }
}

Plant.js (which is printing printing data of particular object from API and adding it to database)

import * as firebase from 'firebase';

var currentUser
class CatalogPlant extends React.Component {

  addToFavourites = async(scname) =>{

//get current user
currentUser = await firebase.auth().currentUser

//get unique key
var databaseRef = await firebase.database().ref(currentUser.uid).child('plantList').push()

//update plant name at the unique key
databaseRef.set({
  'namePlant': scname

})

  }

// part of code which connects to API and gets the data...

Body:
It seems like your user is not signed in to the app yet. In that case firebase.auth().currentUser is null, so when you do firebase.auth().currentUser.uid, you are calling uid on null.

The simple way to fix this is to always check for null after calling firebase.auth().currentUser. So:

currentUser = firebase.auth().currentUser

if (currentUser != null) {
    var that = this

    firebase.database().ref(user.uid).child('plantList').on('child_added',function(data){

    ...

Note that I also removed the await from before firebase.auth().currentUser. Since firebase.auth().currentUser is not an asynchronous operation, there no need (nor use) for await here.

The better solution is to use an auth state listener, as also shown in this example from the RNFirebase documentation:

componentDidMount() {
  this.unsubscriber = firebase.auth().onAuthStateChanged((user) => {
    this.setState({ user });
  });
}

So in your case that would translate to:

componentDidMount(){
  firebase.auth().onAuthStateChanged((user) => {

    if (user != null) {
      var that = this

       firebase.database().ref(currentUser.uid).child('plantList').on('child_added',function(data){

          var newData = [...that.state.listViewData]
          newData.push(data)

          that.setState({ listViewData: newData})
      })
    }
  })
}

Signing in, or restoring the authentication state when the app restarts, is an asynchronous operation. So simply calling firebase.auth().currentUser may miss the fact that the user signed in. By using onAuthStateChanged, Firebase will call your code whenever the authentication state changes, which is the perfect moment to do things that depend on authentication state, such as (in your case) listening for data for that user).


问:
Programmatic Views in Drupal 7
I'm trying to create two views.

View-1 is a list of nodes.

View-2 is an image gallery associated with each node.

I basically want to pass the node title from View-1 to a programmatic View-2, so that each row in View-1 will load View-2(with a result set filtered by the title of View-1!).

I'm confused about the approach. Should this happen in a custom module, preprocess functions, or some combination thereof?

I run into this a lot - wanting to pass an argument from a primary view to a secondary view that displays with each result.

I realize that the question is a bit general, but I'm curious how folks with more experience would approach this problem.

答:
Personally I would avoid views here alltogether.

A simple module using a hook_menu to define the menu-items and two simple menu-callback-functions dealing with the required parameters.

The alternative would be to make all the custom parameters and custom query-filtering and tables known to views.

My (pseronal) rule of thumb is:

If you are certain you will re-use the code several times in future projects a view-addon is worth the investment.

If you will use the views-interface for more then one-time-setup (the general use) e.g. define or change views in an editors/webmasters workflow this makes sense.

The basics of this is really simple and most probably a lot less coding and development then writing the views extensions.

```<code>/** Implementation of hook_menu().
 */
function gallery_menu() {
  $items = array();

  $items['gallery'] = array(
    'title'            => 'Gallery',
    'page callback'    => '_gallery_list',
    'access arguments' => array('access content'),
  );

  $items['gallery/%gallery'] = array(
    'title'            => 'For dynamic titles, see title_callback documentation',
    'page callback'    => '_gallery_view',
    'access arguments' => array('access content'),
  );

  return $items;
}

/** Load a gallery from database. Name follows %parameter_load hook.
 */
function gallery_load($id) {
  return db_query("SELECT * FROM {galleries} WHERE id = %d", $id);
}

/** Render a list of galleries.
 */
function _gallery_list() {
  $html = "";
  $galleries = pager_query("SELECT * FROM {galleries}", 10);

  foreach($galleries as $gallery) {
    $html .= check_plain($gallery->title); //You would actually build vars here and push them to theme layer instead.
  }
  $html .= theme("pager");
  return $html;
}

/** Load a gallery from database. Name follows %parameter_load hook.
 */
function gallery_load($id) {
  return db_query("SELECT * FROM {galleries} WHERE id = %d", $id);
}

/** Render a list of galleries.
 */
function _gallery_view($gallery) {
  $html = "";
  $images = pager_query("SELECT * FROM {images} WHERE gallery_id = %d", 10, $gallery->id);

  foreach($images as $image) {
    $html .= check_plain($image->title); //You would actually build vars here and push them to theme layer instead.
  }
  $html .= theme("pager");
  return $html;
}
</code>```

Obviously, as stated in the comments, you would additionally create a few theme functions to handle the rendering, to 1) avoid hardcoded spagetty-HTML all over your module and b) allow the frontenders to stay in their theme when creating the HTML.

Title: Programmatic Views in Drupal 7

Body:
Personally I would avoid views here alltogether.

A simple module using a hook_menu to define the menu-items and two simple menu-callback-functions dealing with the required parameters.

The alternative would be to make all the custom parameters and custom query-filtering and tables known to views.

My (pseronal) rule of thumb is:

If you are certain you will re-use the code several times in future projects a view-addon is worth the investment.

If you will use the views-interface for more then one-time-setup (the general use) e.g. define or change views in an editors/webmasters workflow this makes sense.

The basics of this is really simple and most probably a lot less coding and development then writing the views extensions.

/** Implementation of hook_menu().
 */
function gallery_menu() {
  $items = array();

  $items['gallery'] = array(
    'title'            => 'Gallery',
    'page callback'    => '_gallery_list',
    'access arguments' => array('access content'),
  );

  $items['gallery/%gallery'] = array(
    'title'            => 'For dynamic titles, see title_callback documentation',
    'page callback'    => '_gallery_view',
    'access arguments' => array('access content'),
  );

  return $items;
}

/** Load a gallery from database. Name follows %parameter_load hook.
 */
function gallery_load($id) {
  return db_query("SELECT * FROM {galleries} WHERE id = %d", $id);
}

/** Render a list of galleries.
 */
function _gallery_list() {
  $html = "";
  $galleries = pager_query("SELECT * FROM {galleries}", 10);

  foreach($galleries as $gallery) {
    $html .= check_plain($gallery->title); //You would actually build vars here and push them to theme layer instead.
  }
  $html .= theme("pager");
  return $html;
}

/** Load a gallery from database. Name follows %parameter_load hook.
 */
function gallery_load($id) {
  return db_query("SELECT * FROM {galleries} WHERE id = %d", $id);
}

/** Render a list of galleries.
 */
function _gallery_view($gallery) {
  $html = "";
  $images = pager_query("SELECT * FROM {images} WHERE gallery_id = %d", 10, $gallery->id);

  foreach($images as $image) {
    $html .= check_plain($image->title); //You would actually build vars here and push them to theme layer instead.
  }
  $html .= theme("pager");
  return $html;
}

Obviously, as stated in the comments, you would additionally create a few theme functions to handle the rendering, to 1) avoid hardcoded spagetty-HTML all over your module and b) allow the frontenders to stay in their theme when creating the HTML.


问:
Jenkins sudo: no tty present and no askpass program specified with NOPASSWD
I spend several days setting up the file /etc/sudoers to be able to give permissions to root to the user jenkins. I have Jenkins installed on my server because I host several projects with symfony, ionic, neo4j, etc... The problem is that I can not do build in the projects with ionic, I get this error:sudo: no tty present and no askpass program specified. This is the content of my /etc/sudoers file:

```<code>#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL
jenkins ALL=(ALL) NOPASSWD: ALL
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
</code>```

答:
This is just a response to elaborate on the steps to take to fix the issue.

First thing, figure out which user Jenkins GUI is using to execute the bash shell script.

select the project > Configure > enter whoami in the executable shell > save and Build Now.

View result in build history > click console output

User may be tomcat or jenkins or whatever.

SSH into Jenkins server

sudo su

visudo

tomcat ALL=(ALL) NOPASSWD: ALL  #if user displayed is tomcat

Body:
I spend several days setting up the file /etc/sudoers to be able to give permissions to root to the user jenkins. I have Jenkins installed on my server because I host several projects with symfony, ionic, neo4j, etc... The problem is that I can not do build in the projects with ionic, I get this error:sudo: no tty present and no askpass program specified. This is the content of my /etc/sudoers file:

#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL
jenkins ALL=(ALL) NOPASSWD: ALL
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL


问:
FileSystemWatcher - Reading last line of file after update?
I'm trying to write a simple console application that waits for a change to a file then reads just the last line of that file. The file watcher works and the change event fires.  But I'm struggling to work out how read from the file.

```<code>        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Path = "E:\\myFilePath";
            watcher.Filter = "";
            watcher.EnableRaisingEvents = true;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            Console.ReadKey();
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(File.ReadLines(e.FullPath).Last());
        }
</code>```

when testing (editing the file in notepad) it will work once, then after a second edit I get the error...

System.IO.IOException: 'The process cannot access the file '' because
  it is being used by another process.'

答:
The problem is due to an already open handle to the file. File.ReadLines uses an iterator internally which is Disposable. Use this to ensure Disposal during the lifetime of your event handler.

```<code>        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            var lines = File.ReadLines(e.FullPath);
            Console.WriteLine(lines.Last());
            lines.GetEnumerator().Dispose();
        }
</code>```

This should guarantee disposal before the end of event handler.

Edit: In the case that a different process is holding a write lock to the file, use Thread.Sleep(ms) with a safe time as inspecting and releasing file handles is not feasible in C#.

Body:
I'm trying to write a simple console application that waits for a change to a file then reads just the last line of that file. The file watcher works and the change event fires.  But I'm struggling to work out how read from the file.

        static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Path = "E:\\myFilePath";
            watcher.Filter = "";
            watcher.EnableRaisingEvents = true;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            Console.ReadKey();
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(File.ReadLines(e.FullPath).Last());
        }

when testing (editing the file in notepad) it will work once, then after a second edit I get the error...

System.IO.IOException: 'The process cannot access the file '' because
  it is being used by another process.'

Body:
The problem is due to an already open handle to the file. File.ReadLines uses an iterator internally which is Disposable. Use this to ensure Disposal during the lifetime of your event handler.

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            var lines = File.ReadLines(e.FullPath);
            Console.WriteLine(lines.Last());
            lines.GetEnumerator().Dispose();
        }

This should guarantee disposal before the end of event handler.

Edit: In the case that a different process is holding a write lock to the file, use Thread.Sleep(ms) with a safe time as inspecting and releasing file handles is not feasible in C#.