问:
Count in the SUM SQL
I have the sql function like the following:

```<code>SELECT
    SUM(3 * tb_spp.bulanan_spp ),
    COUNT(tb_bulan.id) AS JUMLAH,
    SUM( count(tb_bulan.id) * tb_angsuran_spp.nominal_spp ),
SUM( (3 * tb_spp.bulanan_spp) - (3 * tb_angsuran_spp.nominal_spp) ) as SPP
FROM tb_spp, tb_angsuran_spp, tb_bulan
where tb_spp.id_siswa = tb_angsuran_spp.id_siswa and tb_spp.id_siswa = '1'
and tb_bulan.id = tb_angsuran_spp.id_bulan
and tb_bulan.id between '1' and '2'
</code>```

But when i run the error message appears '# 1111 - Invalid use of group function'

What is the cause and how is the solution?

答:
sum(count()) isn't generally allowed.  There are a few other changes I would make to the query as well:

```<code>SELECT SUM( 3 * s.bulanan_spp ),
       count(b.id) as JUMLAH,
       SUM(a.nominal_spp ),
       SUM( (3 * s.bulanan_spp) - (3 * a.nominal_spp) ) as SPP
FROM tb_spp s JOIN
     tb_angsuran_spp a
     on s.id_siswa = a.id_siswa join
     tb_bulan b
     on b.id = a.id_bulan
where s.id_siswa = 1 and
      b.id between 1 and 2;
</code>```

Notes:

Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

Table aliases make the query easier to write and to read.

Ids are usually numbers; hence I removed the single quotes (they are appropriate for strings).

I'm not sure that  your sums and counts will produce correct answers. If not, ask another question, including sample data and desired results.  This answer addresses the syntax problems in this question.

Title: Count in the SUM SQL

Body:
I have the sql function like the following:

SELECT
    SUM(3 * tb_spp.bulanan_spp ),
    COUNT(tb_bulan.id) AS JUMLAH,
    SUM( count(tb_bulan.id) * tb_angsuran_spp.nominal_spp ),
SUM( (3 * tb_spp.bulanan_spp) - (3 * tb_angsuran_spp.nominal_spp) ) as SPP
FROM tb_spp, tb_angsuran_spp, tb_bulan
where tb_spp.id_siswa = tb_angsuran_spp.id_siswa and tb_spp.id_siswa = '1'
and tb_bulan.id = tb_angsuran_spp.id_bulan
and tb_bulan.id between '1' and '2'

But when i run the error message appears '# 1111 - Invalid use of group function'

What is the cause and how is the solution?

Body:
sum(count()) isn't generally allowed.  There are a few other changes I would make to the query as well:

SELECT SUM( 3 * s.bulanan_spp ),
       count(b.id) as JUMLAH,
       SUM(a.nominal_spp ),
       SUM( (3 * s.bulanan_spp) - (3 * a.nominal_spp) ) as SPP
FROM tb_spp s JOIN
     tb_angsuran_spp a
     on s.id_siswa = a.id_siswa join
     tb_bulan b
     on b.id = a.id_bulan
where s.id_siswa = 1 and
      b.id between 1 and 2;

Notes:

Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

Table aliases make the query easier to write and to read.

Ids are usually numbers; hence I removed the single quotes (they are appropriate for strings).

I'm not sure that  your sums and counts will produce correct answers. If not, ask another question, including sample data and desired results.  This answer addresses the syntax problems in this question.


来源: stackexchange

问:
How to Async Mongoose Controller
Trying to configure a SignUp() controller that can update multiple (separate) user accounts when a referral code is provided by the user.

Basic Flow:

Verify email doesn't already exist in system

Find the driver w/ userID matching the rider's refCode (FindOneAndUpdate)

If Found: Add the userID of each user to the other users [clients] list

Only need to do a refCode match if isRider

If any of those fail... Return the specific error to the client/user

This does not work. But essentially, this is what I'm trying to accomplish...

```<code>// POST `/signup` (Create a new local user)
export function signUp(req, res, next) {
  const newUser = new User({
    email: req.body.email,
    password: req.body.password,
    profile: {
      userID: req.body.userID,
      refCode: req.body.refCode,
      isRider: req.body.isRider
    }
  });

  User.findOne({ email: req.body.email }, (findErr, foundUser) => {
    if (foundUser) {
      return res.status(409).send('This e-mail address already exists');
    }
    // riders must link to a driver
    if (req.body.isRider) {
      // find driver + add rider ID to clients
      return User.findOneAndUpdate({ 'profile.userID': req.body.refCode }, { $push: { clients: newUser.profile.userID }}).exec()
        .then((err, foundDriver) => {
          if (err) {
            return res.status(409).send('Error searching for driver');
          } else if (!foundDriver) {
            return res.status(409).send(`We can't find your driver (${req.body.refCode})!`);
          }
          // add driver ID to rider's clients
          newUser.clients = [req.body.refCode];

          return newUser.save((saveErr) => {
            if (saveErr) return next(saveErr);
            return req.logIn(newUser, (loginErr) => {
              if (loginErr) return res.sendStatus(401);
              return res.json(newUser.profile);
            });
          });
        });
    }

    return newUser.save((saveErr) => {
      if (saveErr) return next(saveErr);
      return req.logIn(newUser, (loginErr) => {
        if (loginErr) return res.sendStatus(401);
        return res.json(newUser.profile);
      });
    });
  });
}
</code>```

Tried to configure it as a pure promise but no luck. Most of the examples out there all seem different to me... Also could not figure out how to handle/throw specific errors using the mongoose docs.

Greatly appreciated if anyone can lend a hand, Thx!

UPDATE:
Ippi's answer helped a ton - Thx!

This does the trick. Remember to return null from .then() after the req.login stuff to avoid warnings - Any tips on how to improve this are appreciated - Thx!

```<code>  const createUser = (foundUser) => {
    if (foundUser) { throw new Error('This e-mail address already exist.'); }
    if (!req.body.isRider) { return newUser.save(); }
    return User.findOneAndUpdate({ 'profile.userID': req.body.refCode.toLowerCase() }, { $push: { clients: newUser.profile.userID }}).exec()
      .then((driver) => {
        if (!driver) { throw new Error('We can\'t find your driver.'); }
        newUser.clients = [req.body.refCode];
        return newUser.save();
      })
      .catch(() => { throw new Error('There was a database error.'); });
  };

  User.findOne({ email: req.body.email }).exec()
    .then(createUser)
    .then((user) => {
      if (user.profile) {
        req.logIn(user, (loginErr) => {
          if (loginErr) return res.sendStatus(401);
          return res.status(200).send({ profile: user.profile, clients: user.clients });
        });
      } else { res.status(409); }
      return null;
    })
    .catch((err) => { return res.status(409).send(err.message); });
</code>```

答:
```<code>function signUp(req, res, next) {

return new Promise((resolve, reject) => {

    const newUser = new User({
        email: req.body.email,
        password: req.body.password,
        profile: {
            userID: req.body.userID,
            refCode: req.body.refCode,
            isRider: req.body.isRider
        }
    });

    User.findOne({ email: req.body.email }, (findErr, foundUser) => {
        if (foundUser) {
            // return res.status(409).send('This e-mail address already exists');
            reject('This e-mail address already exists');
        }
        // riders must link to a driver
        if (req.body.isRider) {
            // find driver + add rider ID clients
            return User.findOneAndUpdate({ 'profile.userID': req.body.refCode }, { $push: { clients: newUser.profile.userID } }).exec()
                .then((err, foundDriver) => {
                    if (err) {
                        // return res.status(409).send('Error searching for driver');
                        reject('Error searching for driver');
                    } else if (!foundDriver) {
                        // return res.status(409).send(`We can't find your driver (${req.body.refCode})!`);
                        reject(`We can't find your driver (${req.body.refCode})!`);
                    }
                    // add driver ID to rider's clients
                    newUser.clients = [req.body.refCode];

                    newUser.save((saveErr) => {
                        if (saveErr)
                            // next(saveErr);
                            reject(saveErr);
                        req.logIn(newUser, (loginErr) => {
                            if (loginErr)
                                // return res.sendStatus(401);
                                reject('401');
                            // return res.json(newUser.profile);
                            resolve(newUser.profile);
                        });
                    });
                });
        }

        newUser.save((saveErr) => {
            if (saveErr)
                // return next(saveErr);
                reject(saveErr);
            req.logIn(newUser, (loginErr) => {
                if (loginErr)
                    // return res.sendStatus(401);
                    reject(loginErr);
                // return res.json(newUser.profile);
                resolve(newUser.profile);
            });
        });
    });

});}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to Async Mongoose Controller

Body:
Trying to configure a SignUp() controller that can update multiple (separate) user accounts when a referral code is provided by the user.

Basic Flow:

Verify email doesn't already exist in system

Find the driver w/ userID matching the rider's refCode (FindOneAndUpdate)

If Found: Add the userID of each user to the other users [clients] list

Only need to do a refCode match if isRider

If any of those fail... Return the specific error to the client/user

This does not work. But essentially, this is what I'm trying to accomplish...

// POST `/signup` (Create a new local user)
export function signUp(req, res, next) {
  const newUser = new User({
    email: req.body.email,
    password: req.body.password,
    profile: {
      userID: req.body.userID,
      refCode: req.body.refCode,
      isRider: req.body.isRider
    }
  });

  User.findOne({ email: req.body.email }, (findErr, foundUser) => {
    if (foundUser) {
      return res.status(409).send('This e-mail address already exists');
    }
    // riders must link to a driver
    if (req.body.isRider) {
      // find driver + add rider ID to clients
      return User.findOneAndUpdate({ 'profile.userID': req.body.refCode }, { $push: { clients: newUser.profile.userID }}).exec()
        .then((err, foundDriver) => {
          if (err) {
            return res.status(409).send('Error searching for driver');
          } else if (!foundDriver) {
            return res.status(409).send(`We can't find your driver (${req.body.refCode})!`);
          }
          // add driver ID to rider's clients
          newUser.clients = [req.body.refCode];

          return newUser.save((saveErr) => {
            if (saveErr) return next(saveErr);
            return req.logIn(newUser, (loginErr) => {
              if (loginErr) return res.sendStatus(401);
              return res.json(newUser.profile);
            });
          });
        });
    }

    return newUser.save((saveErr) => {
      if (saveErr) return next(saveErr);
      return req.logIn(newUser, (loginErr) => {
        if (loginErr) return res.sendStatus(401);
        return res.json(newUser.profile);
      });
    });
  });
}

