问:
How can this structure have sizeof == 0?
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

```<code>struct ZeroMemory {
    int *a[0];
};
</code>```

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

```<code>ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...
</code>```

Whaaaat...?

Godbolt link

How is this possible?

答:
As pointed out by Jarod42 zero size arrays are not standard C++, but GCC and Clang extensions.

Adding -pedantic produces this warning:

```<code>5 : <source>:5:12: warning: zero size arrays are an extension [-Wzero-length-array]
    int *a[0];
           ^
</code>```

I always forget that std=c++XX (instead of std=gnu++XX) doesn't disable all extensions.

This still doesn't explain the sizeof behavior. But at least we know it's not standard...

Body:
There is an old post asking for a construct for which sizeof would return 0. There are some high score answers from high reputation users saying that by the standard no type or variable can have sizeof 0. And I agree 100% with that.

However there is this new answer which presents this solution:

struct ZeroMemory {
    int *a[0];
};

I was just about to down-vote and comment on it, but time spent here taught me to check even the things that I am 100% sure on. So... to my surprise both gcc and clang show the same results: sizeof(ZeroMemory) == 0. Even more, sizeof a variable is 0:

ZeroMemory z{};
static_assert(sizeof(z) == 0); // Awkward...

Whaaaat...?

Godbolt link

How is this possible?

Body:
As pointed out by Jarod42 zero size arrays are not standard C++, but GCC and Clang extensions.

Adding -pedantic produces this warning:

5 : <source>:5:12: warning: zero size arrays are an extension [-Wzero-length-array]
    int *a[0];
           ^

I always forget that std=c++XX (instead of std=gnu++XX) doesn't disable all extensions.

This still doesn't explain the sizeof behavior. But at least we know it's not standard...


来源: stackexchange

问:
alert box without ok button in jQuery
How to show alert box without "OK" button and close after 2 seconds</p>

```<code>setTimeout(function() {
  alert("$premium$");
}, 1);
</code>```

答:
It's not possible to amend the dialog shown by the standard alert() method as the buttons are controlled by the browser/OS.

If you need this behaviour you'll need to use a library which builds alert notifications in HTML which can be amended exactly as you require.

ContentLicense: CC BY-SA 3.0

Title: alert box without ok button in jQuery

Body:
How to show alert box without "OK" button and close after 2 seconds

setTimeout(function() {
  alert("$premium$");
}, 1);


问:
How to create a database in docker mysql/mysql-server image and connect it through java
I have pulled the image mysql/mysql-server from the docker hub. Now I wanted to create a table with name and email columns and connect to this mysql db from java

Can I connect to this db using the below statement ?

Connection connect = DriverManager.getConnection("jdbc:mysql://xxxxxxx:xxxxx/dbname","uname","pwd");

答:
You should create your connection string with the db service name (or container name)

```<code>DriverManager.getConnection("jdbc:mysql://<mysqlcontainername>/dbname","uname","pwd");
</code>```

Note that your java application container and the mysql container must be in the same docker network.

I suggest to create a complete connection string injected from an environment variable (this is a really sweet procedure for Sysadmins):

```<code>DriverManager.getConnection("jdbc:mysql://username:password@<mysqlcontainername>/dbname");
</code>```

Body:
You should create your connection string with the db service name (or container name)

DriverManager.getConnection("jdbc:mysql://<mysqlcontainername>/dbname","uname","pwd");

Note that your java application container and the mysql container must be in the same docker network.

I suggest to create a complete connection string injected from an environment variable (this is a really sweet procedure for Sysadmins):

DriverManager.getConnection("jdbc:mysql://username:password@<mysqlcontainername>/dbname");


问:
Refresh All Subform from Another Form
I have two main forms. One is the Dashboard and another is Edit.

After Editing, I have a button to reopen the Dashboard.
It can open the dashboard but I want it to refresh the subforms within that Dashboard.

答:
You shouldn't need to close and reopen anything. Any opened form and the controls on it can be requeried from VBA code running anywhere. It gets a little convoluted with subforms.

To requery a subform control on the current form: [SubformControlName].Requery

To requery the form in a subform control on the current form: [SubformControlName].Form.Requery

To requery a control in a subform on the current form: [SubformControlName].Form.Controls("ControlName").Requery

To do any of the above operations on a different form in the application, prefix with Forms![FormName].

Example: Forms![FormName].[SubformControlName].Form.Controls("ControlName").Requery

ContentLicense: CC BY-SA 4.0

Title: Refresh All Subform from Another Form


问:
Lexical environment example explanation
I am following a JS tutorial and have come across this example below, and the first one makes sense from what I have learned so far:

```<code>function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 0
</code>```

So, that makes sense since the new lexical environments are created each time we assign the makeCounter function to a new variable. What I don't understand is if I am using the property of the function makeCounter I am still incrementing the makeCounter.count if I assign it to new variables:

```<code>function makeCounter() {
  function counter() {
    return makeCounter.count++;
  };
  makeCounter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 2
</code>```

答:
The function counter and counter.count are defined new in the function scope of makeCounter in each call.
makeCounter.count is defined once only for the global scope.</p>

Title: Lexical environment example explanation

Body:
I am following a JS tutorial and have come across this example below, and the first one makes sense from what I have learned so far:

function makeCounter() {
  function counter() {
    return counter.count++;
  };
  counter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 0

So, that makes sense since the new lexical environments are created each time we assign the makeCounter function to a new variable. What I don't understand is if I am using the property of the function makeCounter I am still incrementing the makeCounter.count if I assign it to new variables:

function makeCounter() {
  function counter() {
    return makeCounter.count++;
  };
  makeCounter.count = 0;

  return counter;
}

let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter());  // 0
console.log(counter());  // 1
console.log(counter1()); // 2


问:
How to write global function in brightscript?
I am working for Roku Scene Graph application, I want to write global user defined function which can be use and call any where in my application. is any way? Please suggest.</p>

答:
A global function script must be included in every XML file were you want to use it.

Steps:

Create a brs file in /source called globalFunction.brs (or any name you choose), and write all of the global functions there.

In every XML file (custom Screen, layout element etc) include the script after the <interface/> and before the <children/> with:

```<code><script type="text/brightscript" uri="pkg:/source/globalFunction.brs" />
</code>```

Body:
A global function script must be included in every XML file were you want to use it.

Steps:

Create a brs file in /source called globalFunction.brs (or any name you choose), and write all of the global functions there.

In every XML file (custom Screen, layout element etc) include the script after the <interface/> and before the <children/> with:

<script type="text/brightscript" uri="pkg:/source/globalFunction.brs" />


问:
How to do this Firebase Cloud Function I cant get this to work
In the Cloud Firestore I try to create a Function trigger but I have some problems.

I want the Cloud Firestore Function to respond to writes at this Firebase Realtime databas location:

```<code>"VISITORS_PRESENCE" : {
    "8PICNP6JBTJDFGiBZYsT" : { // House for sale
      "3b1874ec-02f8-4004-817d-a3c44877473c" : { // The user Id
        "applicationId" : "3b1874ec-02f8-4004-817d-a3c44877473c",
        "last_changed" : 1510859721293,
        "state" : "online",
        "userId" : "testtest@test,com"
      }
    }
  },
</code>```