Tried to configure it as a pure promise but no luck. Most of the examples out there all seem different to me... Also could not figure out how to handle/throw specific errors using the mongoose docs.

Greatly appreciated if anyone can lend a hand, Thx!

UPDATE:
Ippi's answer helped a ton - Thx!

This does the trick. Remember to return null from .then() after the req.login stuff to avoid warnings - Any tips on how to improve this are appreciated - Thx!

  const createUser = (foundUser) => {
    if (foundUser) { throw new Error('This e-mail address already exist.'); }
    if (!req.body.isRider) { return newUser.save(); }
    return User.findOneAndUpdate({ 'profile.userID': req.body.refCode.toLowerCase() }, { $push: { clients: newUser.profile.userID }}).exec()
      .then((driver) => {
        if (!driver) { throw new Error('We can\'t find your driver.'); }
        newUser.clients = [req.body.refCode];
        return newUser.save();
      })
      .catch(() => { throw new Error('There was a database error.'); });
  };

  User.findOne({ email: req.body.email }).exec()
    .then(createUser)
    .then((user) => {
      if (user.profile) {
        req.logIn(user, (loginErr) => {
          if (loginErr) return res.sendStatus(401);
          return res.status(200).send({ profile: user.profile, clients: user.clients });
        });
      } else { res.status(409); }
      return null;
    })
    .catch((err) => { return res.status(409).send(err.message); });


问:
How to check whether Azure Blob Storage upload was successful?
I'm using an Azure SAS URL to upload a file to a blob storage:

```<code>var blockBlob = new Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob(new System.Uri(sasUrl));
blockBlob.UploadFromFile(filePath);
</code>```

The file exists on my disk, and the URL should be correct since it is automatically retrieved from the Windows Store Ingestion API (and, if I slightly change one character in the URL's signature part, the upload fails with HTTP 403).

However, when checking

```<code>var blobs = blockBlob.Container.ListBlobs();
</code>```

the result is Count = 0, so I'm wondering if the upload was successful? Unfortunately, the UploadFromFile method (similarly to the UploadFromStream method) has no return type, so I'm not sure how to retrieve the upload's result).

If I try to connect to the SAS URL using Azure Storage Explorer, listing
blob containers fails with the error "Authentication Error. Signature fields not well formed". I tried URL escaping the URL's signature part since that seems to be the reason for that error in some similar cases, but that doesn't solve the problem.

Is there any way to check the status of a blob upload? Has anybody an idea why an auto-generated URL (delivered by one of Microsoft's official APIs) can not be connected to using Azure Explorer?

答:
Please examine the sp field of your SAS. It shows the rights you are authorized to do with the blob. For example, sp=rw means you could read the blob and write content to the blob using this SAS. sp=w means you can only write content to the blob using this SAS.

If you have the read right, you can copy the SAS URL to the browser address bar. The browser will download or show the blob content for you.

Is there any way to check the status of a blob upload?

If no exception throws from your code, it means the blob has been uploaded successfully. Otherwise, a exception will be thrown.

```<code>try
{
    blockBlob.UploadFromFile(filePath);
}
catch(Exception ex)
{
    //uploaded failed
}
</code>```

You can also confirm it using any web debugging proxy tool(ex. Fiddler) to capture the response message from storage server. 201 Created status code will be returned if the blob has been uploaded successfully.

Has anybody an idea why an auto-generated URL (delivered by one of Microsoft's official APIs) can not be connected to using Azure Explorer?

Azure Storage Explorer only allow us to connect a Storage Account using SAS or attach a storage service (blob container, queue, or table) using an SAS. It doesn't allow us to connect a blob item using SAS.

Body:
I'm using an Azure SAS URL to upload a file to a blob storage:

var blockBlob = new Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob(new System.Uri(sasUrl));
blockBlob.UploadFromFile(filePath);

The file exists on my disk, and the URL should be correct since it is automatically retrieved from the Windows Store Ingestion API (and, if I slightly change one character in the URL's signature part, the upload fails with HTTP 403).

However, when checking

var blobs = blockBlob.Container.ListBlobs();

the result is Count = 0, so I'm wondering if the upload was successful? Unfortunately, the UploadFromFile method (similarly to the UploadFromStream method) has no return type, so I'm not sure how to retrieve the upload's result).

If I try to connect to the SAS URL using Azure Storage Explorer, listing
blob containers fails with the error "Authentication Error. Signature fields not well formed". I tried URL escaping the URL's signature part since that seems to be the reason for that error in some similar cases, but that doesn't solve the problem.

Is there any way to check the status of a blob upload? Has anybody an idea why an auto-generated URL (delivered by one of Microsoft's official APIs) can not be connected to using Azure Explorer?

Body:
Please examine the sp field of your SAS. It shows the rights you are authorized to do with the blob. For example, sp=rw means you could read the blob and write content to the blob using this SAS. sp=w means you can only write content to the blob using this SAS.

If you have the read right, you can copy the SAS URL to the browser address bar. The browser will download or show the blob content for you.

Is there any way to check the status of a blob upload?

If no exception throws from your code, it means the blob has been uploaded successfully. Otherwise, a exception will be thrown.

try
{
    blockBlob.UploadFromFile(filePath);
}
catch(Exception ex)
{
    //uploaded failed
}

You can also confirm it using any web debugging proxy tool(ex. Fiddler) to capture the response message from storage server. 201 Created status code will be returned if the blob has been uploaded successfully.

Has anybody an idea why an auto-generated URL (delivered by one of Microsoft's official APIs) can not be connected to using Azure Explorer?

Azure Storage Explorer only allow us to connect a Storage Account using SAS or attach a storage service (blob container, queue, or table) using an SAS. It doesn't allow us to connect a blob item using SAS.


问:
How to get SIZE_MAX in C89
I'm trying to get SIZE_MAX in C89.

I thought of the following way to find SIZE_MAX:

```<code>const size_t SIZE_MAX = -1;
</code>```

Since the standard (§6.2.1.2 ANSI C) says:

When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged. Otherwise: if the unsigned integer has greater size, the signed integer is first promoted to the signed integer corresponding to the unsigned integer; the value is converted to unsigned by adding to it one greater than the largest number that can be represented in the unsigned integer type 28

With footnote 28:

In a two's-complement representation, there is no actual change in the bit pattern except filling the high-order bits with copies of the sign bit if the unsigned integer has greater size.

This seems like this has defined behavior, but I'm not quite sure if I understand the wording of that paragraph correctly.

Note that this question is explicitly about C89, so this doesn't answer my question because the standard has different wording.

If that doesn't work, the other way I came up with is:

```<code>size_t get_size_max() {
    static size_t max = 0;
    if (max == 0) {
        max -= 1U;
    }

    return max;
}
</code>```

But I couldn't find anything about unsigned integer underflow in the standard, so I'm poking in the dark here.

答:
I recommend using the macro definition as described in M.M's answer.

In some cases, you might need a similar macro, but as a numerical constant, so that you can use it in preprocessor directives like #if VALUE > 42 ... #endif. I commented that in such cases, a helper program can be run at compile time, to compute and print a header file defining such constants.

Obviously, this will not work when cross-compiling to a different architecture; in that case, the header file must be provided by some other way. (For example, the project could have a subdirectory of pre-generated headers, and a list of known architectures for each, so that the user can simply copy the header file into place.)

Creating a Makefile and associated facilities for running such programs (and only if the user did not copy the header file into place), is not difficult.

First, let's say your program consists of two source files, foo.c:

```<code>#include <stdlib.h>
extern void hello(void);

int main(void)
{
    hello();
    return EXIT_SUCCESS;
}
</code>```

and a bar.c:

```<code>#include <stdio.h>
#include "size_max.h"

#define  STRINGIFY_(s) #s
#define  STRINGIFY(s) STRINGIFY_(s)

void hello(void)
{
    fputs("SIZE_MAX = \"" STRINGIFY(SIZE_MAX) "\".\n", stdout);
}
</code>```

The above bar.c converts the SIZE_MAX preprocessor macro to a string, and prints it. If we had #define SIZE_MAX (size_t)(-1), it would print SIZE_MAX = "(size_t)(-1)".

Note that bar.c includes file size_max.h, which we do not have. This is the header file we intend to generate using our helper program, size_max.c:

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

int main(void)
{
    printf("#ifndef SIZE_MAX\n");
    printf("#define SIZE_MAX %lluU\n", (unsigned long long)(size_t)(-1));
    printf("#endif\n");
    return EXIT_SUCCESS;
}
</code>```

chux noted in a comment that u suffix (for sufficiently large unsigned integer type) might be necessary.  If that is not what you require, I'm sure you can modify the macro generator helper to suit your needs.

M.M noted in a comment that %z is not supported by ANSI C/ISO C90, so the above program first creates the constant using (size_t)(-1), then casts and prints it in the unsigned long long format.

Now, Makefiles can be written in an OS-agnostic manner, but I'm too lazy to do that here, so I shall use the values that work with GNU tools. To make it work on other systems, you only need to modify the values of

CC, to reflect the compiler you use

CFLAGS, to reflect your preferred compiler options

LD, to reflect your linker, unless the same as CC

LDFLAGS, if you need some linker flags (maybe -lm?)

RM, to reflect the command to delete unnecessary files

File names, if your build system requires some funky file name extension for executables

Anyway, here's the Makefile:

```<code>CC      := gcc
CFLAGS  := -Wall -O2
LD      := $(CC)
LDFLAGS := $(CFLAGS)
RM      := rm -f

# Programs to be built
PROGS   := example

# Relative path to use for executing the header generator helper program
HEADERGEN := ./headergen

# Rules that do not correspond to actual files
.PHONY: all clean headergen

# Default rule is to build all binaries
all: $(PROGS)

# Clean rule removes build files and binaries
clean:
    -$(RM) $(PROGS) $(HELPROG) *.o size_max.h

# Rule to "rebuild" size_max.h
size_max.h: size_max.c
    -@$(RM) $(HEADERGEN) size_max.h
    @$(CC) $(CFLAGS) $^ -o $(HEADERGEN)
    $(HEADERGEN) > size_max.h
    @$(RM) $(HEADERGEN)

# Rule to build object files from .c source files
%.o: %.c size_max.h
    $(CC) $(CFLAGS) -c $<

# Example binary requires foo.o and bar.o:
example: foo.o bar.o size_max.h
    $(LD) $(LDFLAGS) foo.o bar.o -o $@
</code>```

Note that the indentation should use tabs, not spaces, so if you copy-paste the above, run e.g. sed -e 's|^  *|\t|' -i Makefile to fix it.

Before zipping or tarring the source tree, run make clean to remove any generated files from it.

Note the extra size_max.h in the recipe prerequisites. It tells make to ensure that size_max.h exists before it can complete the recipe.

The downside of this approach is that you cannot use $^ in link recipes to refer to all prerequisite file names. $< refers to the first prerequisite file name. If you use GNU make or a compatible make, you can use $(filter-out %.h, %^) (to list all prerequisites except for header files), though.

If all your binaries are built from a single source with the same name, you can replace the last two recipes with

```<code># All programs are built from same name source files:
$(PROGS): %: %.c size_max.h
    $(CC) $(CFLAGS) $< $(LDFLAGS) -o $@
</code>```

On my system, running

```<code>make clean all && ./example
</code>```

outputs

```<code>rm -f example  *.o size_max.h
./headergen > size_max.h
gcc -Wall -O2 -c foo.c
gcc -Wall -O2 -c bar.c
gcc -Wall -O2 foo.o bar.o -o example
SIZE_MAX = "18446744073709551615U".
</code>```

and running

```<code>make CC="gcc-5" CFLAGS="-Wall -std=c99 -pedantic -m32" clean all && ./example
</code>```

outputs

```<code>rm -f example  *.o size_max.h
./headergen > size_max.h
gcc-5 -Wall -std=c99 -pedantic -m32 -c foo.c
gcc-5 -Wall -std=c99 -pedantic -m32 -c bar.c
gcc-5 -Wall -std=c99 -pedantic -m32 foo.o bar.o -o example
SIZE_MAX = "4294967295U".
</code>```

Note that make does not detect if you change compiler options, if you edit the Makefile or use different CFLAGS= or CC= options when running make, so you do need then specify the clean target first, to ensure you start from a clean slate with the new settings in effect.

During normal editing and builds, when you don't change compilers or compiler options, there is no need to make clean between builds.

Title: How to get SIZE_MAX in C89

Body:
I'm trying to get SIZE_MAX in C89.

I thought of the following way to find SIZE_MAX:

const size_t SIZE_MAX = -1;

Since the standard (§6.2.1.2 ANSI C) says:

When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged. Otherwise: if the unsigned integer has greater size, the signed integer is first promoted to the signed integer corresponding to the unsigned integer; the value is converted to unsigned by adding to it one greater than the largest number that can be represented in the unsigned integer type 28

With footnote 28:

In a two's-complement representation, there is no actual change in the bit pattern except filling the high-order bits with copies of the sign bit if the unsigned integer has greater size.

This seems like this has defined behavior, but I'm not quite sure if I understand the wording of that paragraph correctly.

Note that this question is explicitly about C89, so this doesn't answer my question because the standard has different wording.

If that doesn't work, the other way I came up with is:

size_t get_size_max() {
    static size_t max = 0;
    if (max == 0) {
        max -= 1U;
    }

    return max;
}

But I couldn't find anything about unsigned integer underflow in the standard, so I'm poking in the dark here.

Body:
I recommend using the macro definition as described in M.M's answer.

In some cases, you might need a similar macro, but as a numerical constant, so that you can use it in preprocessor directives like #if VALUE > 42 ... #endif. I commented that in such cases, a helper program can be run at compile time, to compute and print a header file defining such constants.

Obviously, this will not work when cross-compiling to a different architecture; in that case, the header file must be provided by some other way. (For example, the project could have a subdirectory of pre-generated headers, and a list of known architectures for each, so that the user can simply copy the header file into place.)

Creating a Makefile and associated facilities for running such programs (and only if the user did not copy the header file into place), is not difficult.

First, let's say your program consists of two source files, foo.c:

#include <stdlib.h>
extern void hello(void);

int main(void)
{
    hello();
    return EXIT_SUCCESS;
}

and a bar.c:

#include <stdio.h>
#include "size_max.h"

#define  STRINGIFY_(s) #s
#define  STRINGIFY(s) STRINGIFY_(s)

void hello(void)
{
    fputs("SIZE_MAX = \"" STRINGIFY(SIZE_MAX) "\".\n", stdout);
}

The above bar.c converts the SIZE_MAX preprocessor macro to a string, and prints it. If we had #define SIZE_MAX (size_t)(-1), it would print SIZE_MAX = "(size_t)(-1)".

Note that bar.c includes file size_max.h, which we do not have. This is the header file we intend to generate using our helper program, size_max.c:

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

int main(void)
{
    printf("#ifndef SIZE_MAX\n");
    printf("#define SIZE_MAX %lluU\n", (unsigned long long)(size_t)(-1));
    printf("#endif\n");
    return EXIT_SUCCESS;
}

chux noted in a comment that u suffix (for sufficiently large unsigned integer type) might be necessary.  If that is not what you require, I'm sure you can modify the macro generator helper to suit your needs.

M.M noted in a comment that %z is not supported by ANSI C/ISO C90, so the above program first creates the constant using (size_t)(-1), then casts and prints it in the unsigned long long format.

Now, Makefiles can be written in an OS-agnostic manner, but I'm too lazy to do that here, so I shall use the values that work with GNU tools. To make it work on other systems, you only need to modify the values of

CC, to reflect the compiler you use

CFLAGS, to reflect your preferred compiler options

LD, to reflect your linker, unless the same as CC

LDFLAGS, if you need some linker flags (maybe -lm?)

RM, to reflect the command to delete unnecessary files

File names, if your build system requires some funky file name extension for executables

Anyway, here's the Makefile:

CC      := gcc
CFLAGS  := -Wall -O2
LD      := $(CC)
LDFLAGS := $(CFLAGS)
RM      := rm -f

# Programs to be built
PROGS   := example

# Relative path to use for executing the header generator helper program
HEADERGEN := ./headergen

# Rules that do not correspond to actual files
.PHONY: all clean headergen

# Default rule is to build all binaries
all: $(PROGS)

# Clean rule removes build files and binaries
clean:
    -$(RM) $(PROGS) $(HELPROG) *.o size_max.h

# Rule to "rebuild" size_max.h
size_max.h: size_max.c
    -@$(RM) $(HEADERGEN) size_max.h
    @$(CC) $(CFLAGS) $^ -o $(HEADERGEN)
    $(HEADERGEN) > size_max.h
    @$(RM) $(HEADERGEN)

# Rule to build object files from .c source files
%.o: %.c size_max.h
    $(CC) $(CFLAGS) -c $<

# Example binary requires foo.o and bar.o:
example: foo.o bar.o size_max.h
    $(LD) $(LDFLAGS) foo.o bar.o -o $@

Note that the indentation should use tabs, not spaces, so if you copy-paste the above, run e.g. sed -e 's|^  *|\t|' -i Makefile to fix it.

Before zipping or tarring the source tree, run make clean to remove any generated files from it.

Note the extra size_max.h in the recipe prerequisites. It tells make to ensure that size_max.h exists before it can complete the recipe.

The downside of this approach is that you cannot use $^ in link recipes to refer to all prerequisite file names. $< refers to the first prerequisite file name. If you use GNU make or a compatible make, you can use $(filter-out %.h, %^) (to list all prerequisites except for header files), though.

If all your binaries are built from a single source with the same name, you can replace the last two recipes with

# All programs are built from same name source files:
$(PROGS): %: %.c size_max.h
    $(CC) $(CFLAGS) $< $(LDFLAGS) -o $@

On my system, running

make clean all && ./example

outputs

rm -f example  *.o size_max.h
./headergen > size_max.h
gcc -Wall -O2 -c foo.c
gcc -Wall -O2 -c bar.c
gcc -Wall -O2 foo.o bar.o -o example
SIZE_MAX = "18446744073709551615U".

and running

make CC="gcc-5" CFLAGS="-Wall -std=c99 -pedantic -m32" clean all && ./example

outputs

rm -f example  *.o size_max.h
./headergen > size_max.h
gcc-5 -Wall -std=c99 -pedantic -m32 -c foo.c
gcc-5 -Wall -std=c99 -pedantic -m32 -c bar.c
gcc-5 -Wall -std=c99 -pedantic -m32 foo.o bar.o -o example
SIZE_MAX = "4294967295U".

Note that make does not detect if you change compiler options, if you edit the Makefile or use different CFLAGS= or CC= options when running make, so you do need then specify the clean target first, to ensure you start from a clean slate with the new settings in effect.

During normal editing and builds, when you don't change compilers or compiler options, there is no need to make clean between builds.


问:
How would I go about making this error message appear when form field is not right?
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

```<code>if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}
</code>```

In the form, I have a span class like so:

```<code><span class="error">'.$error.'</span>
</code>```

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

答:
My suggest is to use ajax call when submit,

according to the answer come back, you update the span of error.

you can find a lot of examples in web like

http://jqueryfordesigners.com/using-ajax-to-validate-forms/

http://www.the-art-of-web.com/javascript/ajax-validate/

ContentLicense: CC BY-SA 2.5

Body:
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}

In the form, I have a span class like so:

'.$error.'

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!


问:
Ordering a array of arrays in a 'fair' manner
I have an array of arrays created with N=9

```<code>a = [1,2,3,4,5,6,7,8,9]
b = a.combination(2).to_a
</code>```

I would like to take N%2 of the sub-arrays out at a time with no number occurring twice, for example the first time this would be:

```<code>[[1,2],[3,4],[5,6],[7,8]]
</code>```

This means 9 was not picked. A second time I would take out

```<code>[[1,3],[2,4],[5,7],[6,8]]
</code>```

Again 9 not being picked.
Eventually I would be left with

```<code> [[1,9],[2,9],[3,9],[4,9],[5,9],[6, 9],[7, 9],[8, 9]]
</code>```

which means I can no longer pick 4 arrays with no duplicate numbers.

How can I order my array so that each number is left out only once instead of 9 all the time?

The use case is as follows:

```<code>students = [1,2,3,4,5,6,7,8,9]
available_combinations = a.combination(2).to_a

def make_pairs
 available_students = students
 while available_students.length > 1 do
  student_combination = find_sub_array(available_combinations, available_students.first, available_students)
   available_combinations.delete(student_combination)
   available_students -= student_combination
 end
end

 def find_sub_array(available_combinations, student, available_students)
 available_combinations.each do |subarray|
  if subarray.include?(student) && (subarray - available_students).empty?
    return subarray
  end
 end
end
</code>```

I would like to run make_pairs multiple times, until available_combinations no longer has enough pairs left.

答:
For odd numbers, just add another dummy number like 0 or :bye:

```<code>students = [1,2,3,4,5,6,7,8,9,:bye]
</code>```

Now when you pull n%2 pairs, at least one will be paired with a :bye. That is the odd student out in that pairing. Each student will have an equal number of :bye rounds.

Edit: I'm assuming you are pulling 5 pairs in this example and discarding the pair with the :bye to ensure it doesn't repeat.

Body:
I have an array of arrays created with N=9

a = [1,2,3,4,5,6,7,8,9]
b = a.combination(2).to_a

I would like to take N%2 of the sub-arrays out at a time with no number occurring twice, for example the first time this would be:

[[1,2],[3,4],[5,6],[7,8]]

This means 9 was not picked. A second time I would take out

[[1,3],[2,4],[5,7],[6,8]]

Again 9 not being picked.
Eventually I would be left with

 [[1,9],[2,9],[3,9],[4,9],[5,9],[6, 9],[7, 9],[8, 9]]

which means I can no longer pick 4 arrays with no duplicate numbers.

How can I order my array so that each number is left out only once instead of 9 all the time?

The use case is as follows:

students = [1,2,3,4,5,6,7,8,9]
available_combinations = a.combination(2).to_a

def make_pairs
 available_students = students
 while available_students.length > 1 do
  student_combination = find_sub_array(available_combinations, available_students.first, available_students)
   available_combinations.delete(student_combination)
   available_students -= student_combination
 end
end

 def find_sub_array(available_combinations, student, available_students)
 available_combinations.each do |subarray|
  if subarray.include?(student) && (subarray - available_students).empty?
    return subarray
  end
 end
end

I would like to run make_pairs multiple times, until available_combinations no longer has enough pairs left.

Body:
For odd numbers, just add another dummy number like 0 or :bye:

students = [1,2,3,4,5,6,7,8,9,:bye]

Now when you pull n%2 pairs, at least one will be paired with a :bye. That is the odd student out in that pairing. Each student will have an equal number of :bye rounds.

Edit: I'm assuming you are pulling 5 pairs in this example and discarding the pair with the :bye to ensure it doesn't repeat.


问:
Is a HTTP proxy allowed to cache a page by default?
If a web server returns the HTTP response without any caching headers (e.g. Pragma and Cache-Control, ETag or Last-Modified), is a standards-conforming HTTP proxy allowed to cache the page and return the cached version (without consulting the web server) if the web browser requests the same URL again?

I'm interested for HTTP/1.0 and HTTP/1.1.

I was reading https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4, and I think the answer is yes (the proxy is allowed to cache the page and return the cached version by default). Did I understand it correctly?

答:
The answer is yes.  There's a concept in http called heuristic freshness, which allows a cache to calculate an estimated age of a resource, and then choose an arbitrary proportion of that value to use as a freshness lifetime, during which it can serve the cached content to clients.

There are some restrictions, for example it's not supposed to do this if there's a query string in the request, or (if my memory serves me) if the response lacks a Date header.


问:
What's the best way to cancel event propagation between nested ng-click calls?
Here's an example.  Let's say I want to have an image overlay like a lot of sites.  So when you click a thumbnail, a black overlay appears over your whole window, and a larger version of the image is centered in it.  Clicking the black overlay dismisses it; clicking the image will call a function that shows the next image.

The html:

```<code><div ng-controller="OverlayCtrl" class="overlay" ng-click="hideOverlay()">
    <img src="http://some_src" ng-click="nextImage()"/>
</div>
</code>```

The javascript:

```<code>function OverlayCtrl($scope) {
    $scope.hideOverlay = function() {
        // Some code to hdie the overlay
    }
    $scope.nextImage = function() {
        // Some code to find and display the next image
    }
}
</code>```

The problem is that with this setup, if you click the image, both nextImage() and hideOverlay() are called.  But what I want is for only nextImage() to be called.

I know you can capture and cancel the event in the nextImage() function like this:

```<code>if (window.event) {
    window.event.stopPropagation();
}
</code>```

...But I want to know if there's a better AngularJS way of doing it that won't require me to prefix all of the functions on elements inside the overlay with this snippet.

答:
```<code><div ng-click="methodName(event)"></div>
</code>```

IN controller use

```<code>$scope.methodName = function(event) {
    event.stopPropagation();
}
</code>```

Body:
Here's an example.  Let's say I want to have an image overlay like a lot of sites.  So when you click a thumbnail, a black overlay appears over your whole window, and a larger version of the image is centered in it.  Clicking the black overlay dismisses it; clicking the image will call a function that shows the next image.

The html:

The javascript:

function OverlayCtrl($scope) {
    $scope.hideOverlay = function() {
        // Some code to hdie the overlay
    }
    $scope.nextImage = function() {
        // Some code to find and display the next image
    }
}

The problem is that with this setup, if you click the image, both nextImage() and hideOverlay() are called.  But what I want is for only nextImage() to be called.

I know you can capture and cancel the event in the nextImage() function like this:

if (window.event) {
    window.event.stopPropagation();
}

...But I want to know if there's a better AngularJS way of doing it that won't require me to prefix all of the functions on elements inside the overlay with this snippet.

Body:
<div ng-click="methodName(event)"></div>

IN controller use

$scope.methodName = function(event) {
    event.stopPropagation();
}

ContentLicense: CC BY-SA 4.0


问:
open graph meta tags not working in facebook
Okay, I can not figure this out for the life of me. I created a new site, and wanted to add the open graph meta tags like on my old site (which is working fine). When I added these to my new site and tested them in facebook debugger, it says that they are not present. I get this back when I test it:

Inferred Property The 'og:url' property should be explicitly provided, even if a value can be inferred from other tags.

Inferred Property  The 'og:title' property should be explicitly provided, even if a value can be inferred from other tags.

Inferred Property  The 'og:description' property should be explicitly provided, even if a value can be inferred from other tags.

Inferred Property  The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags.

Also, it is not finding the image even though it is there as well. Here is the code from my site as follows:

```<code><meta property="fb:admins" content="100002683693547" />
<meta property="og:title" content="JDerry Art" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://www.jderry.com/2015" />
<meta property="og:image" content="http://www.jderry.com/2015/images/link.jpg" />
<meta property="og:description" content="Art and Illustration by J. Derry" />
<meta property="og:site_name" content="JDerry Art" />
</code>```

my new site URL is: http://www.jderry.com/2015/
I have tried all suggestions for similar issues on here and other forums, as well as tried moving the order of the tags to no avail...
Any and all help will be greatly appreciated as this is starting to drive me nuts as there appears to be no definite answer and all suggested solutions yield the same problem. Thanks in advance.

P.S. My old site was xhtml and my new site is HTML5, not sure if that has any influence on this issue?

答:
HEY GUYS HERE'S MY ANSWER, i HOPE IT WORKS FOR YOU AS WELL: I try'ed every sugestion I can get my hands on, and what worked for me was this:
go to: https://developers.facebook.com/tools/debug/og/object/

Once you are there, paste the URL from the web page you wish to share in the box, and hit the button "retrieve information from the new extraction"

After you do this, it will appear some information, WHAT YOU ARE GOING TO NEED from this information, is the "og:update_time" element, on the right side of this element you will have a number, you are going to need to add this element along with this number to your meta information, someting like this:

meta property="og:updated_time"       content="1496821331"

every number for every page is UNIQUE, but I find that if you put the same number in more than one web page it still works, but you may wanna put the specific number for each web page you are going to need (NOTE: in my experience,
you DONT need to have the image in the same directory as the meta is, actually, I use an image from google images and work out just fine!)
this is an example of the og:updated_time

I hope this can help you guys.

Body:
Okay, I can not figure this out for the life of me. I created a new site, and wanted to add the open graph meta tags like on my old site (which is working fine). When I added these to my new site and tested them in facebook debugger, it says that they are not present. I get this back when I test it:

Inferred Property The 'og:url' property should be explicitly provided, even if a value can be inferred from other tags.

Inferred Property  The 'og:title' property should be explicitly provided, even if a value can be inferred from other tags.

Inferred Property  The 'og:description' property should be explicitly provided, even if a value can be inferred from other tags.

Inferred Property  The 'og:image' property should be explicitly provided, even if a value can be inferred from other tags.

Also, it is not finding the image even though it is there as well. Here is the code from my site as follows:

<meta property="fb:admins" content="100002683693547" />
<meta property="og:title" content="JDerry Art" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://www.jderry.com/2015" />
<meta property="og:image" content="http://www.jderry.com/2015/images/link.jpg" />
<meta property="og:description" content="Art and Illustration by J. Derry" />
<meta property="og:site_name" content="JDerry Art" />

my new site URL is: http://www.jderry.com/2015/
I have tried all suggestions for similar issues on here and other forums, as well as tried moving the order of the tags to no avail...
Any and all help will be greatly appreciated as this is starting to drive me nuts as there appears to be no definite answer and all suggested solutions yield the same problem. Thanks in advance.

P.S. My old site was xhtml and my new site is HTML5, not sure if that has any influence on this issue?


问:
How to select data to array field?
TableA:

```<code>idA: 1, name: John;
</code>```

TableB:

```<code>idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;
</code>```

And I want the finally JSON result look like that:

```<code>[
    {
        "idA": 1,
        "name": "John",
        "TableB": [
            {
                "idB": 1,
                "product": "milk",
                "idA": 1
            },
            {
                "idB": 2,
                "product": "egg",
                "idA": 1
            }
        ]
    }
]
</code>```

I'm using PHP and mySQL.
How's the query should be?
Thanks too much!
I'm so sorry because my English isn't well.

答:
Use Mysqli or pdo. Check the code below. I didn't test but it should work.</p>

```<code>// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM TableA ORDER BY idA";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

  $rows = array();
  while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;

    $sqlSub = "SELECT * FROM TableB WHERE idA = '{$row['idA']}' ORDER BY idB";
    $resultSub = mysqli_query($conn, $resultSub);

    if (mysqli_num_rows($resultSub) > 0) {
        while ($rowSub = mysqli_fetch_array($resultSub)) {

            $rows[]['TableB'][] = $rowSub;
        }
    }

  }

  echo json_encode($rows);
} else {
  echo "no results found";
}
</code>```

Title: How to select data to array field?

Body:
TableA:

idA: 1, name: John;

TableB:

idB: 1, product: milk, idA: 1;
idB: 2, product: egg, idA: 1;

And I want the finally JSON result look like that:

[
    {
        "idA": 1,
        "name": "John",
        "TableB": [
            {
                "idB": 1,
                "product": "milk",
                "idA": 1
            },
            {
                "idB": 2,
                "product": "egg",
                "idA": 1
            }
        ]
    }
]

I'm using PHP and mySQL.
How's the query should be?
Thanks too much!
I'm so sorry because my English isn't well.

Body:
Use Mysqli or pdo. Check the code below. I didn't test but it should work.

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT * FROM TableA ORDER BY idA";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

  $rows = array();
  while ($row = mysqli_fetch_array($result)) {
    $rows[] = $row;

    $sqlSub = "SELECT * FROM TableB WHERE idA = '{$row['idA']}' ORDER BY idB";
    $resultSub = mysqli_query($conn, $resultSub);

    if (mysqli_num_rows($resultSub) > 0) {
        while ($rowSub = mysqli_fetch_array($resultSub)) {

            $rows[]['TableB'][] = $rowSub;
        }
    }

  }

  echo json_encode($rows);
} else {
  echo "no results found";
}


答:
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.</p>

```<code><?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $comment = $_POST['comment'];
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
    Email: $email
    Phone Number: $phone
    Comment: $comment", "From: $email" );
    } else {
        $error = "Please fill in the required fields.";
    }
}else{ ?>

<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
    <span class="error><?php echo $error; ?></span>
    Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
    Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
    Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
    Comment: <br/>
    <textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
    <input type="submit" value="Submit Email"/>
</form></div>

<?php } ?>
</code>```

Title: How would I go about making this error message appear when form field is not right?

Body:
Well without the rest of the page I'm not sure why this isn't working already but you should post back to the same page not just an empty action. I would do it this way.

<?php
$error = $name = $email = $phone = $comment = "";
if(isset($_POST['submit'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $comment = $_POST['comment'];
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
    Email: $email
    Phone Number: $phone
    Comment: $comment", "From: $email" );
    } else {
        $error = "Please fill in the required fields.";
    }
}else{ ?>

<div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
<form method="post" action="emailMonthlySpecials.php">
    <span class="error><?php echo $error; ?></span>
    Name: <input name="name" type="text" value="<?php echo $name;?>"/><br />
    Email: <input name="email" type="text" value="<?php echo $email;?>"/><br />
    Phone Number: <input name="phone" type="text" <?php echo $phone;?>"/><br /><br />
    Comment: <br/>
    <textarea name="comment" rows="5" cols="30"><?php echo $comment;?></textarea><br /><br />
    <input type="submit" value="Submit Email"/>
</form></div>

<?php } ?>


问:
PHP/Laravel file existence verification not working
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:

```<code>$counter = 0;
do{
  $nomeArquivo = $post->id . "-{$counter}"  . "." . $arq->extension();

  $counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));