and simply copy this values/writes into Cloud Firestore Using this functions:
(note this is based on the Cloud Firestore docs functions get-started

```<code>exports.onvisitorPresence = functions.database
    .ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {
        // Get the data written to Realtime Database
        const eventStatus = event.data.val();

        // Then use other event data to create a reference to the
        // corresponding Firestore document.
        const userStatusFirestoreRef = firestore
        .doc(`VISITORS_PRESENCE/${event.params.uid1}/USERS/{event.params.uid2}`);

        // It is likely that the Realtime Database change that triggered
        // this event has already been overwritten by a fast change in
        // online / offline status, so we'll re-read the current data
        // and compare the timestamps.
        return event.data.ref.once("value").then((statusSnapshot) => {
            return statusSnapshot.val();
        }).then((status) => {
            console.log(status, eventStatus);
            // If the current timestamp for this data is newer than
            // the data that triggered this event, we exit this function.
            if (status.last_changed > eventStatus.last_changed) return;

            // Otherwise, we convert the last_changed field to a Date
            eventStatus.last_changed = new Date(eventStatus.last_changed);

            // ... and write it to Firestore.
            return userStatusFirestoreRef.set(eventStatus);
        });
    });
</code>```

In the Cloud Firestore what this produces is this:

VISITORS_PRESENCE/8PICNP6JBTJDFGiBZYsT/USERS/{event.params.uid2}/

applicationId "3b1874ec-02f8-4004-817d-a3c44877473c"

last_changed November 16, 2017 at 8:15:21 PM UTC+1

state "online"

userId "testtest@test,com"

Here´s a pic:

I want the event.params.uid2in the above to be the "3b1874ec-02f8-4004-817d-a3c44877473c" which is a userId.

How can I do this?

答:
I did a smaaall error. I forgot the $ sign

.doc(VISITORS_PRESENCE/${event.params.uid1}/USERS/{event.params.uid2});

.doc(VISITORS_PRESENCE/${event.params.uid1}/USERS/${event.params.uid2});

Now the Cloud Firestore data looks ok:

VISITORS_PRESENCE/8PICNP6JBTJDFGiBZYsT/USERS/8PICNP6JBTJDFGiBZYsT/

applicationId "3b1874ec-02f8-4004-817d-a3c44877473c"

last_changed November 16, 2017 at 8:15:21 PM UTC+1

state "online"

userId "testtest@test,com"

Body:
In the Cloud Firestore I try to create a Function trigger but I have some problems.

I want the Cloud Firestore Function to respond to writes at this Firebase Realtime databas location:

"VISITORS_PRESENCE" : {
    "8PICNP6JBTJDFGiBZYsT" : { // House for sale
      "3b1874ec-02f8-4004-817d-a3c44877473c" : { // The user Id
        "applicationId" : "3b1874ec-02f8-4004-817d-a3c44877473c",
        "last_changed" : 1510859721293,
        "state" : "online",
        "userId" : "testtest@test,com"
      }
    }
  },

and simply copy this values/writes into Cloud Firestore Using this functions:
(note this is based on the Cloud Firestore docs functions get-started

exports.onvisitorPresence = functions.database
    .ref("/VISITORS_PRESENCE/{uid1}/{uid2}").onWrite((event) => {
        // Get the data written to Realtime Database
        const eventStatus = event.data.val();

        // Then use other event data to create a reference to the
        // corresponding Firestore document.
        const userStatusFirestoreRef = firestore
        .doc(`VISITORS_PRESENCE/${event.params.uid1}/USERS/{event.params.uid2}`);

        // It is likely that the Realtime Database change that triggered
        // this event has already been overwritten by a fast change in
        // online / offline status, so we'll re-read the current data
        // and compare the timestamps.
        return event.data.ref.once("value").then((statusSnapshot) => {
            return statusSnapshot.val();
        }).then((status) => {
            console.log(status, eventStatus);
            // If the current timestamp for this data is newer than
            // the data that triggered this event, we exit this function.
            if (status.last_changed > eventStatus.last_changed) return;

            // Otherwise, we convert the last_changed field to a Date
            eventStatus.last_changed = new Date(eventStatus.last_changed);

            // ... and write it to Firestore.
            return userStatusFirestoreRef.set(eventStatus);
        });
    });

In the Cloud Firestore what this produces is this:

VISITORS_PRESENCE/8PICNP6JBTJDFGiBZYsT/USERS/{event.params.uid2}/

applicationId "3b1874ec-02f8-4004-817d-a3c44877473c"

last_changed November 16, 2017 at 8:15:21 PM UTC+1

state "online"

userId "testtest@test,com"

Here´s a pic:

I want the event.params.uid2in the above to be the "3b1874ec-02f8-4004-817d-a3c44877473c" which is a userId.

How can I do this?


问:
Why i am getting wrong string of dynamic length using pointers in C from stdin?
I am trying to receive a string of unidentified length in C through pointers and realloc() function but after the string became 30 character long , the first few characters are like this :

```<code>ÿZ └
</code>```

I am running it on windows :

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

char* array;
int current = 0;
int size = 10;

void add(char element)
{
    if (current == size) {
        size += 10;
        realloc(array, size * (sizeof(char)));
    }
    *(array + current) = element;
    current++;
}

int main()
{
    array = calloc(10, sizeof(char));
    char c;
loop:
    c = getchar();
    if (c != '\n') {
        add(c);
        goto loop;
    }
    else {
        for (int i = 0; i <= current - 1; i++) {
            putchar(*(array + i));
        }
        printf("\nThe size of the string is %d", current);
    }
}
</code>```

答:
You need to do like this:

```<code>array=realloc(array,size*(sizeof(char)));
</code>```

The memory may be moved to another location. That's why you need to reassign the pointer.

Of course, it is good to do some error checking too:

```<code>char *tmp;
tmp = realloc(array,size*(sizeof(char)));
if(tmp)
    array=tmp;
else
    perror("realloc failed");
</code>```

Body:
I am trying to receive a string of unidentified length in C through pointers and realloc() function but after the string became 30 character long , the first few characters are like this :

ÿZ └

I am running it on windows :

#include <stdio.h>
#include <stdlib.h>

char* array;
int current = 0;
int size = 10;

void add(char element)
{
    if (current == size) {
        size += 10;
        realloc(array, size * (sizeof(char)));
    }
    *(array + current) = element;
    current++;
}

int main()
{
    array = calloc(10, sizeof(char));
    char c;
loop:
    c = getchar();
    if (c != '\n') {
        add(c);
        goto loop;
    }
    else {
        for (int i = 0; i <= current - 1; i++) {
            putchar(*(array + i));
        }
        printf("\nThe size of the string is %d", current);
    }
}

Body:
You need to do like this:

array=realloc(array,size*(sizeof(char)));

The memory may be moved to another location. That's why you need to reassign the pointer.

Of course, it is good to do some error checking too:

char *tmp;
tmp = realloc(array,size*(sizeof(char)));
if(tmp)
    array=tmp;
else
    perror("realloc failed");


问:
How can I detect whether a type is list-initializable?
Background: I'm writing a wrapper type like Either, and I'd like return {some, args}; to work from a function returning Either exactly when it'd work from a function returning A or B. However, I also want to detect when both A and B could be initialized with {some, args}, and produce an error to protect users from the ambiguity.

To detect whether a type T can be initialized from some arguments, I tried writing a function like this:

```<code>template<typename T, typename... Args>
auto testInit(Args&&... args) -> decltype(T{std::forward<Args>(args)...});

// imagine some other fallback overload here...
</code>```

I thought the expression testInit<T>(some, args) should be valid exactly when T{some, args} is valid — in the code below, the initialization auto x = MyType{1UL, 'a'}; works, and this test also passes:

```<code>struct MyType {
    MyType(size_t a, char b) {}
};
auto x = MyType{1UL, 'a'};  // ok
static_assert(std::is_same<MyType, decltype(testInit<MyType>(1UL, 'a'))>::value, "");  // ok
</code>```

However, when we add a constructor from std::initializer_list<char>, it breaks:

```<code>struct MyType {
    MyType(size_t a, char b) {}
    MyType(std::initializer_list<char> x) {}  // new!
};
auto x = MyType{1UL, 'a'};  // still ok

// FAILS:
static_assert(std::is_same<MyType, decltype(testInit<MyType>(1UL, 'a'))>::value, "");
</code>```

note: candidate template ignored: substitution failure [with T = MyType, Args = <unsigned long, char>]: non-constant-expression cannot be narrowed from type 'unsigned long' to 'char' in initializer list

```<code>auto testInit(Args&&... args) -> decltype(T{std::forward<Args>(args)...});
     ^                                      ~~~
</code>```

Why is Clang refusing to resolve my (size_t, char) constructor in favor of the initializer_list constructor? How can I correctly detect whether return {some, args}; would work in a function returning T, regardless of whether it's an aggregate type, a user-defined constructor, or an initializer_list constructor?

答:
It's a little complicated.

And I'm not really an expert so I can say something non completely exact: take what I say with a pinch of salt.

First of all: when you write

```<code>auto x = MyType{1UL, 'a'};  // ok
</code>```

the constructor called is the initializer list one, not the one that receive a std::size_t and the char.

And this works because the first value, 1UL is an unsigned long int but with a value (attention: a value) that can be narrowed to char. That is: works because 1UL is a value that fits in a char.

If you try

```<code>auto y = MyType{1000UL, 'a'};  // ERROR!
</code>```

you get an error because 1000UL can't be narrowed to a char. That is: the 1000UL doesn't fit in a char.

This works also with decltype():

```<code>decltype( char{1UL} )    ch1; // compile
decltype( char{1000UL} ) ch2; // ERROR
</code>```

But consider this function

```<code>auto test (std::size_t s)
   -> decltype( char{s} );
</code>```

This function gives immediately a compilation error.

You can think: "but if a pass 1UL to test(), decltype() can narrow the std::size_t value to a char"

The problem is that C and C++ are strongly typed languages; if you permit that test(), works, returning a type, when receive some values of std::size_t, you can create (via SFINAE) a function that return a type for some values and another type with another types. This in unacceptable from the point of view of a strongly typed language.

So

```<code>auto test (std::size_t s)
   -> decltype( char{s} );
</code>```

is acceptable only if decltype( char{s} ) is acceptable for all possible values of s. That is: test() is unacceptable because std::size_t can hold the 1000UL that doesn't fit in a char.

A little change now: make test() a template function

```<code>template <typename T>
auto test (T s)
   -> decltype( char{s} );
</code>```

Now test() compile; because there are types T with all values that can be narrowed to a char (T = char, by example). So test(), templatized, isn't intrinsically wrong.

But when you use it with a std::size_t

```<code>decltype( test(1UL) ) ch;  // ERROR
</code>```

you get an error because test() can't accept a std::size_t. Neither a value that can be narrowed to a char.

This is exactly the problem of your code.

Your testInit()

```<code>template <typename T, typename... Args>
auto testInit(Args&&... args)
   -> decltype(T{std::forward<Args>(args)...});
</code>```

is acceptable because there are types T and Args... so that T{std::forward<Args>(args)...} is acceptable (example: T = int and Args... = int).

But T = MyType and Args... = std::size_t, char is unacceptable because the constructor used is the one with an initializer list of char and non all std::size_t values can be narrowed to a char.

Concluding: you get an error compiling decltype(testInit<MyType>(1UL, 'a') because you get an error compiling MyType{1000UL, 'a'}.

Bonus answer: I suggest an improvement (IMHO) for your testInit().

Using SFINAE and the power of the comma operator, you can write

```<code>template <typename T, typename... Args>
auto testInit (Args ... args)
   -> decltype( T{ args... }, std::true_type{} );

template <typename...>
std::false_type testInit (...);
</code>```

So you can write some static_assert() simply as follows

```<code>static_assert( true == decltype(testInit<MyType>('a', 'b'))::value, "!");
static_assert( false == decltype(testInit<MyType>(1UL, 'b'))::value, "!");
</code>```

Post scriptum: if you want that the MyType(size_t a, char b) {} constructor is called, you can use the round parentheses

```<code>auto y = MyType(1000UL, 'a');  // compile!
</code>```

So if you write testInit() with round parentheses

```<code>template <typename T, typename... Args>
auto testInit (Args ... args)
   -> decltype( T( args... ), std::true_type{} );

template <typename...>
std::false_type testInit (...);
</code>```

you pass both following static_assert()s

```<code>static_assert( true == decltype(testInit<MyType>('a', 'b'))::value, "!");
static_assert( true == decltype(testInit<MyType>(1UL, 'b'))::value, "!");
</code>```

Body:
Background: I'm writing a wrapper type like Either, and I'd like return {some, args}; to work from a function returning Either exactly when it'd work from a function returning A or B. However, I also want to detect when both A and B could be initialized with {some, args}, and produce an error to protect users from the ambiguity.

To detect whether a type T can be initialized from some arguments, I tried writing a function like this:

template<typename T, typename... Args>
auto testInit(Args&&... args) -> decltype(T{std::forward<Args>(args)...});

// imagine some other fallback overload here...

I thought the expression testInit<T>(some, args) should be valid exactly when T{some, args} is valid — in the code below, the initialization auto x = MyType{1UL, 'a'}; works, and this test also passes:

struct MyType {
    MyType(size_t a, char b) {}
};
auto x = MyType{1UL, 'a'};  // ok
static_assert(std::is_same<MyType, decltype(testInit<MyType>(1UL, 'a'))>::value, "");  // ok

However, when we add a constructor from std::initializer_list<char>, it breaks:

struct MyType {
    MyType(size_t a, char b) {}
    MyType(std::initializer_list<char> x) {}  // new!
};
auto x = MyType{1UL, 'a'};  // still ok

// FAILS:
static_assert(std::is_same<MyType, decltype(testInit<MyType>(1UL, 'a'))>::value, "");

note: candidate template ignored: substitution failure [with T = MyType, Args = <unsigned long, char>]: non-constant-expression cannot be narrowed from type 'unsigned long' to 'char' in initializer list

auto testInit(Args&&... args) -> decltype(T{std::forward<Args>(args)...});
     ^                                      ~~~

Why is Clang refusing to resolve my (size_t, char) constructor in favor of the initializer_list constructor? How can I correctly detect whether return {some, args}; would work in a function returning T, regardless of whether it's an aggregate type, a user-defined constructor, or an initializer_list constructor?

Body:
It's a little complicated.

And I'm not really an expert so I can say something non completely exact: take what I say with a pinch of salt.

First of all: when you write

auto x = MyType{1UL, 'a'};  // ok

the constructor called is the initializer list one, not the one that receive a std::size_t and the char.

And this works because the first value, 1UL is an unsigned long int but with a value (attention: a value) that can be narrowed to char. That is: works because 1UL is a value that fits in a char.

If you try

auto y = MyType{1000UL, 'a'};  // ERROR!

you get an error because 1000UL can't be narrowed to a char. That is: the 1000UL doesn't fit in a char.

This works also with decltype():

decltype( char{1UL} )    ch1; // compile
decltype( char{1000UL} ) ch2; // ERROR

But consider this function

auto test (std::size_t s)
   -> decltype( char{s} );

This function gives immediately a compilation error.

You can think: "but if a pass 1UL to test(), decltype() can narrow the std::size_t value to a char"

The problem is that C and C++ are strongly typed languages; if you permit that test(), works, returning a type, when receive some values of std::size_t, you can create (via SFINAE) a function that return a type for some values and another type with another types. This in unacceptable from the point of view of a strongly typed language.

So

auto test (std::size_t s)
   -> decltype( char{s} );

is acceptable only if decltype( char{s} ) is acceptable for all possible values of s. That is: test() is unacceptable because std::size_t can hold the 1000UL that doesn't fit in a char.

A little change now: make test() a template function

template <typename T>
auto test (T s)
   -> decltype( char{s} );

Now test() compile; because there are types T with all values that can be narrowed to a char (T = char, by example). So test(), templatized, isn't intrinsically wrong.

But when you use it with a std::size_t

decltype( test(1UL) ) ch;  // ERROR

you get an error because test() can't accept a std::size_t. Neither a value that can be narrowed to a char.

This is exactly the problem of your code.

Your testInit()

template <typename T, typename... Args>
auto testInit(Args&&... args)
   -> decltype(T{std::forward<Args>(args)...});

is acceptable because there are types T and Args... so that T{std::forward<Args>(args)...} is acceptable (example: T = int and Args... = int).

But T = MyType and Args... = std::size_t, char is unacceptable because the constructor used is the one with an initializer list of char and non all std::size_t values can be narrowed to a char.

Concluding: you get an error compiling decltype(testInit<MyType>(1UL, 'a') because you get an error compiling MyType{1000UL, 'a'}.

Bonus answer: I suggest an improvement (IMHO) for your testInit().

Using SFINAE and the power of the comma operator, you can write

template <typename T, typename... Args>
auto testInit (Args ... args)
   -> decltype( T{ args... }, std::true_type{} );

template <typename...>
std::false_type testInit (...);

So you can write some static_assert() simply as follows

static_assert( true == decltype(testInit<MyType>('a', 'b'))::value, "!");
static_assert( false == decltype(testInit<MyType>(1UL, 'b'))::value, "!");

Post scriptum: if you want that the MyType(size_t a, char b) {} constructor is called, you can use the round parentheses

auto y = MyType(1000UL, 'a');  // compile!

So if you write testInit() with round parentheses

template <typename T, typename... Args>
auto testInit (Args ... args)
   -> decltype( T( args... ), std::true_type{} );

template <typename...>
std::false_type testInit (...);

you pass both following static_assert()s

static_assert( true == decltype(testInit<MyType>('a', 'b'))::value, "!");
static_assert( true == decltype(testInit<MyType>(1UL, 'b'))::value, "!");


问:
About "SLComposeViewController" in iOS 11 beta
In my project, I always use SLComposeViewController to share contents with third-party apps, but now, when I update my iPhone to iOS 11 beta, this no longer works.

The SLComposeViewControllerCompletionHandler always callback SLComposeViewControllerResultCancelled.

Why is this?

答:
For iOS 11 this line:

```<code> ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
</code>```

is always returning NO

I replaced it with check if user has Facebook app installed with:

```<code>static NSString *const canOpenFacebookURL = @"fbauth2";
</code>```

+ adding it to LSApplicationQueriesSchemes in plist

```<code>-(BOOL)isFacebookAppInstalled {
    NSURLComponents *components = [[NSURLComponents alloc] init];
    components.scheme = canOpenFacebookURL;
    components.path = @"/";
    return [[UIApplication sharedApplication]
            canOpenURL:components.URL];
}
</code>```

And then just call SLComposeViewController *composeVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

as usual, the same how Matheus Domingos described. But with this check at least you know that user has facebook app installed.

Body:
For iOS 11 this line:

 ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])

is always returning NO

I replaced it with check if user has Facebook app installed with:

static NSString *const canOpenFacebookURL = @"fbauth2";

+ adding it to LSApplicationQueriesSchemes in plist

-(BOOL)isFacebookAppInstalled {
    NSURLComponents *components = [[NSURLComponents alloc] init];
    components.scheme = canOpenFacebookURL;
    components.path = @"/";
    return [[UIApplication sharedApplication]
            canOpenURL:components.URL];
}

And then just call SLComposeViewController *composeVC = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];

as usual, the same how Matheus Domingos described. But with this check at least you know that user has facebook app installed.


答:
What I don't understand is if I am using the property of the function
  makeCounter I am still incrementing the makeCounter.count if I assign
  it to new variables:

makeCounter is available in the scope in which it is defined and inside makeCounter definition as well.

So, since makeCounter.count is not scoped exclusively local to makeCounter function definition, so both counter and counter1 has access to the same reference of makeCounter.count.

Title: Lexical environment example explanation


问:
Pattern and Matcher java problem

"SOMETHING, SOMETHING1,
  SOMETHING2,..."

How can I split that string to

SOMETHING SOMETHING1 SOMETHING2

This is what I have at the moment:

```<code>Pattern p = Pattern.compile("\\,+");
Matcher m = p.matcher(nVI);
while(m.find()){
System.out.println(m.group(1));
</code>```

However, it is not producing the desired result.

答:
What exactly separates the parts? Just a comma and a single space?

Try this:

```<code>String[] parts = nVI.split(", ");
</code>```

There is no need to escape the comma by writing \\, in your regular expression.

ContentLicense: CC BY-SA 2.5

Title: Pattern and Matcher java problem

Body:
"SOMETHING, SOMETHING1,
  SOMETHING2,..."

How can I split that string to

SOMETHING SOMETHING1 SOMETHING2

This is what I have at the moment:

Pattern p = Pattern.compile("\\,+");
Matcher m = p.matcher(nVI);
while(m.find()){
System.out.println(m.group(1));

However, it is not producing the desired result.

Body:
What exactly separates the parts? Just a comma and a single space?

Try this:

String[] parts = nVI.split(", ");

There is no need to escape the comma by writing \\, in your regular expression.


问:
Python - If row more than, do something
I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance!

The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime.

```<code>Forename: Surname: Email: Querytime:
</code>```

e.g.

```<code>for row in list:
    print row[4]
    if row[4] > '10':
        print("is greater than")
</code>```

row 4 =

```<code>55.9280
45.5300
40.2040
38.7850
32.8320
32.5820
31.6290
30.0630
29.4950
28.9780
</code>```

答:
The problem here is that you are dealing with strings and not numbers. Even if a string consists of numerical digits it is still considered like a word as far as python is concerned, and it just doesn't make any sense to ask if one word is 'greater than' another word.

It wouldn't make sense to ask is 'hello world'>17 and it would make no more sense to ask if '18'>17. You should think of '18' like a word.

Infact, if you try and compare a string and an integer, python should raise an error. Something like this:
TypeError: '>' not supported between instances of 'str' and 'int'

The fact that your program isn't raising any errors would suggest you are comparing strings with strings (which again doesn't make very much sense) and so you need to convert your stings into numbers. I would suggest the following:

```<code>if float(row[4]) > 10:
</code>```

You are now comparing two numbers, which makes sense.

I would use float instead of int, since looking at your data, your numbers are not whole numbers.

Title: Python - If row more than, do something

Body:
I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance!

The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime.

Forename: Surname: Email: Querytime:

e.g.

for row in list:
    print row[4]
    if row[4] > '10':
        print("is greater than")

row 4 =

55.9280
45.5300
40.2040
38.7850
32.8320
32.5820
31.6290
30.0630
29.4950
28.9780

Body:
The problem here is that you are dealing with strings and not numbers. Even if a string consists of numerical digits it is still considered like a word as far as python is concerned, and it just doesn't make any sense to ask if one word is 'greater than' another word.

It wouldn't make sense to ask is 'hello world'>17 and it would make no more sense to ask if '18'>17. You should think of '18' like a word.

Infact, if you try and compare a string and an integer, python should raise an error. Something like this:
TypeError: '>' not supported between instances of 'str' and 'int'

The fact that your program isn't raising any errors would suggest you are comparing strings with strings (which again doesn't make very much sense) and so you need to convert your stings into numbers. I would suggest the following:

if float(row[4]) > 10:

You are now comparing two numbers, which makes sense.

I would use float instead of int, since looking at your data, your numbers are not whole numbers.


问:
How do I get independent service Zeppelin to see Hive?
I am using HDP-2.6.0.3 but I need Zeppelin 0.8, so I have installed it as an independent service. When I run:

```<code>%sql
show tables
</code>```

I get nothing back and I get 'table not found' when I run Spark2 SQL commands. Tables can be seen in the 0.7 Zeppelin that is part of HDP.

Can anyone tell me what I am missing, for Zeppelin/Spark to see Hive?

The steps I performed to create the zep0.8 are as follows:

```<code>maven clean package -DskipTests -Pspark-2.1 -Phadoop-2.7-Dhadoop.version=2.7.3 -Pyarn -Ppyspark -Psparkr -Pr -Pscala-2.11
</code>```

Copied zeppelin-site.xml and shiro.ini from /usr/hdp/2.6.0.3-8/zeppelin/conf to /home/ed/zeppelin/conf.

created /home/ed/zeppelin/conf/zeppeli-env.sh in which I put the following:

```<code>export JAVA_HOME=/usr/jdk64/jdk1.8.0_112
export HADOOP_CONF_DIR=/etc/hadoop/conf
export ZEPPELIN_JAVA_OPTS="-Dhdp.version=2.6.0.3-8"
</code>```

Copied /etc/hive/conf/hive-site.xml to /home/ed/zeppelin/conf

EDIT:
I have also tried:

```<code>import org.apache.spark.sql.SparkSession
val spark = SparkSession
          .builder()
          .appName("interfacing spark sql to hive metastore without configuration file")
          .config("hive.metastore.uris", "thrift://s2.royble.co.uk:9083") // replace with your hivemetastore service's thrift url
          .config("url", "jdbc:hive2://s2.royble.co.uk:10000/default")
          .config("UID", "admin")
          .config("PWD", "admin")
          .config("driver", "org.apache.hive.jdbc.HiveDriver")
          .enableHiveSupport() // don't forget to enable hive support
          .getOrCreate()
</code>```

same result, and:

```<code>import java.sql.{DriverManager, Connection, Statement, ResultSet}
val url = "jdbc:hive2://"
val driver = "org.apache.hive.jdbc.HiveDriver"
val user = "admin"
val password = "admin"
Class.forName(driver).newInstance
val conn: Connection = DriverManager.getConnection(url, user, password)
</code>```

which gives:

```<code> java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
ERROR XSDB6: Another instance of Derby may have already booted the database /home/ed/metastore_db
</code>```

Fixed error with:

```<code>val url = "jdbc:hive2://s2.royble.co.uk:10000"
</code>```

but still no tables :(

答:
I had a similar problem in Cloudera Hadoop. In my case the problem was that spark sql did not see my hive metastore. So when I used my Spark Session object for spark SQL I could not see my previously created tables. I managed to solve it with adding in zeppelin-env.sh

```<code>export SPARK_HOME=/opt/cloudera/parcels/SPARK2/lib/spark2
export HADOOP_HOME=/opt/cloudera/parcels/CDH
export SPARK_CONF_DIR=/etc/spark/conf
export HADOOP_CONF_DIR=/etc/hadoop/conf
</code>```

(I assume for Horton Works these paths are something else). I also change spark.master from local[*] to yarn-client at Interpreter UI. Most importantly I manually copied hive-site.xml in /etc/spark/conf/ because I though it was strange that it was not in that directory and that solved my problem.

So my advice is to see if hive-site.xml exists in your SPARK_CONF_DIR and if not add it manually. I also find a guide for Horton Works and zeppelin in case this will not work.

Body:
I am using HDP-2.6.0.3 but I need Zeppelin 0.8, so I have installed it as an independent service. When I run:

%sql
show tables

I get nothing back and I get 'table not found' when I run Spark2 SQL commands. Tables can be seen in the 0.7 Zeppelin that is part of HDP.

Can anyone tell me what I am missing, for Zeppelin/Spark to see Hive?

The steps I performed to create the zep0.8 are as follows:

maven clean package -DskipTests -Pspark-2.1 -Phadoop-2.7-Dhadoop.version=2.7.3 -Pyarn -Ppyspark -Psparkr -Pr -Pscala-2.11

Copied zeppelin-site.xml and shiro.ini from /usr/hdp/2.6.0.3-8/zeppelin/conf to /home/ed/zeppelin/conf.

created /home/ed/zeppelin/conf/zeppeli-env.sh in which I put the following:

export JAVA_HOME=/usr/jdk64/jdk1.8.0_112
export HADOOP_CONF_DIR=/etc/hadoop/conf
export ZEPPELIN_JAVA_OPTS="-Dhdp.version=2.6.0.3-8"

Copied /etc/hive/conf/hive-site.xml to /home/ed/zeppelin/conf

EDIT:
I have also tried:

import org.apache.spark.sql.SparkSession
val spark = SparkSession
          .builder()
          .appName("interfacing spark sql to hive metastore without configuration file")
          .config("hive.metastore.uris", "thrift://s2.royble.co.uk:9083") // replace with your hivemetastore service's thrift url
          .config("url", "jdbc:hive2://s2.royble.co.uk:10000/default")
          .config("UID", "admin")
          .config("PWD", "admin")
          .config("driver", "org.apache.hive.jdbc.HiveDriver")
          .enableHiveSupport() // don't forget to enable hive support
          .getOrCreate()

same result, and:

import java.sql.{DriverManager, Connection, Statement, ResultSet}
val url = "jdbc:hive2://"
val driver = "org.apache.hive.jdbc.HiveDriver"
val user = "admin"
val password = "admin"
Class.forName(driver).newInstance
val conn: Connection = DriverManager.getConnection(url, user, password)

which gives:

 java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
ERROR XSDB6: Another instance of Derby may have already booted the database /home/ed/metastore_db

Fixed error with:

val url = "jdbc:hive2://s2.royble.co.uk:10000"

but still no tables :(

Body:
I had a similar problem in Cloudera Hadoop. In my case the problem was that spark sql did not see my hive metastore. So when I used my Spark Session object for spark SQL I could not see my previously created tables. I managed to solve it with adding in zeppelin-env.sh

export SPARK_HOME=/opt/cloudera/parcels/SPARK2/lib/spark2
export HADOOP_HOME=/opt/cloudera/parcels/CDH
export SPARK_CONF_DIR=/etc/spark/conf
export HADOOP_CONF_DIR=/etc/hadoop/conf

(I assume for Horton Works these paths are something else). I also change spark.master from local[*] to yarn-client at Interpreter UI. Most importantly I manually copied hive-site.xml in /etc/spark/conf/ because I though it was strange that it was not in that directory and that solved my problem.

So my advice is to see if hive-site.xml exists in your SPARK_CONF_DIR and if not add it manually. I also find a guide for Horton Works and zeppelin in case this will not work.


问:
Bash Check for Git Updates on Login
I am attempting to check my git repo if there are updates.
I need to do this when I login to my Ubuntu server, so I figured I would modify the /etc/update-motd.d/90-updates-available script with the following

It is supposed to cd into my repo once it is found, and then compare it to the remote repo, if remote is newer, print the notice.

```<code>#!/bin/sh

stamp="/var/lib/update-notifier/updates-available"

[ ! -r "$stamp" ] || cat "$stamp"

cd $(find / -wholename '*-Commander*/.git' | xargs -n 1 dirname)

UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
echo "----------------------------------------------------------"
echo ""
if [ $LOCAL = $BASE ]; then
    echo "Repo Need to be Updated"
    MEM=$(free -m | grep -oP '\d+' | head -n 1);
    if [ $MEM -lt 2048 ]; then
        echo "Low Mem Check"
    fi;
fi;
echo ""
echo "----------------------------------------------------------"
</code>```

what I am finding is, no matter what.. on login to the machine, it still shows Repo Need to be Updated, even if it is up to date.

Note, the repo was pulled as a sudoer, logging into the machine does logs in as a normal user at first.

What am I doing wrong?

答:
With the script you provided you don't check whether remote is newer than local (you wrote that this is what you want). You call git merge-base and save it to variable BASE an check equality with you local branch. What do you think BASE variable contains? It contains common ancestor(s) between two commits you provided. If local branch won't be changed after you pulled from the remote in past, both commits (in variables LOCAL and BASE) will be the same.So you are more likely checking whether your local repository did't change Also message should be printed in non-equality case.

Please have a look at first picture on page git merge-base example. Lets suppose you did in past pull on your local branch, then both remote and local branches will be both at commit 1. Then later on there will be some commits added to remote, so on this picture it could be branch named A, but your local branch won't be changed, so it still points to commit 1. When you call at this state git merge-base, result will be commit 1, so equality.

I see one more problem Do you fetch remote? AFAIK none of the commands do it automatically.

Title: Bash Check for Git Updates on Login

Body:
I am attempting to check my git repo if there are updates.
I need to do this when I login to my Ubuntu server, so I figured I would modify the /etc/update-motd.d/90-updates-available script with the following

It is supposed to cd into my repo once it is found, and then compare it to the remote repo, if remote is newer, print the notice.

#!/bin/sh

stamp="/var/lib/update-notifier/updates-available"

[ ! -r "$stamp" ] || cat "$stamp"

cd $(find / -wholename '*-Commander*/.git' | xargs -n 1 dirname)

UPSTREAM=${1:-'@{u}'}
LOCAL=$(git rev-parse @)
REMOTE=$(git rev-parse "$UPSTREAM")
BASE=$(git merge-base @ "$UPSTREAM")
echo "----------------------------------------------------------"
echo ""
if [ $LOCAL = $BASE ]; then
    echo "Repo Need to be Updated"
    MEM=$(free -m | grep -oP '\d+' | head -n 1);
    if [ $MEM -lt 2048 ]; then
        echo "Low Mem Check"
    fi;
fi;
echo ""
echo "----------------------------------------------------------"

what I am finding is, no matter what.. on login to the machine, it still shows Repo Need to be Updated, even if it is up to date.

Note, the repo was pulled as a sudoer, logging into the machine does logs in as a normal user at first.

What am I doing wrong?


问:
Complex condition and returned value using xpath
I'm using xpath in order to get values from xml. I found a particular situation:

```<code><Docs>
    <Doc>
       <tag1>0</tag1>
       <tag2>150.0</tag2>
    </Doc>
    <Doc>
       <tag1>45</tag1>
       <tag2>0</tag2>
    </Doc>
</Docs>
</code>```

There are two posibilities for each Doc entity:

case 1: if (tag1 = 0 and tag2 != 0) or (tag2 = 0 and tag1 != 0), I need to return the non-zero value.

case 2: Maybe the two fields are 0. I need to return 0

UPDATE1:
For example:
Suppose that I query the first node Doc (/Docs/doc[0]). I need to get 150.0. For the second one (/Docs/doc[1]) I need to get 45.

How can I solve this using just xpath?

答:
You can use the xpath union (|) operator, in order to cover all cases:</p>

```<code>Docs/Doc[tag1=0]/tag2[.!=0]/text() |
Docs/Doc[tag2=0]/tag1[.!=0]/text() |
Docs/Doc[tag1=0 and tag2=0]/tag1/text()
</code>```

Body:
I'm using xpath in order to get values from xml. I found a particular situation:

<Docs>
    <Doc>
       <tag1>0</tag1>
       <tag2>150.0</tag2>
    </Doc>
    <Doc>
       <tag1>45</tag1>
       <tag2>0</tag2>
    </Doc>
</Docs>

There are two posibilities for each Doc entity:

case 1: if (tag1 = 0 and tag2 != 0) or (tag2 = 0 and tag1 != 0), I need to return the non-zero value.

case 2: Maybe the two fields are 0. I need to return 0

UPDATE1:
For example:
Suppose that I query the first node Doc (/Docs/doc[0]). I need to get 150.0. For the second one (/Docs/doc[1]) I need to get 45.

How can I solve this using just xpath?

Body:
You can use the xpath union (|) operator, in order to cover all cases:

Docs/Doc[tag1=0]/tag2[.!=0]/text() |
Docs/Doc[tag2=0]/tag1[.!=0]/text() |
Docs/Doc[tag1=0 and tag2=0]/tag1/text()


问:
Iterating through a vector of tuples c+17 style don't work?
I am currently looking neat ways in which i can iterate this vector of tuples..

This is what I am currently doing?

```<code>#include <experimental/filesystems>
#include <tuple>
#include <iostream>
#include <vector>

std::tuple<std::experimental::filesystem::path, std::experimental::filesystem::file_status, std::size_t>
file_info(const std::experimental::filesystem::directory_entry &entry)
{

    const std::experimental::filesystem::file_status fs(std::experimental::filesystem::status(entry));
    return {entry.path(),
                fs,
                std::experimental::filesystem::is_regular_file(fs) ? std::experimental::filesystem::file_size(entry.path()) : 0u};

}

int main ()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);  // string_dir_to_test_files is just a string
    std::experimental::filesystem::directory_entry dir_path(_path);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << std::endl;
        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
        std::vector<std::tuple<std::experimental::filesystem::path,std::experimental::filesystem::file_status, std::size_t>> items;
        std::transform(std::experimental::filesystem::directory_iterator(_path),{},back_inserter(items),file_info);
        for( auto const& index : items)
        {
            std::cout << std::get<0>(index) << std::endl; // This line could be written better?
        }
    }
    else
    {
        std::cout << "No data to build database with!" << std::endl;
        exit(1);
    }

    return 0;
}
</code>```

Even though it does the job, it does not seem to be "reader" friendly, is there other ways in which I can the iterate the elements of the vector, in a more reader friendly manner?

One way I tried to make the for loop a bit more readable was by making like this:

```<code>for (auto const& [path, status, size] : items) {
    std::cout << path << std::endl;
}
</code>```

But this somehow give me this error:

```<code>/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected unqualified-id before ‘[’ token
         for(auto const& [path, status, size] : items)
                         ^
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected ‘;’ before ‘[’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:26: error: ‘path’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                          ^~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:26: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:39:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
   class path
         ^~~~
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
/home/noob/soundcloud/src/include/database/database.cpp:31:32: error: ‘status’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                                ^~~~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:32: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:41:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
   file_status status(const path& __p, error_code& __ec) noexcept;
               ^~~~~~
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
/home/noob/soundcloud/src/include/database/database.cpp:31:40: error: capture by copy of incomplete type ‘<unresolved overloaded function type>’
         for(auto const& [path, status, size] : items)
                                        ^~~~
/home/noob/soundcloud/src/include/database/database.cpp: In lambda function:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘{’ before ‘:’ token
         for(auto const& [path, status, size] : items)
                                              ^
/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘;’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘)’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
make[2]: *** [src/include/database/CMakeFiles/database.dir/database.cpp.o] Error 1
make[1]: *** [src/include/database/CMakeFiles/database.dir/all] Error 2
make: *** [all] Error 2
</code>```

答:
In C++11 you may do</p>

```<code>for (auto const& tup : items)
    std::experimental::filesystem::path path;
    std::tie(path, std::ignore, std::ignore) = tup;
    std::cout << path << std::endl;
}
</code>```

Body:
I am currently looking neat ways in which i can iterate this vector of tuples..

This is what I am currently doing?

#include <experimental/filesystems>
#include <tuple>
#include <iostream>
#include <vector>

std::tuple<std::experimental::filesystem::path, std::experimental::filesystem::file_status, std::size_t>
file_info(const std::experimental::filesystem::directory_entry &entry)
{

    const std::experimental::filesystem::file_status fs(std::experimental::filesystem::status(entry));
    return {entry.path(),
                fs,
                std::experimental::filesystem::is_regular_file(fs) ? std::experimental::filesystem::file_size(entry.path()) : 0u};

}

int main ()
{
    std::experimental::filesystem::path _path(string_dir_to_test_files);  // string_dir_to_test_files is just a string
    std::experimental::filesystem::directory_entry dir_path(_path);
    if (std::experimental::filesystem::exists(_path))
    {
        std::cout << "exists() = " << std::experimental::filesystem::exists(_path) << std::endl;
        std::cout << "Number of files in directory: " << number_of_files(_path) << std::endl;
        std::vector<std::tuple<std::experimental::filesystem::path,std::experimental::filesystem::file_status, std::size_t>> items;
        std::transform(std::experimental::filesystem::directory_iterator(_path),{},back_inserter(items),file_info);
        for( auto const& index : items)
        {
            std::cout << std::get<0>(index) << std::endl; // This line could be written better?
        }
    }
    else
    {
        std::cout << "No data to build database with!" << std::endl;
        exit(1);
    }

    return 0;
}

Even though it does the job, it does not seem to be "reader" friendly, is there other ways in which I can the iterate the elements of the vector, in a more reader friendly manner?

One way I tried to make the for loop a bit more readable was by making like this:

for (auto const& [path, status, size] : items) {
    std::cout << path << std::endl;
}

But this somehow give me this error:

/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected unqualified-id before ‘[’ token
         for(auto const& [path, status, size] : items)
                         ^
/home/noob/soundcloud/src/include/database/database.cpp:31:25: error: expected ‘;’ before ‘[’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:26: error: ‘path’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                          ^~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:26: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:39:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
   class path
         ^~~~
/usr/include/c++/6/experimental/bits/fs_path.h:79:9: note:   ‘std::experimental::filesystem::v1::path’
/home/noob/soundcloud/src/include/database/database.cpp:31:32: error: ‘status’ was not declared in this scope
         for(auto const& [path, status, size] : items)
                                ^~~~~~
/home/noob/soundcloud/src/include/database/database.cpp:31:32: note: suggested alternatives:
In file included from /usr/include/c++/6/experimental/filesystem:41:0,
                 from /home/noob/soundcloud/src/include/database/database.h:9,
                 from /home/noob/soundcloud/src/include/database/database.cpp:1:
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
   file_status status(const path& __p, error_code& __ec) noexcept;
               ^~~~~~
/usr/include/c++/6/experimental/bits/fs_ops.h:274:15: note:   ‘std::experimental::filesystem::v1::status’
/home/noob/soundcloud/src/include/database/database.cpp:31:40: error: capture by copy of incomplete type ‘<unresolved overloaded function type>’
         for(auto const& [path, status, size] : items)
                                        ^~~~
/home/noob/soundcloud/src/include/database/database.cpp: In lambda function:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘{’ before ‘:’ token
         for(auto const& [path, status, size] : items)
                                              ^
/home/noob/soundcloud/src/include/database/database.cpp: In constructor ‘database::database()’:
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘;’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected ‘)’ before ‘:’ token
/home/noob/soundcloud/src/include/database/database.cpp:31:46: error: expected primary-expression before ‘:’ token
make[2]: *** [src/include/database/CMakeFiles/database.dir/database.cpp.o] Error 1
make[1]: *** [src/include/database/CMakeFiles/database.dir/all] Error 2
make: *** [all] Error 2

Body:
In C++11 you may do

for (auto const& tup : items)
    std::experimental::filesystem::path path;
    std::tie(path, std::ignore, std::ignore) = tup;
    std::cout << path << std::endl;
}


答:
You are not storing the return value of realloc.

```<code>char *temp;
temp=realloc(array,size*(sizeof(char)));

if( temp )
  array = temp;
else
  // error
</code>```

goto makes code harder to debug by generating a complex control flow.

If you think, you will see you can replace goto with a for or while loop too.

You can see that your else part is not part of the goto part. Once else is executed it's never going to execute again.

So create a loop with this(else part) outside the loop.

Also return type of getchar() is int.

Title: Why i am getting wrong string of dynamic length using pointers in C from stdin?

Body:
You are not storing the return value of realloc.

char *temp;
temp=realloc(array,size*(sizeof(char)));

if( temp )
  array = temp;
else
  // error

goto makes code harder to debug by generating a complex control flow.

If you think, you will see you can replace goto with a for or while loop too.

You can see that your else part is not part of the goto part. Once else is executed it's never going to execute again.

So create a loop with this(else part) outside the loop.

Also return type of getchar() is int.


问:
Can this lead to rejection of iphone app
I am making an app and one of the requirements is a contactlist of people working in the company. I have made a tableview, searchbar and a detailedviewcontroller with view that shows details of a contact. The detail view is almost identical with the native contactview.

This can't lead to that my app is going to be rejected can it?

Thanks in advance.

答: I don’t think so, you’re not competing with the system Contacts app and UI consistency is good.</p>


问:
Reinitialize TinyMCE 4 in AJAX
I'm using TinyMCE in an ajax enabled Foundation Reveal box. Now the TinyMCE kicks in the first time it loads, but if I close the box and open it again it doesn't trigger :(

I have other scripts like chosen and masked input triggered in the exact same fore query that work, but TinyMCE will not reinitialize when I reload it a second time

This is my code currently that I'm trying as recommended at this question:

```<code>$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
    $("#expenseUser, #expenseVendorID, #expenseCategoryID, #expenseAccidentID").chosen({disable_search_threshold: 5, width: '365px'});
    $("#expOdo").mask("999999",{placeholder:"0"});
    $('.datePicker').each(function() {
        $(this).datetimepicker({
            addSliderAccess: true,
            sliderAccessArgs: {touchonly: false},
            changeMonth: true,
            changeYear: true,
            altField: "#"+$(this).attr('id')+"Alt",
            altFieldTimeOnly: false,
            altFormat: "yy-mm-dd",
            altTimeFormat : "HH:mm:ss",
            dateFormat: "D, d MM yy",
            timeFormat: "hh:mmtt"
        });
    });
    tinymce.execCommand('mceRemoveEditor',true,"textarea#expenseComments");
    tinymce.execCommand('mceAddEditor',true,"textarea#expenseComments");
    tinyMCE.init({selector: "textarea#expenseComments",menubar : false,toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright"});
});
</code>```

UPDATED

I've tried changing to the following with luck, but I think this is the right path to go down?

```<code>$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
    $("#expenseUser, #expenseVendorID, #expenseCategoryID, #expenseAccidentID").chosen({disable_search_threshold: 5, width: '365px'});
    $("#expOdo").mask("999999",{placeholder:"0"});
    $('.datePicker').each(function() {
        $(this).datetimepicker({
            addSliderAccess: true,
            sliderAccessArgs: {touchonly: false},
            changeMonth: true,
            changeYear: true,
            altField: "#"+$(this).attr('id')+"Alt",
            altFieldTimeOnly: false,
            altFormat: "yy-mm-dd",
            altTimeFormat : "HH:mm:ss",
            dateFormat: "D, d MM yy",
            timeFormat: "hh:mmtt"
        });
    });
    tinyMCE.init({selector: "textarea#expenseComments",menubar : false,toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright"});
});
$(document).on('close.fndtn.reveal', '[data-reveal]', function () {
    tinymce.execCommand('mceRemoveEditor',true,"textarea#expenseComments");
});
</code>```

答:
Hoping this will be a more complete guide to solving this.

console.log("before remove")
//capture the editorId from this (id: )
console.log(tinymce.EditorManager.editors);
//remove instance
tinymce.execCommand('mceRemoveEditor', true, "editorId");
//add to the DOM the html to whom you will apply tinymce
$("#emailEditor").append(html);
console.log("before add")
console.log(tinymce.EditorManager.editors);
//add instance
tinymce.EditorManager.execCommand('mceAddEditor', false, "editorId");
//init tinymce
initTinyMce();

//be sure to add the init_instance_callback part
function initTinyMce() {
    console.log("init tinymce")
    tinymce.init({
        //script_url: '~/Scripts/tinymce/jquery.tiny_mce.js',
        selector: "textarea#editorId",
        // General options
        mode: "textareas",
        theme: "modern",
        // Theme options
        theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
        theme_advanced_toolbar_location: "top",
        theme_advanced_toolbar_align: "left",
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_resizing: true,
        init_instance_callback: function (editor) {
            var currentEditor = editor.editorContainer;
            $(currentEditor).show();
        }
    });
}```

Title: Reinitialize TinyMCE 4 in AJAX

Body:
I'm using TinyMCE in an ajax enabled Foundation Reveal box. Now the TinyMCE kicks in the first time it loads, but if I close the box and open it again it doesn't trigger :(

I have other scripts like chosen and masked input triggered in the exact same fore query that work, but TinyMCE will not reinitialize when I reload it a second time

This is my code currently that I'm trying as recommended at this question:

$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
    $("#expenseUser, #expenseVendorID, #expenseCategoryID, #expenseAccidentID").chosen({disable_search_threshold: 5, width: '365px'});
    $("#expOdo").mask("999999",{placeholder:"0"});
    $('.datePicker').each(function() {
        $(this).datetimepicker({
            addSliderAccess: true,
            sliderAccessArgs: {touchonly: false},
            changeMonth: true,
            changeYear: true,
            altField: "#"+$(this).attr('id')+"Alt",
            altFieldTimeOnly: false,
            altFormat: "yy-mm-dd",
            altTimeFormat : "HH:mm:ss",
            dateFormat: "D, d MM yy",
            timeFormat: "hh:mmtt"
        });
    });
    tinymce.execCommand('mceRemoveEditor',true,"textarea#expenseComments");
    tinymce.execCommand('mceAddEditor',true,"textarea#expenseComments");
    tinyMCE.init({selector: "textarea#expenseComments",menubar : false,toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright"});
});

UPDATED

I've tried changing to the following with luck, but I think this is the right path to go down?

$(document).on('opened.fndtn.reveal', '[data-reveal]', function () {
    $("#expenseUser, #expenseVendorID, #expenseCategoryID, #expenseAccidentID").chosen({disable_search_threshold: 5, width: '365px'});
    $("#expOdo").mask("999999",{placeholder:"0"});
    $('.datePicker').each(function() {
        $(this).datetimepicker({
            addSliderAccess: true,
            sliderAccessArgs: {touchonly: false},
            changeMonth: true,
            changeYear: true,
            altField: "#"+$(this).attr('id')+"Alt",
            altFieldTimeOnly: false,
            altFormat: "yy-mm-dd",
            altTimeFormat : "HH:mm:ss",
            dateFormat: "D, d MM yy",
            timeFormat: "hh:mmtt"
        });
    });
    tinyMCE.init({selector: "textarea#expenseComments",menubar : false,toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright"});
});
$(document).on('close.fndtn.reveal', '[data-reveal]', function () {
    tinymce.execCommand('mceRemoveEditor',true,"textarea#expenseComments");
});


问:
Visual Studio Code doesn't format C# code
I created a new file, set the C# language, and wrote some code. Then I pressed Ctrl + Shift + F (or F1 → Format Document). And got I the error

Sorry, but there is no formatter for 'csharp'-files installed.

Also, I installed C# Extension, but it didn't help.
The Visual Studio Code version is 1.18.0.

答:
Use the Synaptic package manager and mark the code package for 'Full Removal' and click apply.

Like here:

```<code>Delete ~/.vscode
Delete ~/.config
Reinstall
</code>```

It worked for me.

Body:
Use the Synaptic package manager and mark the code package for 'Full Removal' and click apply.

Like here:

Delete ~/.vscode
Delete ~/.config
Reinstall

It worked for me.


问:
c#/.net service bus using sql server
I know there are mature frameworks out there like nservicebus, but I would like a queue that utilizes sql server and not msmq/rabbit.

Is there one out there?

Thanks in advance.

答:
You should look at ReBus. I have used it with SQL Server and worked fine.

https://github.com/rebus-org/Rebus

Title: c#/.net service bus using sql server


问:
ReactNative Flatlist onEndReached not working
Im trying to call a function on onEndReached of a FlatList but it's not working.

I'm calling the this.state.pageNo at the end and it's not updating. I want to use this logic later in infinite scroll but not able to get it working now.

```<code> import React, { Component } from "react";
 import {
  View,
  Text,
  StyleSheet,
  Button,
  TouchableOpacity,
  FlatList,
  Alert
  } from "react-native";

 class InfiniteScrollRedux extends Component {
   constructor(props) {
      super(props);
      this.state = {
        loading: false,
        pageNo: 1,
        data: [
            { id: 1, name: "Name01" },
            { id: 2, name: "Name02" },
            { id: 3, name: "Name03" },
            { id: 4, name: "Name04" },
            { id: 5, name: "Name05" },
            { id: 6, name: "Name06" }
        ]
    };
}

myFunction = () => {
    this.setState({ pageNo: this.state.pageNo++ });
};

render() {
    return (
        <View>
            <FlatList
                data={this.state.data}
                renderItem={({ item }) => (
                    <View style={mystyle.mainCard}>
                        <Text style={mystyle.titleText}> {item.id} </Text>
                        <View style={{ marginTop: 200 }} />
                        <Text style={mystyle.nameText}> {item.name} </Text>
                    </View>
                )}
                keyExtractor={item => item.id}
                onEndReached={this.myFunction}
                onEndThreshold={0}
            />
            <Text style={{ margin: 20, padding: 20, fontSize: 20 }}>
                {this.state.pageNo}
            </Text>
        </View>
      );
   }
}

const mystyle = StyleSheet.create({
 mainCard: {
    backgroundColor: "#2F4F4F",
    marginBottom: 1,
    padding: 5
},
titleText: {
    fontSize: 20,
    color: "#F0FFFF"
},
nameText: {
    fontSize: 14,
    color: "#F0FFFF"
 }
 });

 export default InfiniteScrollRedux;
</code>```

答: The property you are looking for in FlatList is onEndReachedThreshold instead of onEndThreshold.</p>

Body:
Im trying to call a function on onEndReached of a FlatList but it's not working.

I'm calling the this.state.pageNo at the end and it's not updating. I want to use this logic later in infinite scroll but not able to get it working now.

 import React, { Component } from "react";
 import {
  View,
  Text,
  StyleSheet,
  Button,
  TouchableOpacity,
  FlatList,
  Alert
  } from "react-native";

 class InfiniteScrollRedux extends Component {
   constructor(props) {
      super(props);
      this.state = {
        loading: false,
        pageNo: 1,
        data: [
            { id: 1, name: "Name01" },
            { id: 2, name: "Name02" },
            { id: 3, name: "Name03" },
            { id: 4, name: "Name04" },
            { id: 5, name: "Name05" },
            { id: 6, name: "Name06" }
        ]
    };
}

myFunction = () => {
    this.setState({ pageNo: this.state.pageNo++ });
};

render() {
    return (
        <View>
            <FlatList
                data={this.state.data}
                renderItem={({ item }) => (
                    <View style={mystyle.mainCard}>
                        <Text style={mystyle.titleText}> {item.id} </Text>
                        <View style={{ marginTop: 200 }} />
                        <Text style={mystyle.nameText}> {item.name} </Text>
                    </View>
                )}
                keyExtractor={item => item.id}
                onEndReached={this.myFunction}
                onEndThreshold={0}
            />
            <Text style={{ margin: 20, padding: 20, fontSize: 20 }}>
                {this.state.pageNo}
            </Text>
        </View>
      );
   }
}

const mystyle = StyleSheet.create({
 mainCard: {
    backgroundColor: "#2F4F4F",
    marginBottom: 1,
    padding: 5
},
titleText: {
    fontSize: 20,
    color: "#F0FFFF"
},
nameText: {
    fontSize: 14,
    color: "#F0FFFF"
 }
 });

 export default InfiniteScrollRedux;


问:
inter thread communication in java
How do threads that rely on one another communicate in Java?

For example, I am building a web crawler with threads that need data that comes from other threads.

答:
Below is example for Inter thread communication:</p>

```<code>public class Main {
    public static void main(String[] args) {
        Chat m = new Chat();
        new T1(m);
        new T2(m);
    }
}

class Chat {
    boolean flag = false;

    public synchronized void FromSam(String msg) {
        if (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(msg);
        flag = true;
        notify();
    }

    public synchronized void FromJam(String msg) {
        if (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(msg);
        flag = false;
        notify();
    }
}

class T1 implements Runnable {
    Chat m;
    String[] s1 = { "Hello Jam", "How are you ?", "I am also doing fine!" };

    public T1(Chat m1) {
        this.m = m1;
        new Thread(this, "Sam").start();
    }

    public void run() {
        for (int i = 0; i < s1.length; i++) {
            m.FromSam(s1[i]);
        }
    }
}

class T2 implements Runnable {
    Chat m;
    String[] s2 = { "HI Sam", "I am good,And U ?", "ha haa" };

    public T2(Chat m2) {
        this.m = m2;
        new Thread(this, "Jam").start();
    }

    public void run() {
        for (int i = 0; i < s2.length; i++) {
            m.FromJam(s2[i]);
        }
    }
}
</code>```

Title: inter thread communication in java

Body:
Below is example for Inter thread communication:

public class Main {
    public static void main(String[] args) {
        Chat m = new Chat();
        new T1(m);
        new T2(m);
    }
}

class Chat {
    boolean flag = false;

    public synchronized void FromSam(String msg) {
        if (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(msg);
        flag = true;
        notify();
    }

    public synchronized void FromJam(String msg) {
        if (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println(msg);
        flag = false;
        notify();
    }
}

class T1 implements Runnable {
    Chat m;
    String[] s1 = { "Hello Jam", "How are you ?", "I am also doing fine!" };

    public T1(Chat m1) {
        this.m = m1;
        new Thread(this, "Sam").start();
    }

    public void run() {
        for (int i = 0; i < s1.length; i++) {
            m.FromSam(s1[i]);
        }
    }
}

class T2 implements Runnable {
    Chat m;
    String[] s2 = { "HI Sam", "I am good,And U ?", "ha haa" };

    public T2(Chat m2) {
        this.m = m2;
        new Thread(this, "Jam").start();
    }

    public void run() {
        for (int i = 0; i < s2.length; i++) {
            m.FromJam(s2[i]);
        }
    }
}