Storage::putFileAs('/public', $arq, $nomeArquivo);
</code>```

This code above runs inside a foreach($files as $arq) where $files are the files from the form input.

Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html

答:
Use the File Facade to check for the existence of a file:

File::exists($myfile)

http://laravel-recipes.com/recipes/123/determining-if-a-file-exists

Body:
I have a <form> with a multiple file input that stores those files into the server. The names of the files must follow a numeric standard and that's why I rename them before storing. Each post has an ID an can have more than one file so the pattern is: post-id + dash and a number + file extension, this way, if the same post has two file with the same extensions, the dash + number will avoid them to be overwriten. So, before I store the files I run a loop to find the proper number to the name. The problem is, the function to verify the existence of the file seems not to be returning true when it should. The code:

$counter = 0;
do{
  $nomeArquivo = $post->id . "-{$counter}"  . "." . $arq->extension();

  $counter++;
//these commented are other ways of verification I tried
//}while(Storage::exists($nomeArquivo));
//}while(file_exists("/storage/" . $nomeArquivo));
}while(is_file("/storage/" . $post->id . "-{$counter}"));

Storage::putFileAs('/public', $arq, $nomeArquivo);

This code above runs inside a foreach($files as $arq) where $files are the files from the form input.

Reference: https://laravel.com/docs/5.4/filesystem and https://laravel.com/api/5.4/Illuminate/Filesystem/Filesystem.html


问:
R: Read raster layers as one object to apply a function in each ENVI file
I have an ENVI file (82_83_test.envi) that contains biweekly raster layers from 1982 to 1983. That is 24 layers per year, 48 layers in total. I would like to create a for loop to apply a function to perform time-series analysis per year, i.e., R will run through 24 layers in a pixel and calculate 5 parameters with the function "fun" for all pixels for that year. Ultimately, I would like to have 5 plots (5 parameters) for each year, so a total of 10 plots for two years.

I tried working with 1 ENVI file with 2 years of data and 2 ENVI files with 1 year of data in each file. I used brickstack_to_raster_list() from the library spatial.tools to read the file, and I get 48 layers. However, I would like to get 2 chunks (1982 and 1983) which consist of 24 layers for each chunk, so that I can run the equation.

Maybe something like brickstack_to_raster_list() then merge the 1st layer to 24th into one, followed by the 25th to 48th layer into one?

```<code>new <- stack("82_83_test.envi")
new1<- brickstack_to_raster_list(new)
</code>```

new1 returns 48 raster layers. For example,

```<code>new1
[[1]]
class       : RasterLayer
band        : 1  (of  48  bands)
dimensions  : 151, 101, 15251  (nrow, ncol, ncell)
resolution  : 0.08333333, 0.08333333  (x, y)
extent      : -105.0833, -96.66667, 56.66667, 69.25  (xmin, xmax, ymin,
ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84
+towgs84=0,0,0
data source : C:\*\82_83_test.envi
names       : Band.1
values      : -32768, 5038  (min, max)
</code>```

The other approach is to concatenate multiple annual ENVI files into a list.

```<code>new <- stack("1982_test.envi")
new1<- stack(new,new)
new2<- brickstack_to_raster_list(new1)
</code>```

Both methods above yield the same result, although I am not certain about its efficiency. Because after getting this set up, I will be generating data from 1982 to 2015, and so efficiency matters a lot.

Below is the function that I would like to apply in the for loop.

```<code># A is an unknown that will be the number of components in the list.
for (i in length(A)) {
new1[new1<=-1000]<-0
Data_value<-new1/10000
# assign 0 to pixel value that is less than -1000 and divide by 10000 in order to use the equation
DOY<-(1:nlayers(new1)*15)
# so that the unit will be in days instead of the number of weeks.

fun<- function(x) { if (all(is.na(x[1]))) { return(rep(NA,5)) } else {
fitForThisData  <-nls(x~ a+((b/(1+ exp(-c*(DOY-e))))- (g/(1+ exp(-d*(DOY-
f))))), alg="port",start=list(a=0.1,b=1,g=1,c=0.04,d=0.04,e=112,f=218),
lower=list(a=0,b=0.3,g=0.3,c=-1,d=-1,e=20,f=100),
upper=list(a=0.4,b=2,g=2,c=1,d=1,e=230,f=365),
control=nls.control(maxiter=2000, tol = 1e-15, minFactor = 1/1024,
warnOnly=TRUE))
SOS<-(coef(fitForThisData)[6] -(4.562/(2*coef(fitForThisData)[4])))
EOS<-(coef(fitForThisData)[7] -(4.562/(2*coef(fitForThisData)[5])))
LOS<-(EOS-SOS)
SPUDOY<-(1.317*((-1/coef(fitForThisData)[4])+ coef(fitForThisData)[6]))
P_TAmplitude<-(SPUDOY-SOS)
return (c(SOS,EOS,LOS,SPUDOY,P_TAmplitude))
}
}
}

equation<-calc(Data_value,fun,forceapply=TRUE)
plot(equation)
</code>```

I would truly appreciate your advice on how to do this. Thank you very much!

答:
UPDATE: I was able to loop the function but my guess is that the calculation was done on all raster layers after comparing it with the truth value. However, two files of the same content with different file names are produced, because two files have the same summaries.</p>

```<code>new <- stack("82_83_test.envi")
new[new<=-1000]<-0
Data_value<-new/10000
nlayers <- nlayers(new)
nyears <- nlayers(new)/24
DOY<-((1:nlayers(new))/nyears)*15
dummy<- FALSE

for (i in 1:nyears) {
  for (j in (1+24*(i-1)):(24*i)) {
    fun<-function (x)
    equation<-calc(Data_value,fun,forceapply=TRUE)
    date<- 1981+i
    writeRaster(equation,filename=paste("Output",date,".envi",sep=""),
    format="ENVI",overwrite=T)
    if (j == nlayers){
    dummy<-TRUE
    break
    if (dummy) {break}
}
}
</code>```

Body:
I have an ENVI file (82_83_test.envi) that contains biweekly raster layers from 1982 to 1983. That is 24 layers per year, 48 layers in total. I would like to create a for loop to apply a function to perform time-series analysis per year, i.e., R will run through 24 layers in a pixel and calculate 5 parameters with the function "fun" for all pixels for that year. Ultimately, I would like to have 5 plots (5 parameters) for each year, so a total of 10 plots for two years.

I tried working with 1 ENVI file with 2 years of data and 2 ENVI files with 1 year of data in each file. I used brickstack_to_raster_list() from the library spatial.tools to read the file, and I get 48 layers. However, I would like to get 2 chunks (1982 and 1983) which consist of 24 layers for each chunk, so that I can run the equation.

Maybe something like brickstack_to_raster_list() then merge the 1st layer to 24th into one, followed by the 25th to 48th layer into one?

new <- stack("82_83_test.envi")
new1<- brickstack_to_raster_list(new)

new1 returns 48 raster layers. For example,

new1
[[1]]
class       : RasterLayer
band        : 1  (of  48  bands)
dimensions  : 151, 101, 15251  (nrow, ncol, ncell)
resolution  : 0.08333333, 0.08333333  (x, y)
extent      : -105.0833, -96.66667, 56.66667, 69.25  (xmin, xmax, ymin,
ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84
+towgs84=0,0,0
data source : C:\*\82_83_test.envi
names       : Band.1
values      : -32768, 5038  (min, max)

The other approach is to concatenate multiple annual ENVI files into a list.

new <- stack("1982_test.envi")
new1<- stack(new,new)
new2<- brickstack_to_raster_list(new1)

Both methods above yield the same result, although I am not certain about its efficiency. Because after getting this set up, I will be generating data from 1982 to 2015, and so efficiency matters a lot.

Below is the function that I would like to apply in the for loop.

# A is an unknown that will be the number of components in the list.
for (i in length(A)) {
new1[new1<=-1000]<-0
Data_value<-new1/10000
# assign 0 to pixel value that is less than -1000 and divide by 10000 in order to use the equation
DOY<-(1:nlayers(new1)*15)
# so that the unit will be in days instead of the number of weeks.

fun<- function(x) { if (all(is.na(x[1]))) { return(rep(NA,5)) } else {
fitForThisData  <-nls(x~ a+((b/(1+ exp(-c*(DOY-e))))- (g/(1+ exp(-d*(DOY-
f))))), alg="port",start=list(a=0.1,b=1,g=1,c=0.04,d=0.04,e=112,f=218),
lower=list(a=0,b=0.3,g=0.3,c=-1,d=-1,e=20,f=100),
upper=list(a=0.4,b=2,g=2,c=1,d=1,e=230,f=365),
control=nls.control(maxiter=2000, tol = 1e-15, minFactor = 1/1024,
warnOnly=TRUE))
SOS<-(coef(fitForThisData)[6] -(4.562/(2*coef(fitForThisData)[4])))
EOS<-(coef(fitForThisData)[7] -(4.562/(2*coef(fitForThisData)[5])))
LOS<-(EOS-SOS)
SPUDOY<-(1.317*((-1/coef(fitForThisData)[4])+ coef(fitForThisData)[6]))
P_TAmplitude<-(SPUDOY-SOS)
return (c(SOS,EOS,LOS,SPUDOY,P_TAmplitude))
}
}
}

equation<-calc(Data_value,fun,forceapply=TRUE)
plot(equation)

I would truly appreciate your advice on how to do this. Thank you very much!

Body:
UPDATE: I was able to loop the function but my guess is that the calculation was done on all raster layers after comparing it with the truth value. However, two files of the same content with different file names are produced, because two files have the same summaries.

new <- stack("82_83_test.envi")
new[new<=-1000]<-0
Data_value<-new/10000
nlayers <- nlayers(new)
nyears <- nlayers(new)/24
DOY<-((1:nlayers(new))/nyears)*15
dummy<- FALSE

for (i in 1:nyears) {
  for (j in (1+24*(i-1)):(24*i)) {
    fun<-function (x)
    equation<-calc(Data_value,fun,forceapply=TRUE)
    date<- 1981+i
    writeRaster(equation,filename=paste("Output",date,".envi",sep=""),
    format="ENVI",overwrite=T)
    if (j == nlayers){
    dummy<-TRUE
    break
    if (dummy) {break}
}
}


问:
Row highlighting based on due date using php
I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.

I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.

With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:

Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.

Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.

Anything else should utilize the bootstrap "table-striped" styling.

Here is the code I've put together

```<code>//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}
</code>```

I then add the $highlight_css to the HTML.

So far some of the functionality is working. Proper highlighting is not added for:

Dates older than 1 day (i.e. yesterday, last week)

How can this functionality be achieved?

答:
I would use this instead:

```<code><?php

$dueDates =["06/05/2017","06/06/2017","06/07/2017","06/08/2017","06/09/2017","06/10/2017","06/11/2017","06/12/2017"];
$table = "<table class='table table-bordered'><thead><tr><th>Date</th></tr></thead><tbody>";
$today = date_create(date('m/d/Y')); // example: 06/07/2017
foreach ($dueDates as $dueStr) {
    $due = date_create($dueStr);
    $diff = date_diff($today, $due)->format("%r%a");
    $highlight_css = "";
    if ($diff > 1 && $diff <= 3) {
        $highlight_css = " warning";
    } elseif ($diff == 1) {
        $highlight_css = " danger";
    }
    $table .= "<tr class='$highlight_css'><td>$dueStr</td></tr>";
}
$table .= "</tbody></table>";
?>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<?php
echo $table;
</code>```

Body:
I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.

I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.

With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:

Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.

Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.

Anything else should utilize the bootstrap "table-striped" styling.

Here is the code I've put together

//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}

I then add the $highlight_css to the HTML.

So far some of the functionality is working. Proper highlighting is not added for:

Dates older than 1 day (i.e. yesterday, last week)

How can this functionality be achieved?

Body:
I would use this instead:

<?php

$dueDates =["06/05/2017","06/06/2017","06/07/2017","06/08/2017","06/09/2017","06/10/2017","06/11/2017","06/12/2017"];
$table = "<table class='table table-bordered'><thead><tr><th>Date</th></tr></thead><tbody>";
$today = date_create(date('m/d/Y')); // example: 06/07/2017
foreach ($dueDates as $dueStr) {
    $due = date_create($dueStr);
    $diff = date_diff($today, $due)->format("%r%a");
    $highlight_css = "";
    if ($diff > 1 && $diff <= 3) {
        $highlight_css = " warning";
    } elseif ($diff == 1) {
        $highlight_css = " danger";
    }
    $table .= "<tr class='$highlight_css'><td>$dueStr</td></tr>";
}
$table .= "</tbody></table>";
?>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" >
<?php
echo $table;


问:
How to save an actual address stored in the pointer
Is it possible to save an actual address stored in the pointer instead of the object that it points to?

I mean, boost::serialization automatically serializes the object referenced by a and not the address of the object but in my case there are a lot of references to the same object and I don't want to serialize them all over and over again, so I need to save just the address of such pointer.

答:
That will not work.  The memory location of an object at run time will vary from one execution of the program to the next.

What would work is some kind of object catalog or ID system, for example if an object had a built-in unique ID.  The pointer address might even work for this if you only use it as an object ID.

Then (if you override normal serialization and deserialization) you could write each object once, read them the first time they are referenced and store the location into a map, then if the same ID is deserialized again you use the map to find its pointer.

This is probably not worth it unless you have a huge amount of duplication of a single type of object.

```<code>boost::archive::text_oarchive oa(ofs);
....
unsigned long long int foo = (unsigned long long int) &my_object;  // might need to lower warning level depending on compiler
oa << foo;
</code>```

You should make sure boost is not already doing this for you.  The boost.org tutorial on serialization means it only writes out objects referenced by pointer once: http://www.boost.org/doc/libs/1_64_0/libs/serialization/doc/tutorial.html#pointers

"If the same pointer is serialized more than once, only one instance is be added to the archive. When read back, no data is read back in. The only operation that occurs is for the second pointer is set equal to the first."

Body:
That will not work.  The memory location of an object at run time will vary from one execution of the program to the next.

What would work is some kind of object catalog or ID system, for example if an object had a built-in unique ID.  The pointer address might even work for this if you only use it as an object ID.

Then (if you override normal serialization and deserialization) you could write each object once, read them the first time they are referenced and store the location into a map, then if the same ID is deserialized again you use the map to find its pointer.

This is probably not worth it unless you have a huge amount of duplication of a single type of object.

boost::archive::text_oarchive oa(ofs);
....
unsigned long long int foo = (unsigned long long int) &my_object;  // might need to lower warning level depending on compiler
oa << foo;

You should make sure boost is not already doing this for you.  The boost.org tutorial on serialization means it only writes out objects referenced by pointer once: http://www.boost.org/doc/libs/1_64_0/libs/serialization/doc/tutorial.html#pointers

"If the same pointer is serialized more than once, only one instance is be added to the archive. When read back, no data is read back in. The only operation that occurs is for the second pointer is set equal to the first."


问:
Azure Custom URL with HTTPS
I have an web app on Azure with a myapp.azurewebsites.net address and have been following the guide here:

```<code>https://learn.microsoft.com/en-USazure/app-service-web/app-service-web-tutorial-custom-domain
</code>```

Based on this, I have added the hostname in the app settings and it has been verified.  I have also added the A Record and TXT record in my domain hosting provider based on the instructions (A Record points to the Azure website IP address) along with installing the SSL certificate for the external domain on the external host.

However when I type in the custom domain name, it goes to the page on the external host instead of the Azure website

What I would like to happen is: https://custom.domain will show the same as https://myapp.azurewebsites.net

Is this even possible ?

答:
As far as I know, the certificate is used to tell the user(client browser) this website is secure.

Normally, there are two reasons why the browser window showed the non-secure page.

You're probably using a self-signed certificate.

You may have left out intermediate certificates when you export your certificate to the PFX file.

So if you want your custom domain doesn't show the non-secure page, you need buy a certificate from the azure or some other company.

After verifying domain ownership, then you could bind this certificate to your azure web app.

After this operation, it will work well.

More details about how to buy certificate with custom domain in the azure, you could refer to this article.

After buying the azure certificate, you could find the certificate as below image shows:

After binding the certificate well, it will not show the no-secure page in the browser.

Image 1:

Image 2:

I saw that creating the fully hosted domain also created A Records pointing to their IP address instead of Azure. Do I need to override these somehow, or how should it work? The tutorial did not show if "contoso.com" was https.

In my opinion, fully hosted domain is the hosting company creates its own web app server to hosting your web app and change the A records point to its own web app server IP address.

So you will find the custom domain show that company pages.

If you want to set the custom domain still points to the azure web app, you need change the A record's IP address as azure web app's address.

If you could find the hosting company has already create a certificate and verified your domain.

Then you could download it and upload it in the azure web app's portal.

After binding the SSL, it will work well.

If the fully hosted domain doesn't contain the certificate, you need buy the certificate by yourself again, upload it in the azure web app portal, change the A record points to your azure web app's IP address.

The problem it seems is that when using a fully hosted site, I can add an A Record but the hosting company keeps using their own A Record which I cannot change, it is part of their "uneditable settings."

Since I don't know how your hosting company's fully hosted site works.

Now, the most easily way is you connect to its support team to change the domain setting firstly, then you follow this article to buy a azure certificate and bind it.

For second option, did you mean to download the SSL from the hosting company and use it as 3rd party SSL in Azure? The A Record would still point to the hosting company right ? Also it seems I do not have an option to download the SSL either in PFX format, I can only view the certificate configuration (CSR, key, etc).

Yes, if you have permission to download the PFX format(if you don't know how to do it, please connect to your hosting company support), you could use it as third party SSL.

Title: Azure Custom URL with HTTPS

Body:
I have an web app on Azure with a myapp.azurewebsites.net address and have been following the guide here:

https://learn.microsoft.com/en-USazure/app-service-web/app-service-web-tutorial-custom-domain

Based on this, I have added the hostname in the app settings and it has been verified.  I have also added the A Record and TXT record in my domain hosting provider based on the instructions (A Record points to the Azure website IP address) along with installing the SSL certificate for the external domain on the external host.

However when I type in the custom domain name, it goes to the page on the external host instead of the Azure website

What I would like to happen is: https://custom.domain will show the same as https://myapp.azurewebsites.net

Is this even possible ?


问:
Azure function is not triggering on scheduled time
Note: Even though it may seem duplicate, My issue is different and I request you to read complete description before hastily marking the question down just by reading Question title.

I opened "Azure function is not triggering on scheduled time " issue on official "azure-webjobs-sdk-script" git repository on May 24, 2017-but there is no reply yet. So I am re-asking this here.

I am using azure function in consumption plan, and have scheduled it to execute at every 4.00 am utc by setting following cron expression in function.json:

```<code>{

"bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 0 4 * * *"
    }
  ],
  "disabled": false
}
</code>```

Azure function does get execute on time only if I am logged into portal or clicks on function blade. It does not invoke when I am logged out from portal (suggesting either system listener or function go to sleep after some interval).

Their official documentation states that functions in consumption plan do not require any other settings (like Always on) to keep the function alive, instances of the Azure Functions host are dynamically added and removed based on the number of incoming events.. So as per documentation, no other settings I have to configure to execute function in consumption plan.

What I have tried?

From "Timer triggered azure function not getting triggered" question on SO, I re-checked and ensured my plan (consumption plan) and time zone. (I want it to run in utc, so no explicit setting is required)

From "#1445: Azure function timer trigger not firing" git issue, I checked whether it was just logs that are not appearing. But I am certainly sure, that its not the logs but the actual function does not get triggered unless I am having my portal on or trigger it manually.

I tried to check whether this behavior exists if I change the schedule to a more closer recursive invocations--I scheduled function to get executed at every 2 hours, and this schedule perfectly worked even when I logged out or did not awake function manually. This means, there is some issue when schedule is set to run on larger set of intervals (in my case each day)

答: As discussed here in #1534, deleting and redeploying the function completely in new function app did not reproduce the issue. So deleting the function and/or function app-and redeploying the same should make things working. Meanwhile, Azure team has announced to add internal logging which will help future diagnosis.</p>

Body:
Note: Even though it may seem duplicate, My issue is different and I request you to read complete description before hastily marking the question down just by reading Question title.

I opened "Azure function is not triggering on scheduled time " issue on official "azure-webjobs-sdk-script" git repository on May 24, 2017-but there is no reply yet. So I am re-asking this here.

I am using azure function in consumption plan, and have scheduled it to execute at every 4.00 am utc by setting following cron expression in function.json:

{

"bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 0 4 * * *"
    }
  ],
  "disabled": false
}

Azure function does get execute on time only if I am logged into portal or clicks on function blade. It does not invoke when I am logged out from portal (suggesting either system listener or function go to sleep after some interval).

Their official documentation states that functions in consumption plan do not require any other settings (like Always on) to keep the function alive, instances of the Azure Functions host are dynamically added and removed based on the number of incoming events.. So as per documentation, no other settings I have to configure to execute function in consumption plan.

What I have tried?

From "Timer triggered azure function not getting triggered" question on SO, I re-checked and ensured my plan (consumption plan) and time zone. (I want it to run in utc, so no explicit setting is required)

From "#1445: Azure function timer trigger not firing" git issue, I checked whether it was just logs that are not appearing. But I am certainly sure, that its not the logs but the actual function does not get triggered unless I am having my portal on or trigger it manually.

I tried to check whether this behavior exists if I change the schedule to a more closer recursive invocations--I scheduled function to get executed at every 2 hours, and this schedule perfectly worked even when I logged out or did not awake function manually. This means, there is some issue when schedule is set to run on larger set of intervals (in my case each day)


问:
Get JavaScript reference to element created in ng-repeat
I'm trying to obtain a
 created inside ng-repeat so that I can add content inside generated by a third-party library.

Attempt 1:

```<code><div ng-init="init()">
  <div ng-repeat="item in items">
    <div id="{{ item.id }}"></div>
  </div>
</div>

$scope.init = function() {
  for (var i in items) {
    var element = document.getElementById(items[i].id);
    generateInnerHtml(element);
  }
};
</code>```

Attempt 2:

```<code><div ng-init="init()">
  <div ng-repeat="item in items">
    <div id="{{ item.id }}" ng-init="addContent(item.id)"></div>
  </div>
</div>

$scope.addContent = function(id) {
  var element = document.getElementById(id);
  generateInnerHtml(element);
};
</code>```

Attempt 3:

```<code><div ng-init="init()">
  <div ng-repeat="item in items">
    <div id="{{ item.id }}" ng-init="addContent(this)"></div>
  </div>
</div>

$scope.addContent = function(element) {
  generateInnerHtml(element);
};
</code>```

For all three attempts, element is always null or undefined. What's wrong?

答:
In attempts #1 and #2 your function is running before all the Angular directives are processed, so the id of the divs isn't defined yet.

You can wrap your code in $timeout() to force it to wait until the DOM is properly generated:

```<code>angular.module("myApp", [])
  .controller("myController", function($scope, $timeout) {
    $scope.addContent = function(id) {
      $timeout(function() {
        var element = document.getElementById(id);
        generateInnerHtml(element);
      }, 0);
    };

})
</code>```

See demo here: https://jsfiddle.net/1w5ntajm/.

Body:
I'm trying to obtain a
 created inside ng-repeat so that I can add content inside generated by a third-party library.

Attempt 1:

$scope.init = function() {
  for (var i in items) {
    var element = document.getElementById(items[i].id);
    generateInnerHtml(element);
  }
};

Attempt 2:

$scope.addContent = function(id) {
  var element = document.getElementById(id);
  generateInnerHtml(element);
};

Attempt 3:

$scope.addContent = function(element) {
  generateInnerHtml(element);
};

For all three attempts, element is always null or undefined. What's wrong?

Body:
In attempts #1 and #2 your function is running before all the Angular directives are processed, so the id of the divs isn't defined yet.

You can wrap your code in $timeout() to force it to wait until the DOM is properly generated:

angular.module("myApp", [])
  .controller("myController", function($scope, $timeout) {
    $scope.addContent = function(id) {
      $timeout(function() {
        var element = document.getElementById(id);
        generateInnerHtml(element);
      }, 0);
    };

})

See demo here: https://jsfiddle.net/1w5ntajm/.


问:
grafana-influxdb get multiple rows for last timestamp
I am using telegraf-influxdb-grafana together. But I could not get rows for only last timestamp.
Here is what I am doing;

Collecting DB statistics(Running queries at that time) with Telegraf(exec plugin).

Storing output to influxdb

Trying to monitor running queries over grafana

But I need to get all rows at last timestamp.

Here is what I've tried;

```<code>> select * from postgresql_running_queries where time=(select max(time) from postgresql_running_queries)
ERR: error parsing query: found SELECT, expected identifier, string, number, bool at line 1, char 54
</code>```

Here is what I want to see;

```<code>Time                 DB     USER      STATE                QUERY
2017-06-06 14:25.00  mydb   myuser    active               my_query
2017-06-06 14:25.00  mydb   myuser    idle in transaction  my_query2
2017-06-06 14:25.00  mydb2  myuser2   active               my_query3
</code>```

Can any one help me to achive this?
I am open to any solution.

答:
```<code>select last(fieldname) from measurment_name;
</code>```

Query in this format will return last timestamp data from the InfluxDB.

But I am surprised with the fact that you are expecting 3 values for a single timestamp (unless you have different TAG values, refer this documentation how to store duplicate points). You will a ONLY ONE record for a given timestamp. InfluxDB overwrites previous content if there is another entry for same timestamp, here is why.

Your results will be something like (if you don't have different TAG value):

```<code>Time                 DB     USER      STATE                QUERY
2017-06-06 14:25.00  mydb2  myuser2   active               my_query3
</code>```

EDIT:

Based on comment, my guess is you are using TAGs to differentiate, still above query should work, if not, you may try by adding WHERE clause.

Body:
I am using telegraf-influxdb-grafana together. But I could not get rows for only last timestamp.
Here is what I am doing;

Collecting DB statistics(Running queries at that time) with Telegraf(exec plugin).

Storing output to influxdb

Trying to monitor running queries over grafana

But I need to get all rows at last timestamp.

Here is what I've tried;

> select * from postgresql_running_queries where time=(select max(time) from postgresql_running_queries)
ERR: error parsing query: found SELECT, expected identifier, string, number, bool at line 1, char 54

Here is what I want to see;

Time                 DB     USER      STATE                QUERY
2017-06-06 14:25.00  mydb   myuser    active               my_query
2017-06-06 14:25.00  mydb   myuser    idle in transaction  my_query2
2017-06-06 14:25.00  mydb2  myuser2   active               my_query3

Can any one help me to achive this?
I am open to any solution.

Body:
select last(fieldname) from measurment_name;

Query in this format will return last timestamp data from the InfluxDB.

But I am surprised with the fact that you are expecting 3 values for a single timestamp (unless you have different TAG values, refer this documentation how to store duplicate points). You will a ONLY ONE record for a given timestamp. InfluxDB overwrites previous content if there is another entry for same timestamp, here is why.

Your results will be something like (if you don't have different TAG value):

Time                 DB     USER      STATE                QUERY
2017-06-06 14:25.00  mydb2  myuser2   active               my_query3

EDIT:

Based on comment, my guess is you are using TAGs to differentiate, still above query should work, if not, you may try by adding WHERE clause.


问:
Selenium xpath: element not visible on Amazon site
I am trying to write a Selenium test against Amazon site. I want to get "Sign in"  element so that I can click on it.

url: www.amazon.ca

Here is my Selenium Code:

```<code>driver.findElement(By.xpath("//a[@data-nav-role='signin']")).click();
</code>```

But I get Element not visible exception.

I have tried putting Thread.sleep(5000) before element lookup but still the same issue.

I have other ways to pick the element but I want to find out why this Xpath not working in my code.

Note: When trying it in Chrome DevTool Console, it works fine there $x("//a[@data-nav-role='signin']")

答:
The selector you have chosen returns multiple elements i.e. 3. You can verify that by using findElements instead of findElement.

You can either give a precise selector for the specific element you want to click on or you can get all matching elements using findElements, loop through them and click one with a matching attribute e.g. text.

Try:

```<code>driver.findElement(By.id("nav-link-yourAccount")).click();
</code>```

Body:
I am trying to write a Selenium test against Amazon site. I want to get "Sign in"  element so that I can click on it.

url: www.amazon.ca

Here is my Selenium Code:

driver.findElement(By.xpath("//a[@data-nav-role='signin']")).click();

But I get Element not visible exception.

I have tried putting Thread.sleep(5000) before element lookup but still the same issue.

I have other ways to pick the element but I want to find out why this Xpath not working in my code.

Note: When trying it in Chrome DevTool Console, it works fine there $x("//a[@data-nav-role='signin']")

Body:
The selector you have chosen returns multiple elements i.e. 3. You can verify that by using findElements instead of findElement.

You can either give a precise selector for the specific element you want to click on or you can get all matching elements using findElements, loop through them and click one with a matching attribute e.g. text.

Try:

driver.findElement(By.id("nav-link-yourAccount")).click();


问:
MySQL Select multiple rows with almost same value
I am using python and MySQL and I have the following table:

```<code>id    name    value1    value2
1     a       36041     140636
2     b       36046     140647
3     c       36042     140642
4     d       36042     140645
5     e       36040     140642
</code>```

I want to select all those rows which have almost same value1 and value2 (±2). So based on the table above, I want to select row 3 and row 5 only and arrange them in increasing order of value1. How should I write the SELECT query for this?

答:
One way to achieve this by using self-join:

```<code>select t1.*
from table1 t1
join table1 t2
on abs(t1.value1 - t2.value1) <= 2
and abs(t1.value2 - t2.value2) <= 2
and t1.id <> t2.id
order by t1.value1
</code>```

And see demo in Rextester.

Body:
I am using python and MySQL and I have the following table:

id    name    value1    value2
1     a       36041     140636
2     b       36046     140647
3     c       36042     140642
4     d       36042     140645
5     e       36040     140642

I want to select all those rows which have almost same value1 and value2 (±2). So based on the table above, I want to select row 3 and row 5 only and arrange them in increasing order of value1. How should I write the SELECT query for this?

Body:
One way to achieve this by using self-join:

select t1.*
from table1 t1
join table1 t2
on abs(t1.value1 - t2.value1) <= 2
and abs(t1.value2 - t2.value2) <= 2
and t1.id <> t2.id
order by t1.value1

And see demo in Rextester.


问:
VSCode build not working - No build task defined. Mark a task with 'isBuildCommand' in the tasks.json file
I have fresh install of VSCode, and this tiny basic TypeScript app.

First time, when I want to build the app, VScode needs to generate tasks.json.

And it worked long time ago before.

Today I am getting this weird message

No build task defined. Mark a task with 'isBuildCommand' in the tasks.json file.

I don't remember seeing this message before.

But, OK, I click Configure Build Task, select TypeScript task, and tasks.json gets generated.

But, what happens, after I try to build now, Ctrl+Shift+B, and I get the exact same message again

Any ideas? Thanks.

BTW, adding this setting to tasks.json doesnt solve the problem.

答:
In my case, my tasks.json had some nonsense in it. Instead of the "command" property, I wrongly named it "executable"...*

So consider if:

Your JSON is valid syntactically (see screenshot below)

Your JSON is valid according to what VS Code expects

Syntactically invalid:

Schematically invalid:

And while I think the other answers are probably correct (I can't reproduce so I can't verify; the issue has been fixed...), I think when the comment said ...

Closing and reopening the window (without starting Code)

... it may have meant the Reload Window command.

*I wrongly named the tasks.json property "executable", vs "command" because...

I thought "command" was causing issues (it wasn't)

I wanted to run a specific executable in a specific directory like "C:/somewhere/python.exe"; ("command" can do that).

I don't know why I thought "executable" was valid! I thought I was referencing some example, but can't find it... :) )


问:
Logon failure: unknown user name or bad password while reading from Active directory
I have wrapper web services to read from Active Directory. It works fine on DEV; but on Staging / QA, I am getting this error

Logon failure: unknown user name or bad password.

I am able telnet to the Active directory server on 389 (LDAP port) from both DEV & Staging boxes. I tried with different user accounts who has even read only access to active directory; all worked fine on DEV but not on Staging / QA. Any clues?

答:
You might check the permissions of the account that runs the web service, usually on the Staging/QA the security requirements are higher.

UPDATE http://www.velocityreviews.com/forums/t619647-impersonating-and-windows-authentication.html


答:
I think you want a self join:</p>

```<code>select t1.*, t2.*
from t t1 join
     t t2
     on abs(t1.value1 - t2.value1) <= 2 and
        abs(t1.value2 - t2.value2) <= 2 and
        t1.id < t2.id
order by t1.value1
</code>```

Title: MySQL Select multiple rows with almost same value

Body:
I think you want a self join:

select t1.*, t2.*
from t t1 join
     t t2
     on abs(t1.value1 - t2.value1) <= 2 and
        abs(t1.value2 - t2.value2) <= 2 and
        t1.id < t2.id
order by t1.value1


问:
How to transform UIBezierPath/CGPath within a reference frame?
I need to scale a path, but instead of using the path's bounds, the transform should be performed using a larger, enclosing, arbitrary rect. (i.e. a "canvas".)

My problem is how to do that without drawing the canvas.

For example, in the following image:

the blue square indicates the native rect of the path (a rocket in this case).

the purple rect indicates the bounds of the "canvas" or parent coordinate system.

the purple rect is for positioning only; not to be drawn. The whitespace is similarly ignored.

I need to scale the canvas, and keep the transformed rocket path (for clipping operations, caching etc.). i.e. I need to lose the purple rect after transformation.

Ideally, I'd use something like the following fiction:

```<code>var canvasPath = UIBezierPath(rect: canvasRect)
canvasPath.append(rocketPath, withName: "rocket")
canvasPath.doSomeTransformOrOther()
let transformedRocketPath = canvasPath.path(forName: "rocket")
</code>```

Sadly, the magical append(:withName:) and path(forName:) methods do not exist, even if UIBezierPath or CGPath treated subpaths like this. Alas!

Another approach could be to temporarily add points to the path, one for each canvas corner. Then, transform the path. Then, walk the path with CGPath's (hideous) apply(info:function:) method, rebuild the path without the canvas points, then draw the result. (Yeah, pass the vodka.)

Can anyone offer a more sane solution? Thanks for any helpi

(For those interested: this is related to a problem of how to center irregularly-shaped paths. The purple rect represents the bounds of the minimum enclosing circle. Drawing the rocket with the MEC's coordinate system will make the rocket appear more visually centered, compared to using boundingBox.)

More info: Fitting UIBezierPath/CGPath to circle

答:
Here's my final approach to the problem: use a "canvas" rect that will be scaled along with the path. Then use the canvas rect when translating the (scaled) path. This keeps the path relative to the canvas

An example of doing this is getting a path from an SVG, and then scaling, positioning the path relative not to the path's bounds, but relative to the native dimensions (the 'viewbox') of the SVG. This in turn allows relative positioning of the path within the SVG canvas.

```<code>extension UIBezierPath
{
    func scaled(usingCanvasSize canvasSize: CGSize,
            scale: CGFloat) -> CGRect
    {
        let canvasRect = CGRect(origin: .zero, size: canvasSize)
        let canvasPath = UIBezierPath(rect: canvasRect)

        let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
        canvasPath.apply(scaleTransform)
        self.apply(scaleTransform)

        return canvas.bounds
    }
}

// Usage:

let nativeSVGSize: CGSize = ...   // 'viewBox' size of SVG
let path = UIBezierPath(...)      // From SVG, wherever.
let scale: CGFloat = 0.5

// Scale the path, get a "canvas" rect.
let canvasRect = path.scaled(usingCanvasSize: nativeSVGSize,
        scale: scale)

// Use the (scaled) canvas for info about the path from now on.

// e.g. move the path using the center of the canvasRect.

let pathCenter = canvasRect.center
let destCenter = ...
let movement = CGPoint(x: destCenter.x - pathCenter.x,
        y: destCenter.y - pathCenter.y)

path.apply(CGAffineTransform(translationX: movement.x,
        y: movement.y))
</code>```

Body:
I need to scale a path, but instead of using the path's bounds, the transform should be performed using a larger, enclosing, arbitrary rect. (i.e. a "canvas".)

My problem is how to do that without drawing the canvas.

For example, in the following image:

the blue square indicates the native rect of the path (a rocket in this case).

the purple rect indicates the bounds of the "canvas" or parent coordinate system.

the purple rect is for positioning only; not to be drawn. The whitespace is similarly ignored.

I need to scale the canvas, and keep the transformed rocket path (for clipping operations, caching etc.). i.e. I need to lose the purple rect after transformation.

Ideally, I'd use something like the following fiction:

var canvasPath = UIBezierPath(rect: canvasRect)
canvasPath.append(rocketPath, withName: "rocket")
canvasPath.doSomeTransformOrOther()
let transformedRocketPath = canvasPath.path(forName: "rocket")

Sadly, the magical append(:withName:) and path(forName:) methods do not exist, even if UIBezierPath or CGPath treated subpaths like this. Alas!

Another approach could be to temporarily add points to the path, one for each canvas corner. Then, transform the path. Then, walk the path with CGPath's (hideous) apply(info:function:) method, rebuild the path without the canvas points, then draw the result. (Yeah, pass the vodka.)

Can anyone offer a more sane solution? Thanks for any helpi

(For those interested: this is related to a problem of how to center irregularly-shaped paths. The purple rect represents the bounds of the minimum enclosing circle. Drawing the rocket with the MEC's coordinate system will make the rocket appear more visually centered, compared to using boundingBox.)

More info: Fitting UIBezierPath/CGPath to circle

Body:
Here's my final approach to the problem: use a "canvas" rect that will be scaled along with the path. Then use the canvas rect when translating the (scaled) path. This keeps the path relative to the canvas

An example of doing this is getting a path from an SVG, and then scaling, positioning the path relative not to the path's bounds, but relative to the native dimensions (the 'viewbox') of the SVG. This in turn allows relative positioning of the path within the SVG canvas.

extension UIBezierPath
{
    func scaled(usingCanvasSize canvasSize: CGSize,
            scale: CGFloat) -> CGRect
    {
        let canvasRect = CGRect(origin: .zero, size: canvasSize)
        let canvasPath = UIBezierPath(rect: canvasRect)

        let scaleTransform = CGAffineTransform(scaleX: scale, y: scale)
        canvasPath.apply(scaleTransform)
        self.apply(scaleTransform)

        return canvas.bounds
    }
}

// Usage:

let nativeSVGSize: CGSize = ...   // 'viewBox' size of SVG
let path = UIBezierPath(...)      // From SVG, wherever.
let scale: CGFloat = 0.5

// Scale the path, get a "canvas" rect.
let canvasRect = path.scaled(usingCanvasSize: nativeSVGSize,
        scale: scale)

// Use the (scaled) canvas for info about the path from now on.

// e.g. move the path using the center of the canvasRect.

let pathCenter = canvasRect.center
let destCenter = ...
let movement = CGPoint(x: destCenter.x - pathCenter.x,
        y: destCenter.y - pathCenter.y)

path.apply(CGAffineTransform(translationX: movement.x,
        y: movement.y))