问:
Getting an "expected identified" error when it perfectly on an IDE
I'm using SSH Secure Shell to run and submit my assignment.  I'm getting this error right now:

In file included from a1ms4.c:15:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token
In file included from contacts.c:16:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token

Which is bogus because the exact same code compiled on another IDE.  These are my C files that are reporting the error.  I am not missing a ( or a { or a ; anywhere in my code.  I went through this code for hours to find a potential mistake but couldn't spot anything and despite that, it won't let me submit my assignment.

a1ms4.c

```<code>#define _CRT_SECURE_NO_WARNINGS

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

int main(void)
{
    struct Contact contact;

    printf("Contact Management System\n-------------------------\n");

    getName(&contact.name);

    getAddress(&contact.address);

    getNumbers(&contact.numbers);

    printf("\nContact Details\n---------------");

    printf("\nName Details");

    printf("\nFirst name: %s", contact.name.firstName);

    printf("\nMiddle initial(s): %s", contact.name.middleInitial);

    printf("\nLast name: %s", contact.name.lastName);

    printf("\n");

    printf("\nAddress Details");

    printf("\nStreet number: %d", contact.address.streetNumber);

    printf("\nStreet name: %s", contact.address.street);

    printf("\nApartment: %d", contact.address.apartmentNumber);

    printf("\nPostal code: %s", contact.address.postalCode);

    printf("\nCity: %s", contact.address.city);

    printf("\n");

    printf("\nPhone Numbers:");

    printf("\nCell phone number: %s", contact.numbers.cell);

    printf("\nHome phone number: %s", contact.numbers.home);

    printf("\nBusiness phone number: %s", contact.numbers.business);

    printf("\n");

    printf("\nStructure test for Contact using functions done!\n");

    return 0;
}
</code>```

contacts.c

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include "contacts.h"

void getName(struct Name *name) {
    char one;
    struct Name temporaryName;

    printf("Please enter the contact's first name: ");
    scanf(" %[^\n]", temporaryName.firstName);
    printf("Do you want to enter a middle initial(s)? (y or n): ");
    scanf(" %c", &one);

    if (one == 'y' || one == 'Y') {
        printf("Please enter the contact's middle initial(s): ");
        scanf(" %[^\n]", temporaryName.middleInitial);
    }

    printf("Please enter the contact's last name: ");
    scanf(" %[^\n]", temporaryName.lastName);

    *name = temporaryName;

    return;
}

void getAddress(struct Address *address) {
    char two;
    struct Address temporaryAddress;

    printf("Please enter the contact's street number: ");
    scanf("%d", &temporaryAddress.streetNumber);

    printf("Please enter the contact's street name: ");
    scanf(" %[^\n]", temporaryAddress.street);

    printf("Do you want to enter an appartment number? (y or n): ");
    scanf(" %c", &two);

    if (two == 'y' || two == 'Y') {
        printf("Please enter the contact's appartment number: ");
        scanf(" %d", &temporaryAddress.apartmentNumber);
    }

    printf("Please enter the contact's postal code: ");
    scanf(" %[^\n]", temporaryAddress.postalCode);

    printf("Please enter the contact's city: ");
    scanf(" %[^\n]", temporaryAddress.city);

    *address = temporaryAddress;

    return;
}

void getNumbers(struct Numbers *numbers) {
    char three, four, five;
    struct Numbers temporaryNumbers;

    printf("Do you want to enter a cell phone number? (y or n): ");
    scanf(" %c", &three);

    if (three == 'y' || three == 'Y') {
        printf("Please enter the contact's cell phone number: ");
        scanf(" %[^\n]", temporaryNumbers.cell);
    }

    printf("Do you want to enter a home phone number? (y or n): ");
    scanf(" %c", &four);

    if (four == 'y' || four == 'Y') {
        printf("Please enter the contact's home phone number: ");
        scanf(" %[^\n]", temporaryNumbers.home);
    }

    printf("Do you want to enter a business phone number? (y or n): ");
    scanf(" %c", &five);

    if (five == 'y' || five == 'Y') {
        printf("Please enter the contact's business phone number: ");
        scanf(" %[^\n]", temporaryNumbers.business);
    }

    *numbers = temporaryNumbers;
    return;
}
</code>```

contacts.h

```<code>/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address {
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers {
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact {
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};
</code>```

答:
The error:

```<code>error: expected identifier or â(â before â--â token
</code>```

suggests that you most likely have an invalid character that is unrecognized by the compiler in your code that occurs in a pattern X...stuff...X (where X represents the unrecognized character).

The line being complained about is:

```<code>scanf(" %[^\n]", temporaryAddress.street);
</code>```

The likely cause of the problem is you have included (copied/pasted or otherwise somehow acquired) a unicode or html variation of '"' (double quote) surrounding your scanf format string. (this is a common occurrence when a #ldquo; or #rdquo; (left-double-quote or right-double-quote) is accidentally included in your source file).  Most likely the result of a copy/paste of " %[^\n]" from some web page. Go double check that your double quotes are all ASCII 0x22 (decimal 34) characters.

The error is not apparent in your code above (most likely because in your copy/paste to stack overflow the funky quotes were lost in translation)

The only errors you need to fix in your code (not including all little nits, etc.) are:

```<code>a1ms4.c: In function ‘main’:
a1ms4.c:12:5: warning: implicit declaration of function ‘getName’ [-Wimplicit-function-declaration]
    getName(&contact.name);
 ^
A1ms4.c:14:5: warning: implicit declaration of function ‘getAddress’ [-Wimplicit-function-declaration]
 getAddress(&contact.address);
 ^
a1ms4.c:16:5: warning: implicit declaration of function ‘getNumbers’ [-Wimplicit-function-declaration]
 getNumbers(&contact.numbers);
 ^
</code>```

Which you remedy by including your function declarations from contacts.c in contacts.h, e.g. include the following at the end of contacts.h

```<code>void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);
</code>```

Your code then compiles fine -- without error or warning (well done).

The only other thing that stands out is you should initialize struct Numbers temporaryNumbers in contacts.c. Not knowing if you are compiling on Win7 with VS 10 or on a later version, simply using the C89 compatible initializer as follows works:

```<code>struct Numbers temporaryNumbers = {{0},{0},{0}};
</code>```

Your code then compiles fine, e.g.

```<code>cl /nologo /Wall /wd4820 /Ox /Fecontacts /Tc a1ms4.c contacts.c
</code>```

(the /Fecontacts just telling the compiler to create contacts.exe as the executable name)

(note: you can create a bin and obj directory to place the executables and object files in to keep your source directory clean. Just add /Foobj/ /Febin/contacts after /Ox to place all object files in obj (the /Fo option) and create the contacts.exe executable in bin (the /Fe option), the /wd4820 just disables the compiler reporting the number of padding bytes added to each struct as a warning)

If you do create and use the bin and obj subdirectories, then your compile string in full would be:

```<code>cl /nologo /Wall /wd4820 /Ox /Foobj/ /Febin/contacts /Tc a1ms4.c contacts.c
</code>```

Body:
I'm using SSH Secure Shell to run and submit my assignment.  I'm getting this error right now:

In file included from a1ms4.c:15:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token
In file included from contacts.c:16:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token

Which is bogus because the exact same code compiled on another IDE.  These are my C files that are reporting the error.  I am not missing a ( or a { or a ; anywhere in my code.  I went through this code for hours to find a potential mistake but couldn't spot anything and despite that, it won't let me submit my assignment.

a1ms4.c

#define _CRT_SECURE_NO_WARNINGS

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

int main(void)
{
    struct Contact contact;

    printf("Contact Management System\n-------------------------\n");

    getName(&contact.name);

    getAddress(&contact.address);

    getNumbers(&contact.numbers);

    printf("\nContact Details\n---------------");

    printf("\nName Details");

    printf("\nFirst name: %s", contact.name.firstName);

    printf("\nMiddle initial(s): %s", contact.name.middleInitial);

    printf("\nLast name: %s", contact.name.lastName);

    printf("\n");

    printf("\nAddress Details");

    printf("\nStreet number: %d", contact.address.streetNumber);

    printf("\nStreet name: %s", contact.address.street);

    printf("\nApartment: %d", contact.address.apartmentNumber);

    printf("\nPostal code: %s", contact.address.postalCode);

    printf("\nCity: %s", contact.address.city);

    printf("\n");

    printf("\nPhone Numbers:");

    printf("\nCell phone number: %s", contact.numbers.cell);

    printf("\nHome phone number: %s", contact.numbers.home);

    printf("\nBusiness phone number: %s", contact.numbers.business);

    printf("\n");

    printf("\nStructure test for Contact using functions done!\n");

    return 0;
}

contacts.c

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include "contacts.h"

void getName(struct Name *name) {
    char one;
    struct Name temporaryName;

    printf("Please enter the contact's first name: ");
    scanf(" %[^\n]", temporaryName.firstName);
    printf("Do you want to enter a middle initial(s)? (y or n): ");
    scanf(" %c", &one);

    if (one == 'y' || one == 'Y') {
        printf("Please enter the contact's middle initial(s): ");
        scanf(" %[^\n]", temporaryName.middleInitial);
    }

    printf("Please enter the contact's last name: ");
    scanf(" %[^\n]", temporaryName.lastName);

    *name = temporaryName;

    return;
}

void getAddress(struct Address *address) {
    char two;
    struct Address temporaryAddress;

    printf("Please enter the contact's street number: ");
    scanf("%d", &temporaryAddress.streetNumber);

    printf("Please enter the contact's street name: ");
    scanf(" %[^\n]", temporaryAddress.street);

    printf("Do you want to enter an appartment number? (y or n): ");
    scanf(" %c", &two);

    if (two == 'y' || two == 'Y') {
        printf("Please enter the contact's appartment number: ");
        scanf(" %d", &temporaryAddress.apartmentNumber);
    }

    printf("Please enter the contact's postal code: ");
    scanf(" %[^\n]", temporaryAddress.postalCode);

    printf("Please enter the contact's city: ");
    scanf(" %[^\n]", temporaryAddress.city);

    *address = temporaryAddress;

    return;
}

void getNumbers(struct Numbers *numbers) {
    char three, four, five;
    struct Numbers temporaryNumbers;

    printf("Do you want to enter a cell phone number? (y or n): ");
    scanf(" %c", &three);

    if (three == 'y' || three == 'Y') {
        printf("Please enter the contact's cell phone number: ");
        scanf(" %[^\n]", temporaryNumbers.cell);
    }

    printf("Do you want to enter a home phone number? (y or n): ");
    scanf(" %c", &four);

    if (four == 'y' || four == 'Y') {
        printf("Please enter the contact's home phone number: ");
        scanf(" %[^\n]", temporaryNumbers.home);
    }

    printf("Do you want to enter a business phone number? (y or n): ");
    scanf(" %c", &five);

    if (five == 'y' || five == 'Y') {
        printf("Please enter the contact's business phone number: ");
        scanf(" %[^\n]", temporaryNumbers.business);
    }

    *numbers = temporaryNumbers;
    return;
}

contacts.h

/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address {
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers {
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact {
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};

Body:
The error:

error: expected identifier or â(â before â--â token

suggests that you most likely have an invalid character that is unrecognized by the compiler in your code that occurs in a pattern X...stuff...X (where X represents the unrecognized character).

The line being complained about is:

scanf(" %[^\n]", temporaryAddress.street);

The likely cause of the problem is you have included (copied/pasted or otherwise somehow acquired) a unicode or html variation of '"' (double quote) surrounding your scanf format string. (this is a common occurrence when a #ldquo; or #rdquo; (left-double-quote or right-double-quote) is accidentally included in your source file).  Most likely the result of a copy/paste of " %[^\n]" from some web page. Go double check that your double quotes are all ASCII 0x22 (decimal 34) characters.

The error is not apparent in your code above (most likely because in your copy/paste to stack overflow the funky quotes were lost in translation)

The only errors you need to fix in your code (not including all little nits, etc.) are:

a1ms4.c: In function ‘main’:
a1ms4.c:12:5: warning: implicit declaration of function ‘getName’ [-Wimplicit-function-declaration]
    getName(&contact.name);
 ^
A1ms4.c:14:5: warning: implicit declaration of function ‘getAddress’ [-Wimplicit-function-declaration]
 getAddress(&contact.address);
 ^
a1ms4.c:16:5: warning: implicit declaration of function ‘getNumbers’ [-Wimplicit-function-declaration]
 getNumbers(&contact.numbers);
 ^

Which you remedy by including your function declarations from contacts.c in contacts.h, e.g. include the following at the end of contacts.h

void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

Your code then compiles fine -- without error or warning (well done).

The only other thing that stands out is you should initialize struct Numbers temporaryNumbers in contacts.c. Not knowing if you are compiling on Win7 with VS 10 or on a later version, simply using the C89 compatible initializer as follows works:

struct Numbers temporaryNumbers = {{0},{0},{0}};

Your code then compiles fine, e.g.

cl /nologo /Wall /wd4820 /Ox /Fecontacts /Tc a1ms4.c contacts.c

(the /Fecontacts just telling the compiler to create contacts.exe as the executable name)

(note: you can create a bin and obj directory to place the executables and object files in to keep your source directory clean. Just add /Foobj/ /Febin/contacts after /Ox to place all object files in obj (the /Fo option) and create the contacts.exe executable in bin (the /Fe option), the /wd4820 just disables the compiler reporting the number of padding bytes added to each struct as a warning)

If you do create and use the bin and obj subdirectories, then your compile string in full would be:

cl /nologo /Wall /wd4820 /Ox /Foobj/ /Febin/contacts /Tc a1ms4.c contacts.c


来源: stackexchange

问:
How to migrate a sub-domain from a shared hosting cpanel to a VPS cpanel
My shared hosting structure is as such that allows we to host up to 5 domain under same account which turns out to be as:
    /home/MainDomain/public_html/domian1/
    /home/MainDomain/public_html/domian2/
    /home/MainDomain/public_html/domian3/
etc...

I want to migrate domain1 to a newly purchased VPS hosting company which they have provided me with WHM/cpanel.

If I use the Backup utility from the old shared hosting, it will backup everything (meaning other domains too).
My question is how do I migrate domain1 with all its DBs, cron jobs, and emails to my new VPS account.

Thank you.

答:
There is a functionality in WHM (WHM 64+ versions I believe) that allows you to to convert an addon domain inside a cPanel account into an invidiual cPanel account.

Since you have multiple domains on the same account and I suppose you have websites for those domains as well, then those domains are added as "addon domains" into your cPanel account. So use that WHM convertor tool, convert the desired domain from that cPanel account as a new invidiual cPanel account.

Then create a full cPanel backup for that account. You can do that either from the cPanel web interface or command line (ssh shell).  Once you have the full backup file you can copy it to the new server and restore it from the command line or you can use the WHM transfer tool to transfer the cPanel account from one server to another.

ContentLicense: CC BY-SA 3.0


问:
Refactor menu missing from Visual Studio 2015
I am having trouble finding the right-click context menu in Visual Studio 2015. I know that nothing is wrong with my project or the file I am working. I can find the right-click context refactor menu in Visual Studio 2013. However, in Visual Studio 2015 there isn't a refactor context menu in the right-click context menu.

Where did it go? How do I get it back?

Your suggestion cannot include menu Edit → Refactor.

I have tried to reset my Visual Studio settings back to default using menu Tools → Import and Export Settings and that didn't bring the menu back either.

答:
Ctrl + . is the shortcut key for extracting a method in Visual Studio 2015 and onward.

Ctrl+M, R does not work anymore in new versions.

ContentLicense: CC BY-SA 4.0


问:
How to display randomly text when a button is clicked
I've got a project to do and I'm stuck at this stage. I have 5 paragraphs that include text and images that have to be displayed randomly in the button in clicked.  I still haven't figured out how to add the images in all of this. So far this is where I am:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text
  idArray [3] = "Third paragraph text
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = new Array[randomParagraph];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <button onclick="myFunction()" id="select">Pick text</button>

  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Hey</footer>
</body></code>```

答:
new Array[randomParagraph]; does not work.

What you need to do is to access the value at the index form the idArray - idArray[randomParagraph + 1]

The +1 had to be added since the idArray you've defined goes from 1 to 5 while the random number generated goes from 0 to 4 since you are using Math.floor

Working example here:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text"
  idArray [3] = "Third paragraph text"
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = idArray[randomParagraph + 1];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <button onclick="myFunction()" id="select">Pick text</button>
  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Hey</footer>
</body></code>```

Body:
I've got a project to do and I'm stuck at this stage. I have 5 paragraphs that include text and images that have to be displayed randomly in the button in clicked.  I still haven't figured out how to add the images in all of this. So far this is where I am:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text
  idArray [3] = "Third paragraph text
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = new Array[randomParagraph];
}

  <button onclick="myFunction()" id="select">Pick text</button>

  Hey

Body:
new Array[randomParagraph]; does not work.

What you need to do is to access the value at the index form the idArray - idArray[randomParagraph + 1]

The +1 had to be added since the idArray you've defined goes from 1 to 5 while the random number generated goes from 0 to 4 since you are using Math.floor

Working example here:

function myFunction() {
  idArray = new Array()
  idArray [1] = "First paragraph text"
  idArray [2] = "Second paragraph text"
  idArray [3] = "Third paragraph text"
  idArray [4] = "Fourth paragraph text"
  idArray [5] = "Fifth paragraph text"

  document.getElementById("select").onclick = myFunction;
  randomParagraph = Math.floor(Math.random()*5);

  document.getElementById("result").innerHTML = idArray[randomParagraph + 1];
}

<body>
  <button onclick="myFunction()" id="select">Pick text</button>
  <div class="main">
    <p id="result"></p>
  </div>
  <footer class="footer">Hey</footer>
</body>


问:
REST: Processing error in long running operation, how to inform clients?
I am developing a webservice that alllows users to request validation reports. Report generation might take up to 20 hours per report. When a new validation request is posted, I return a 202 Accepted answer with Location set to a processing queue (e.g./queue/5) When the queue resource is polled some processing information is provided:

<queueResponse>
    <status>QUEUED</status>
    <queuePosition>1</queuePosition>
</queueResponse>

Once processing completes successfully and the queue is polled, a 303 see other will redirect to the created resource (at /reports/5 e.g.).

However if a processing error occurs on server, i simply return my queueResponse without redirect and status set to <status>ERROR</status>.

Is this the best way to comunicate a processing error to the client? Or should instead simply a 500 Internal Server Error returned when polling the queue for a failed validation task?.....

答:
Your current solution is best. A 500 error for the queued process information would indicate that the request for that resource had failed, not the process it was reporting on.

postscript: If your API is still being defined, I would suggest FAILED instead of ERROR, as it sounds more permanent. Errors are potentially recoverable situations, failures are not.


问:
Why AVD Manager options are not showing in Android Studio
Why i'm unable to see Android Virtual Device (AVD)

I'm facing problem to create AVD in android studio, the problem is i'm unable to see any of this option Tools —> Android —> AVD Manager

below screen shot  where i'm not finding  Tools —> Android —> AVD Manager

in the above screen shot you cannot find Android --> AVD Manager,Why it is not showing.

Below is my installed packages:

1. SDK Manager

2. SDK Tools

i'm following this link:http://www.dev2qa.com/how-to-create-android-virtual-device-avd-in-android-studio/

答:
I had installed Android studio and was not able to access the AVD Manager directly. I had to follow the steps as mentioned below:

Created a blank project using Android Studio

Once the Project is ready to use I tried open action using the shortcut  ctrl+shift+a option and searched for AVD Manager
AVD Manager

On double clicking the AVD Manager I got a few errors in console about the missing libararies along with the link to install the neccessary dependencies. On clicking the links which was displayed with the error message few packages which were needed were installed. Once all the required packages were installed the AVD Manager icon becomes active.


问:
Uncaught type error: Cannot set the property of "Callback Client" and $m is not defined
I am a learner of the field of Web development. I work on a project in which I face the following problems.Here I want to add, "mowbly" API is used.

Uncaught TypeError: Cannot set property 'CallbackClient' of undefined

```<code> bridge.CallbackClient = new CallbackClient();
</code>```

Uncaught ReferenceError: $m is not defined

```<code>var PACKS = new PacksModel();

$m.juci.addDataset(PACKS, true);
</code>```

Uncaught Error: Unable to parse bindings

I don't understand what to do.Please help me.I am sorry for my poor english.

答: Check the path of all js. I have a same problem. Then I fixed it by correcting the path.</p>

Body:
I am a learner of the field of Web development. I work on a project in which I face the following problems.Here I want to add, "mowbly" API is used.

Uncaught TypeError: Cannot set property 'CallbackClient' of undefined

 bridge.CallbackClient = new CallbackClient();

Uncaught ReferenceError: $m is not defined

var PACKS = new PacksModel();

$m.juci.addDataset(PACKS, true);

Uncaught Error: Unable to parse bindings

I don't understand what to do.Please help me.I am sorry for my poor english.


问:
problem with sizeof operator
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result.
here is one demo program to show you, what i want to do.

```<code>//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------
</code>```

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

```<code>array size(in function):2
array size:19
</code>```

please explain ,why this is happening.
what can be done to solve this problem.

答:
S is an int *, a pointer to an integer, which is a memory address, which is on your machine twice the size of an integer.

If you want the size of the array (I.e., the number of elements), you can't get that directly in pure C. But since this is a c++ question, there is a way: use a vector, which has a size() method.

Actually, this isn't quite true: within the function that you declare S (and only if it's explicitly initialized at compile time as you do in your example -- even new int[19] doesn't work), the sizeof operator actually does get the correct answer, which is why c++ allows you to do this:

```<code>int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
vector<int> v(S, S + sizeof(S) / sizeof(int) );
</code>```

and then you can use v.size() (see these docs).

The template version by Nawaz elsewhere is another excellent suggestion which forces the compiler into carrying the full information about the construction of the c++ array around (again, note that this is all known at compile time, which is why you can be explicit about the size in the argument).

ContentLicense: CC BY-SA 2.5

Title: problem with sizeof operator

Body:
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result.
here is one demo program to show you, what i want to do.

//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

array size(in function):2
array size:19

please explain ,why this is happening.
what can be done to solve this problem.

Body:
S is an int *, a pointer to an integer, which is a memory address, which is on your machine twice the size of an integer.

If you want the size of the array (I.e., the number of elements), you can't get that directly in pure C. But since this is a c++ question, there is a way: use a vector, which has a size() method.

Actually, this isn't quite true: within the function that you declare S (and only if it's explicitly initialized at compile time as you do in your example -- even new int[19] doesn't work), the sizeof operator actually does get the correct answer, which is why c++ allows you to do this:

int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
vector<int> v(S, S + sizeof(S) / sizeof(int) );

and then you can use v.size() (see these docs).

The template version by Nawaz elsewhere is another excellent suggestion which forces the compiler into carrying the full information about the construction of the c++ array around (again, note that this is all known at compile time, which is why you can be explicit about the size in the argument).


问:
Swift 4 backgroundColor bug?
I have a problem with transparency in my Views, especially with UITableView.

Just to make sure. I already have 3 years of experience with swift and this is the first time, I am getting this problem.

So in apple's docs it says the following:
backgroundColor
The view's background color.

Changes to this property can be animated. The default value is nil, which results in a transparent background color."

But when applying clear color to backgroundColor or tableView.backgroundColor = UIColor.clear, the background is still appearing white.

Is this a bug or a feature?

EDIT:

The tableView isn't the problem anymore. It is the cell within the tableView.
Already tried solutions are clearing the background color of all subviews. Nothing changed.

EDIT 29.09.17

Ok, I debugged my application and got this:

UICachedDeviceWhiteColor and cachedColor.

A google searching also didn't help.

Edit 29.09.2017 Later that day ...

The problem occurs, when updating from swift 3 to swift 4.
I made a new project with swift 4, but it actually works fine.
Because it is a problem I have to solve. I will try some things and update this post from time to time.

答:
If you are setting

```<code>tableView.backgroundColor = .red
</code>```

and if it's an empty TableView then the Red will be visible. I give a headerView and FooterView also to visualise.

 Now TableView Contents some data, so to reflect the color you need to set background color to cell.

```<code>class UserCell: UITableViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
}

override func layoutSubviews() {
    super.layoutSubviews()
     backgroundColor = .yellow
}
....
}
</code>```

You can check out the original project here.

Title: Swift 4 backgroundColor bug?

Body:
If you are setting

tableView.backgroundColor = .red

and if it's an empty TableView then the Red will be visible. I give a headerView and FooterView also to visualise.

 Now TableView Contents some data, so to reflect the color you need to set background color to cell.

class UserCell: UITableViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
}

override func layoutSubviews() {
    super.layoutSubviews()
     backgroundColor = .yellow
}
....
}

You can check out the original project here.


问:
Implementing "JSON Merge Patch" in ASP.NET Core - best way do differentiate between null and not defined property
I would like to create and endpoint conforming to "JSON Merge Patch" https://www.rfc-editor.org/rfc/rfc7396

Please do not confuse it with "JavaScript Object Notation (JSON) Patch"
https://www.rfc-editor.org/rfc/rfc6902

However, I have a slight problem with differentiating between two situations in request:

removal of property value, here  email value is being removed:

  {
      surname: "Kowalski"
      email: null
  }
```
</li>
<li><p>property not included because client simply does not want to update it, here email is not included because it should not be updated:</p>
  <pre class="lang-json prettyprint-override"><code>  {
      surname: "Kowalski"
  }
</code>```

The problem arises because in both situations after model binding email would have value null.

Do you have suggestion how this might be implemented?

答:
You need 3 different states for email value here:

Filled value for update (e.g. test@mail.com)

null value if email should be removed

Missing value if email should not be touched.

So the problem actually is how to express these 3 states in string property of your model. You can't do this with just raw string property because null value and missing value will conflict as you correctly described.
Solution is to use some flag that indicates whether the value was provided in the request. You could either have this flag as another property in your model or create a simple wrapper over string, very similar to Nullable<T> class.
I suggest creation of simple generic OptionalValue<T> class:

```<code>public class OptionalValue<T>
{
    private T value;
    public T Value
    {
        get => value;

        set
        {
            HasValue = true;
            this.value = value;
        }
    }

    public bool HasValue { get; set; }
}
</code>```

Then you need custom JsonConverter that could deserialize usual json value to OptionalValue<T>:

```<code>class OptionalValueConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(OptionalValue<T>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new OptionalValue<T>
        {
            Value = (T) reader.Value,
        };
    }

    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

Your model will look something like this:

```<code>public class SomeModel
{
    public string Surname { get; set; }

    [JsonConverter(typeof(OptionalValueConverter<string>))]
    public OptionalValue<string> Email { get; set; } = new OptionalValue<string>();
}
</code>```

Note that you assign Email with empty OptionalValue<string>(). If input json does not contains email value than Email property will keep it OptionalValue with HasValue set to false.
If input json contains some email, even null, then OptionalValueConverter will create instance of OptionalValue with HasValue set to true.

Now in controller action you could determine any of 3 states for email:

```<code>[HttpPatch]
public void Patch([FromBody]SomeModel data)
{
    if (data.Email.HasValue)
    {
        //  Email presents in Json
        if (data.Email.Value == null)
        {
            //  Email should be removed
        }
        else
        {
            //  Email should be updated
        }
    }
    else
    {
        //  Email does not present in Json and should not be affected
    }
}
</code>```

Body:
I would like to create and endpoint conforming to "JSON Merge Patch" https://www.rfc-editor.org/rfc/rfc7396

Please do not confuse it with "JavaScript Object Notation (JSON) Patch"
https://www.rfc-editor.org/rfc/rfc6902

However, I have a slight problem with differentiating between two situations in request:

removal of property value, here  email value is being removed:

  {
      surname: "Kowalski"
      email: null
  }

property not included because client simply does not want to update it, here email is not included because it should not be updated:

  {
      surname: "Kowalski"
  }

The problem arises because in both situations after model binding email would have value null.

Do you have suggestion how this might be implemented?

Body:
You need 3 different states for email value here:

Filled value for update (e.g. test@mail.com)

null value if email should be removed

Missing value if email should not be touched.

So the problem actually is how to express these 3 states in string property of your model. You can't do this with just raw string property because null value and missing value will conflict as you correctly described.
Solution is to use some flag that indicates whether the value was provided in the request. You could either have this flag as another property in your model or create a simple wrapper over string, very similar to Nullable<T> class.
I suggest creation of simple generic OptionalValue<T> class:

public class OptionalValue<T>
{
    private T value;
    public T Value
    {
        get => value;

        set
        {
            HasValue = true;
            this.value = value;
        }
    }

    public bool HasValue { get; set; }
}

Then you need custom JsonConverter that could deserialize usual json value to OptionalValue<T>:

class OptionalValueConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(OptionalValue<T>);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return new OptionalValue<T>
        {
            Value = (T) reader.Value,
        };
    }

    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Your model will look something like this:

public class SomeModel
{
    public string Surname { get; set; }

    [JsonConverter(typeof(OptionalValueConverter<string>))]
    public OptionalValue<string> Email { get; set; } = new OptionalValue<string>();
}

Note that you assign Email with empty OptionalValue<string>(). If input json does not contains email value than Email property will keep it OptionalValue with HasValue set to false.
If input json contains some email, even null, then OptionalValueConverter will create instance of OptionalValue with HasValue set to true.

Now in controller action you could determine any of 3 states for email:

[HttpPatch]
public void Patch([FromBody]SomeModel data)
{
    if (data.Email.HasValue)
    {
        //  Email presents in Json
        if (data.Email.Value == null)
        {
            //  Email should be removed
        }
        else
        {
            //  Email should be updated
        }
    }
    else
    {
        //  Email does not present in Json and should not be affected
    }
}


问:
Can multiple versions of the same iphone or android app use shared code or libraries?
Let's say I write an app that displays restaurant menus and lets a user order items from them. I'll call it RestaurantMenuApp. I'd like to have this main application be branded under my company name. It would allow users to view multiple different restaurants and place orders on any of them. Purchases are done through API calls to my web service using my company's merchant account.

Now let's say I also want to sell customized versions of this app to individual restaurants. The customized version would be themed just for that restaurant, only show their menus, locations, their promos, and so forth. It would make the restaurant look like they built their own custom app. Purchases are still done through API calls to my web service, but each branded version can use their own merchant account.

I'm wondering if each application (the main RestaurantMenuApp and each individually customized restaurant app) has to contain an entire copy of the entire application. Is it possible to have each app install a shared library that all of the apps use? If any of the apps has already installed this shared library, the others apps don't need to install it as well?

I'm new to mobile app development and searched for answers, but could only find solutions for how to build lite vs. full versions of the same app. It was not clear if these apps could SHARE code to make each install smaller.

答:
For iPhone, the inter-app communication is restricted almost to none. Apple designed the iOS this way for the benefit, arguably, of security and user experience.

On Android, there is much more flexibility in inter-app communication. There are several ways to achieve what you want.

First, you can use service. Service processes on Android are pretty much like service processes on Windows. They are running in the background all the time. There is an code sample.

http://marakana.com/forums/android/examples/60.html

Or you can use intents. Intent receivers register with the Android OS to specify what action and data format that they will handle. For example, an intent filter like below tells the Android OS that the receive will be able to view, edit, and pick any mime type of vnd.android.cursor.dir/vnd.google.note. So you can create a component as intent receivers to take care of a special data format. In another Android app, you then push out your data and the intent receiver will take over from there.

```<code><intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.PICK" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter>
</code>```

For more information on intent filter, you can refer to this doc.

http://developer.android.com/guide/topics/intents/intents-filters.html

Body:
For iPhone, the inter-app communication is restricted almost to none. Apple designed the iOS this way for the benefit, arguably, of security and user experience.

On Android, there is much more flexibility in inter-app communication. There are several ways to achieve what you want.

First, you can use service. Service processes on Android are pretty much like service processes on Windows. They are running in the background all the time. There is an code sample.

http://marakana.com/forums/android/examples/60.html

Or you can use intents. Intent receivers register with the Android OS to specify what action and data format that they will handle. For example, an intent filter like below tells the Android OS that the receive will be able to view, edit, and pick any mime type of vnd.android.cursor.dir/vnd.google.note. So you can create a component as intent receivers to take care of a special data format. In another Android app, you then push out your data and the intent receiver will take over from there.

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.PICK" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter>

For more information on intent filter, you can refer to this doc.

http://developer.android.com/guide/topics/intents/intents-filters.html


问:
Ionic check multiple Promises are finished
I want to run multiple promises and print the result if all promises are finished. Currently I try below approach:

```<code>for (let p of this.invoiceProduct) {
  this.promotionSvc.checkPromoBuyNGetN(this.username, p).then(result => {
    console.log(result);
    this.promoBuyNGetNData.push(result);
  })
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
})
</code>```

In the console, it prints [] for console.log(values) and {id: "e620c8a8-dca8-11e7-8443-2c56dcbcb038", productIdGet: "98926f8c-6afb-11e7-8dd4-2c56dcbcb038", productGet: "Style Laki", getN: 1, description: ""} for console.log(result).

From above result we can see that the Promise.all doesn't work. How should I fix this?

答:
you seem to be trying to push the results of the promises in the array and then calling Promise.all.

Promise.all takes an array of promise objects and calls all of them and then fires then on completion of all promises. YOu can do:

```<code>promoData:any[]=[];//class variable

for (let p of this.invoiceProduct) {
  this.promoBuyNGetNData.push(this.promotionSvc.checkPromoBuyNGetN(this.username, p));//push the promise function into array
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);// all results within values array
  this.promoData=values;
})
</code>```

And in your HTML,

```<code><tr *ngFor="let p of promoData">
</code>```

Body:
I want to run multiple promises and print the result if all promises are finished. Currently I try below approach:

for (let p of this.invoiceProduct) {
  this.promotionSvc.checkPromoBuyNGetN(this.username, p).then(result => {
    console.log(result);
    this.promoBuyNGetNData.push(result);
  })
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
})

In the console, it prints [] for console.log(values) and {id: "e620c8a8-dca8-11e7-8443-2c56dcbcb038", productIdGet: "98926f8c-6afb-11e7-8dd4-2c56dcbcb038", productGet: "Style Laki", getN: 1, description: ""} for console.log(result).

From above result we can see that the Promise.all doesn't work. How should I fix this?

Body:
you seem to be trying to push the results of the promises in the array and then calling Promise.all.

Promise.all takes an array of promise objects and calls all of them and then fires then on completion of all promises. YOu can do:

promoData:any[]=[];//class variable

for (let p of this.invoiceProduct) {
  this.promoBuyNGetNData.push(this.promotionSvc.checkPromoBuyNGetN(this.username, p));//push the promise function into array
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);// all results within values array
  this.promoData=values;
})

And in your HTML,

<tr *ngFor="let p of promoData">


问:
UIRefreshControl for uitableview is not working in only iphone 6
Actually this working is fine in all devices except IPhone-6. Please help me for this problem.

my code is

```<code>var refreshControl = UIRefreshControl()

        self.refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
        self.tableView.addSubview(self.refreshControl)

func refresh(_ sender:AnyObject) {
    if self.appDel.isNetworkEnabled
    {
        DispatchQueue.main.async {
            if(self.page < Int(self.total_pages)! )
            {
                self.page = self.page + 1
                self.fetchMessageApiCall()
            }
        }
    }
    else
    {
        self.singletonObj.showAlert("", message: "No Internet")
    }

    self.refreshControl.endRefreshing()
}
</code>```

答:
SWIFT 3.0

I faced this issue in IOS 10 and above, and resolved it using below code

```<code>refreshControl = UIRefreshControl()

refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: UIControlEvents.valueChanged)
    if #available(iOS 10.0, *) {
        self.gigListTableView.refreshControl = refreshControl
    } else {
        // Fallback on earlier versions
        self.gigListTableView.addSubview(refreshControl)
    }
</code>```

Body:
Actually this working is fine in all devices except IPhone-6. Please help me for this problem.

my code is

var refreshControl = UIRefreshControl()

        self.refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged)
        self.tableView.addSubview(self.refreshControl)

func refresh(_ sender:AnyObject) {
    if self.appDel.isNetworkEnabled
    {
        DispatchQueue.main.async {
            if(self.page < Int(self.total_pages)! )
            {
                self.page = self.page + 1
                self.fetchMessageApiCall()
            }
        }
    }
    else
    {
        self.singletonObj.showAlert("", message: "No Internet")
    }

    self.refreshControl.endRefreshing()
}

Body:
SWIFT 3.0

I faced this issue in IOS 10 and above, and resolved it using below code

refreshControl = UIRefreshControl()

refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: UIControlEvents.valueChanged)
    if #available(iOS 10.0, *) {
        self.gigListTableView.refreshControl = refreshControl
    } else {
        // Fallback on earlier versions
        self.gigListTableView.addSubview(refreshControl)
    }


问:
How to apply gsub on exact words instead of characters
I have a data frame in R containing a column "CountryCode".

I would like to select valid Countries and replace all other codes with "OtherCountry". So I wrote:

```<code>Valid_Countries <- c("US", "CA", "JP", "AU", "DE", "IT", "ES", "FR", "UK", "FI", "SE", "NO")

levels(Orders2$CountryCode) <- gsub(paste0("[^", paste(Valid_Countries, collapse=""), "]+"), "OtherCountry", levels(Orders2$CountryCode))
</code>```

which almost works. My problem is that Country codes like "BE" is replaced with "OtherCountryE" (I guess it is because "E" is included in the Valid_Countries).

How can I say "just consider the entire code"?

答:
Does this work:</p>

```<code>levels(Orders2$CountryCode)[
    !(levels(Orders2$CountryCode) %in% Valid_Countries)
    ] <- "OtherCountry
</code>```

Body:
I have a data frame in R containing a column "CountryCode".

I would like to select valid Countries and replace all other codes with "OtherCountry". So I wrote:

Valid_Countries <- c("US", "CA", "JP", "AU", "DE", "IT", "ES", "FR", "UK", "FI", "SE", "NO")

levels(Orders2$CountryCode) <- gsub(paste0("[^", paste(Valid_Countries, collapse=""), "]+"), "OtherCountry", levels(Orders2$CountryCode))

which almost works. My problem is that Country codes like "BE" is replaced with "OtherCountryE" (I guess it is because "E" is included in the Valid_Countries).

How can I say "just consider the entire code"?

Body:
Does this work:

levels(Orders2$CountryCode)[
    !(levels(Orders2$CountryCode) %in% Valid_Countries)
    ] <- "OtherCountry


答:
Promise.all expects an array of promises. You need to change your for loop to put the promises into this.promoBuyNGetNData.  If I understand you correctly, this code should do what you want.

```<code>for (let p of this.invoiceProduct) {
  const promise = this.promotionSvc.checkPromoBuyNGetN(this.username, p);
  promise.then(result => {
    console.log(result);
  });
  this.promoBuyNGetNData.push(promise);
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
});
</code>```

You can make this cleaner by getting rid of the promise.then console log, and turning the for loop into a map.

```<code>this.promoBuyNGetNData = this.invoiceProduct.map(p => this.promotionSvc.checkPromoBuyNGetN(this.username, p));
Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
});
</code>```

Title: Ionic check multiple Promises are finished

Body:
Promise.all expects an array of promises. You need to change your for loop to put the promises into this.promoBuyNGetNData.  If I understand you correctly, this code should do what you want.

for (let p of this.invoiceProduct) {
  const promise = this.promotionSvc.checkPromoBuyNGetN(this.username, p);
  promise.then(result => {
    console.log(result);
  });
  this.promoBuyNGetNData.push(promise);
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
});

You can make this cleaner by getting rid of the promise.then console log, and turning the for loop into a map.

this.promoBuyNGetNData = this.invoiceProduct.map(p => this.promotionSvc.checkPromoBuyNGetN(this.username, p));
Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
});


问:
axios: stop automatic sorting of objects based on keys
I am gettting an api response using axios.

I am sending the api response sorted w.r.t name http://localhost:8000/api/ingredients/ordering=name

The actual object sent is as below from my server.

```<code>{
    2:{"id":2,"name":"anil"},
    1:{"id":1,"name":"sant"},
    3:{"id":3,"name":"vino"}
}
</code>```

or pass the key as string instead of integer

```<code>{
    "2":{"id":2,"name":"anil"},
    "1":{"id":1,"name":"sant"},
    "3":{"id":3,"name":"vino"}
}
</code>```

or key as alphanumeric

```<code>{
    "a2":{"id":2,"name":"anil"},
    "a1":{"id":1,"name":"sant"},
    "a3":{"id":3,"name":"vino"}
}
</code>```

what axios is doing is sorting the objects w.r.t keys and the names are not in sorted order

```<code>{
    1:{"id":1,"name":"sant"},
    2:{"id":2,"name":"anil"},
    3:{"id":3,"name":"vino"}
}
</code>```

or if key is alpha numeric

```<code>{
    a1:{"id":1,"name":"sant"},
    a2:{"id":2,"name":"anil"},
    a3:{"id":3,"name":"vino"}
}
</code>```

How to stop this

I dont want in array format the list because i have to update the individual objects later based on the id. This representation is easy. I am using reactjs state.

答:
This is an expected behavior for objects in JavaScript.

If you want to have the order intact, use Arrays, So your example would turn out like this,

```<code>const obj = [{name:"two"},{name:"three"},{name:"one"}];
</code>```

If you need to pass keys, then reorder it in this way,

Edited

Back to your edited version, say you want to update your object based on ID and this is your provided json,

```<code>{
    a1:{"id":1,"name":"sant"},
    a2:{"id":2,"name":"anil"},
    a3:{"id":3,"name":"vino"}
}
</code>```

Nothing will stop you from doing so, if you want to change details for an object with id:2, you can do the following to get the key a2,

```<code>const key = Object.entries(obj).find(entry => entry[1].key === 2)[0];
const desiredElement = obj(key);
</code>```

Breakdown of the code,

```<code>Object.entries(obj) // get entries from object
.find(entry) //where entry[0] is key, entry[1] is value/object
entry[1].id=== 2 // return the element that has id === 2
[0] // since entry[0] is key, then it would hold a2 here
</code>```

Now we can use the key as we want like, Obj[key], and update it as well.

Body:
I am gettting an api response using axios.

I am sending the api response sorted w.r.t name http://localhost:8000/api/ingredients/ordering=name

The actual object sent is as below from my server.

{
    2:{"id":2,"name":"anil"},
    1:{"id":1,"name":"sant"},
    3:{"id":3,"name":"vino"}
}

or pass the key as string instead of integer

{
    "2":{"id":2,"name":"anil"},
    "1":{"id":1,"name":"sant"},
    "3":{"id":3,"name":"vino"}
}

or key as alphanumeric

{
    "a2":{"id":2,"name":"anil"},
    "a1":{"id":1,"name":"sant"},
    "a3":{"id":3,"name":"vino"}
}

what axios is doing is sorting the objects w.r.t keys and the names are not in sorted order

{
    1:{"id":1,"name":"sant"},
    2:{"id":2,"name":"anil"},
    3:{"id":3,"name":"vino"}
}

or if key is alpha numeric

{
    a1:{"id":1,"name":"sant"},
    a2:{"id":2,"name":"anil"},
    a3:{"id":3,"name":"vino"}
}

How to stop this

I dont want in array format the list because i have to update the individual objects later based on the id. This representation is easy. I am using reactjs state.

Body:
This is an expected behavior for objects in JavaScript.

If you want to have the order intact, use Arrays, So your example would turn out like this,

const obj = [{name:"two"},{name:"three"},{name:"one"}];

If you need to pass keys, then reorder it in this way,

Edited

Back to your edited version, say you want to update your object based on ID and this is your provided json,

{
    a1:{"id":1,"name":"sant"},
    a2:{"id":2,"name":"anil"},
    a3:{"id":3,"name":"vino"}
}

Nothing will stop you from doing so, if you want to change details for an object with id:2, you can do the following to get the key a2,

const key = Object.entries(obj).find(entry => entry[1].key === 2)[0];
const desiredElement = obj(key);

Breakdown of the code,

Object.entries(obj) // get entries from object
.find(entry) //where entry[0] is key, entry[1] is value/object
entry[1].id=== 2 // return the element that has id === 2
[0] // since entry[0] is key, then it would hold a2 here

Now we can use the key as we want like, Obj[key], and update it as well.


问:
Python: Importing multiple methods from external module
With very common Python modules, I find that importing using the from .. import statement greatly increases the readability of my code, since I can reference methods by name without the dot notation. However, in some modules, the methods I require are nested differently, e.g in os:

```<code>from os.path import join
from os import listdir, getcwd
</code>```

Why doesn't from os import path.join, listdir, getcwd work? What would be a "pythonic" way to import all the methods I need in a more succinct manner?

答:
The opinion on whether from <module> import <identifier> is Pythonic itself is quite split - it hides away the origin of a method so it's not easy to figure out whence a certain variable/function comes from just by perusing the code. On the other hand, it reduces verbosity which some people consider Pythonic even tho it's not specifically mandated. Either way, Pythonic is as elusive term as you're going to get and more often than not it means "the way I think Python code should look like" backed up by several PEPs and obscure mail list posts while conveniently omitting the ones that go against one's notion of Pythonic.

from os import path.join doesn't work because os defines the os.path module (by directly writing to sys.modules of all things), it's not an identifier in the os module itself. path, however, is an identifier in the os module pointing to the os.path module so you can do from os import path or from os.path import join.

Finally, succinct and Pythonic are not synonyms, in fact PEP 8 for example prescribes using multiple lines for multiple imports even tho you can succinctly write import <module1>, <module2>, <module3> .... It says that it's OK to import multiple identifiers like that, tho, but keep in mind that os and os.path are two different modules so based on PEP 8 they shouldn't be on the same line and therefore should be written as:

```<code>from os import <identifier_1>, <identifier_2>
from os.path import <identifier_3>, <identifier_4>
</code>```

Now, I would go as far as claiming that this is Pythonic but it makes the most sense based on PEP 8, at least to me.

Body:
With very common Python modules, I find that importing using the from .. import statement greatly increases the readability of my code, since I can reference methods by name without the dot notation. However, in some modules, the methods I require are nested differently, e.g in os:

from os.path import join
from os import listdir, getcwd

Why doesn't from os import path.join, listdir, getcwd work? What would be a "pythonic" way to import all the methods I need in a more succinct manner?

Body:
The opinion on whether from <module> import <identifier> is Pythonic itself is quite split - it hides away the origin of a method so it's not easy to figure out whence a certain variable/function comes from just by perusing the code. On the other hand, it reduces verbosity which some people consider Pythonic even tho it's not specifically mandated. Either way, Pythonic is as elusive term as you're going to get and more often than not it means "the way I think Python code should look like" backed up by several PEPs and obscure mail list posts while conveniently omitting the ones that go against one's notion of Pythonic.

from os import path.join doesn't work because os defines the os.path module (by directly writing to sys.modules of all things), it's not an identifier in the os module itself. path, however, is an identifier in the os module pointing to the os.path module so you can do from os import path or from os.path import join.

Finally, succinct and Pythonic are not synonyms, in fact PEP 8 for example prescribes using multiple lines for multiple imports even tho you can succinctly write import <module1>, <module2>, <module3> .... It says that it's OK to import multiple identifiers like that, tho, but keep in mind that os and os.path are two different modules so based on PEP 8 they shouldn't be on the same line and therefore should be written as:

from os import <identifier_1>, <identifier_2>
from os.path import <identifier_3>, <identifier_4>

Now, I would go as far as claiming that this is Pythonic but it makes the most sense based on PEP 8, at least to me.


问:
Java applets with hardware accelerated 3D graphics? OpenGL and/orDirectX
I can't find a clear answer to this question with all my googling.

If I want a web applet, is there a library in Java that takes advantage of the hardware accelerated graphics drivers on the client's machine, as in OpenGL and directx?  I'm picturing writing some driver detection code before the applet launches to detect 3D graphics capabilities.

I realize there are a lot of Java 3D libraries but can't figure this out.

I was under the impression that you could do that, but can't find it.

While i'm asking, how about Flash and Silverlight?  I thought all their 3D graphics are software rendered?

EDIT:

I see the answer to the question is yes, Java does have 3D hardware support.  Thanks for all the info!

I guess my real question is (what I'm getting at):

1) To what extent is this supported for  full use?  Can you use DirectX or OpenGL shaders, for example?  I might expect some features to be missing as that tend to abstract things out.  Could I make a GPUID program or a utility that list's the client's GPU capabilities in detail?

2) Is it practical?  Could I port an old 3D game like Quake to a Java applet and have decent performance? (depends on client system of course)

答:
It is totally possible to write java applets that access the 3D hardware.  The env3d project (http://env3d.org) is exactly that -- a java 3D engine that produces 3D accelerated 3D applets.  There are lots of example programs on the website to demonstrate the use of hardware accelerated 3D inside your browser.  The only requirement is that Java has to be installed and the user has to explicitly allow the applet permission to access local resources.

Env3D is based on lwjgl, a opengl/gaming wrapper for Java.  It even supports shaders and other advanced features.


问:
How to centralize cells in Material Components Web (MDC)?
I want to have a centralized grid cells with, for example, 6 columns in desktop. In docs, it says:

The grid is by default center aligned. You can add mdc-layout-grid--align-left or mdc-layout-grid--align-right modifier class to change this behavior.

Then I type:

```<code><div class="mdc-layout-grid">
  <div class="mdc-layout-grid__inner">
    <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-3-desktop">first</div>
    <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-3-desktop">second</div>
  </div>
</div>
</code>```

Expecting on Desktop:

```<code>| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|----|----|----|
| ~ | ~ | ~ |   first   |  second   | ~  |  ~ | ~  |
</code>```

Instead of what really outputs:

```<code>| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|----|----|----|
|   first   |  second   | ~ | ~ | ~ | ~  |  ~ |  ~ |
</code>```

How to make cells stays centralized?

答:
The grid is center aligned, the grid cell spacing is not aligned to the center of the grid (which you seem to assume). Thus, if you give the grid a width of 50% relative to its container, and make your cells have a span-width of 6, that will give the desired effect on desktop. Alternatively, you could add an empty cell with a span width of 3 before your first cell. But that's a bit harder to tune for other screen sizes (on tablet and phone the grid uses 8 and 4 cell widths by default).

Since the column span is 8 on tablet and 4 on phone, and you did not specify how you want your cells played out on such devices

Body:
I want to have a centralized grid cells with, for example, 6 columns in desktop. In docs, it says:

The grid is by default center aligned. You can add mdc-layout-grid--align-left or mdc-layout-grid--align-right modifier class to change this behavior.

Then I type:

first

second

Expecting on Desktop:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|----|----|----|
| ~ | ~ | ~ |   first   |  second   | ~  |  ~ | ~  |

Instead of what really outputs:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|----|----|----|
|   first   |  second   | ~ | ~ | ~ | ~  |  ~ |  ~ |

How to make cells stays centralized?


问:
materialize css: remove gap/space between grid
Is there any idea how to remove gap/space between the grid?
Here's an example of code for each columns, it will show the gap/space between grid

```<code><div class="row">
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
</div>
</code>```

答:
Try to add padding: 0; to .row .col.s4 in your main css file.

.row .col.s4 {
  padding: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<div class="row">
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
</div></code>```

Body:
Is there any idea how to remove gap/space between the grid?
Here's an example of code for each columns, it will show the gap/space between grid

4

4

4

Body:
Try to add padding: 0; to .row .col.s4 in your main css file.

.row .col.s4 {
  padding: 0;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<div class="row">
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
  <div class="col s4">
    <div class="card-panel light-blue">4</div>
  </div>
</div>


问:
How to populate dropdownlist with JSON data as ajax response in jQuery
I am working on a j2ee application. In my application I have a drop-down list(or Select element). I want to populate this drop-down list with JSON data as a Ajax response.

Below is the code what I have:

Server side Code (json_source.java) which generates a JSON response. :

```<code>package demo.model;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.*;

/**
 * Servlet implementation class json_source
 */
public class json_source extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    JsonArray data_json=new JsonArray();

    Statement st_loginId=null;
    ResultSet rs_loginId=null;
    try
    {
        Connection con=null;

        Class.forName("oracle.jdbc.OracleDriver");

        /* Connection String for "OPERWH"(exadata) Database */
        con=DriverManager.getConnection("jdbc:oracle:thin:*************","*****","*****");

        con.setAutoCommit(true);

        st_loginId=con.createStatement();
        rs_loginId=st_loginId.executeQuery("select login_id \"LOGIN ID\" from user_access");
        //System.out.println("entered in frame_login_code");
        int login_val=0;
        JsonObject json_response=new JsonObject();

        while(rs_loginId.next())
        {
            login_val++;
            JsonObject json=new JsonObject();
            json.addProperty("value", "login"+login_val);
            json.addProperty("text", rs_loginId.getString(1));
            data_json.add(json);
        }
        System.out.println(data_json);
        json_response.add("aaData", data_json);

        response.setContentType("application/Json");

        response.getWriter().write(json_response.toString());

        System.out.println(json_response);
    }
    catch(Exception ex)
    {
        System.out.println("Exception occured during retrieval of Login_Id in ComboBox :"+ex);
        ex.printStackTrace();
    }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

}
</code>```

and the JSON data which successfully generated through above server side code :

```<code>{
    "aaData": [{
        "value": "login1",
        "text": "kapils"
    }, {
        "value": "login2",
        "text": "davidn"
    }, {
        "value": "login3",
        "text": "alanp"
    }]
}
</code>```

and Below is my Client side code (source1.jsp) which generate ajax request:

(Using $.ajax() ) :

```<code><script type="text/javascript">
$(document).ready(function()
{
$('#id_trial').click(function() {

    alert("entered in trial button code");

    $.ajax({
        type: "GET",
        url:"/demo_trial_application/json_source",
        dataType: "json",
        success: function (data) {
            $.each(data.aaData,function(i,data)
            {
             alert(data.value+":"+data.text);
             var div_data="<option value="+data.value+">"+data.text+"</option>";
            alert(div_data);
            $(div_data).appendTo('#ch_user1');
            });
            }
      });
    });
});

</script>

<body>

<div id="div_source1">
    <select id="ch_user1" >
        <option value="select"></option>
    </select>
</div>
<input type="button" id="id_trial" name="btn_trial" value="Trial Button..">
</body>
</code>```

OR Using ($.getJSON()) :

```<code>$.getJSON("/demo_trial_application/json_source", function (data) {
    $.each(data.aaData, function (i, data) {
        var div_data = "<option value=" + data.value + ">" + data.text + "</option>";
        alert(div_data);
        $(div_data).appendTo('#ch_user1');

    });
});
</code>```

Now when I clicked on button (#id_trial), the server side code executes successfully and as a result JSON object created. but i am not getting that "JSON response" in callback function of Success parameter using jQuery's ajax call.

and apart from jQuery's ajax call I also tried with $.getJSON function to receive JSON response..but I didn't get JSON data.

So please tell me if there is any mistake in my code, and how to get JSON data using above code and populate drop-down list.

I want to populate my dropdownlist with JSON data using ajax response.
please help me to sort out this problem...its very urgent for my application.

答:
The simplest way is to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src . This JQuery library directly loads JSON into dropdows and looks like a perfect match for your example. You just need to put the following code:

```<code>success: function (data) {
            $('#ch_user1').view(data.aaData);
}
</code>```

Take a look at this page https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown for more details.

Body:
I am working on a j2ee application. In my application I have a drop-down list(or Select element). I want to populate this drop-down list with JSON data as a Ajax response.

Below is the code what I have:

Server side Code (json_source.java) which generates a JSON response. :

package demo.model;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.*;

/**
 * Servlet implementation class json_source
 */
public class json_source extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    JsonArray data_json=new JsonArray();

    Statement st_loginId=null;
    ResultSet rs_loginId=null;
    try
    {
        Connection con=null;

        Class.forName("oracle.jdbc.OracleDriver");

        /* Connection String for "OPERWH"(exadata) Database */
        con=DriverManager.getConnection("jdbc:oracle:thin:*************","*****","*****");

        con.setAutoCommit(true);

        st_loginId=con.createStatement();
        rs_loginId=st_loginId.executeQuery("select login_id \"LOGIN ID\" from user_access");
        //System.out.println("entered in frame_login_code");
        int login_val=0;
        JsonObject json_response=new JsonObject();

        while(rs_loginId.next())
        {
            login_val++;
            JsonObject json=new JsonObject();
            json.addProperty("value", "login"+login_val);
            json.addProperty("text", rs_loginId.getString(1));
            data_json.add(json);
        }
        System.out.println(data_json);
        json_response.add("aaData", data_json);

        response.setContentType("application/Json");

        response.getWriter().write(json_response.toString());

        System.out.println(json_response);
    }
    catch(Exception ex)
    {
        System.out.println("Exception occured during retrieval of Login_Id in ComboBox :"+ex);
        ex.printStackTrace();
    }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

}

and the JSON data which successfully generated through above server side code :

{
    "aaData": [{
        "value": "login1",
        "text": "kapils"
    }, {
        "value": "login2",
        "text": "davidn"
    }, {
        "value": "login3",
        "text": "alanp"
    }]
}

and Below is my Client side code (source1.jsp) which generate ajax request:

(Using $.ajax() ) :

    <select id="ch_user1" >
        <option value="select"></option>
    </select>

<input type="button" id="id_trial" name="btn_trial" value="Trial Button..">

OR Using ($.getJSON()) :

$.getJSON("/demo_trial_application/json_source", function (data) {
    $.each(data.aaData, function (i, data) {
        var div_data = "<option value=" + data.value + ">" + data.text + "</option>";
        alert(div_data);
        $(div_data).appendTo('#ch_user1');

    });
});

Now when I clicked on button (#id_trial), the server side code executes successfully and as a result JSON object created. but i am not getting that "JSON response" in callback function of Success parameter using jQuery's ajax call.

and apart from jQuery's ajax call I also tried with $.getJSON function to receive JSON response..but I didn't get JSON data.

So please tell me if there is any mistake in my code, and how to get JSON data using above code and populate drop-down list.

I want to populate my dropdownlist with JSON data using ajax response.
please help me to sort out this problem...its very urgent for my application.

Body:
The simplest way is to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src . This JQuery library directly loads JSON into dropdows and looks like a perfect match for your example. You just need to put the following code:

success: function (data) {
            $('#ch_user1').view(data.aaData);
}

Take a look at this page https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown for more details.


答:
There is answer here Does JavaScript Guarantee Object Property Order? among other that says:

most browsers returns properties in the same order as they were inserted, but it was explicitly not guaranteed behaviour so shouldn't have been relied upon.

The ECMAScript specification used to say:

The mechanics and order of enumerating the properties ... is not
  specified.

However in ES2015 and later non-integer keys will be returned in insertion order.

So don't rely on order of an object keys. If you don't worry about ES5 you can try to use non-integer keys - strings for instance but note that strings like '1' are not suitable http://code.google.com/p/v8/issues/detail?id=164.

You can find on the page of the answer also:

If you rely on insertion order, you are outside the ECMAScript spec, but within the de-facto standard of common browser behavior as long as your keys don't parse as integers.

UPDATE

Short answer is axios doesn't sort keys of an object

https://jsfiddle.net/zabq841t/

```<code>axios.get('/echo/js/?js={a2: 1, a1: 0}')
    .then((res) => {
        //res.data is {a2: 1, a1: 0}
    })
</code>```

You can get sorted version because of old browser or your server. Take a look fiddle if it works for you then probably you have 'issue' on server side. You need to provide more details about you server app.

Title: axios: stop automatic sorting of objects based on keys

Body:
There is answer here Does JavaScript Guarantee Object Property Order? among other that says:

most browsers returns properties in the same order as they were inserted, but it was explicitly not guaranteed behaviour so shouldn't have been relied upon.

The ECMAScript specification used to say:

The mechanics and order of enumerating the properties ... is not
  specified.

However in ES2015 and later non-integer keys will be returned in insertion order.

So don't rely on order of an object keys. If you don't worry about ES5 you can try to use non-integer keys - strings for instance but note that strings like '1' are not suitable http://code.google.com/p/v8/issues/detail?id=164.

You can find on the page of the answer also:

If you rely on insertion order, you are outside the ECMAScript spec, but within the de-facto standard of common browser behavior as long as your keys don't parse as integers.

UPDATE

Short answer is axios doesn't sort keys of an object

https://jsfiddle.net/zabq841t/

axios.get('/echo/js/?js={a2: 1, a1: 0}')
    .then((res) => {
        //res.data is {a2: 1, a1: 0}
    })

You can get sorted version because of old browser or your server. Take a look fiddle if it works for you then probably you have 'issue' on server side. You need to provide more details about you server app.


问:
CefSharp How to read values from getElementById('numbers')?
I wrote a simple web browser. I can log in to the site, and modify the values of the page. But I have one problem. How to read the value entered into the form?

I've tried:

```<code>labeltest.Text =
 chrome.EvaluateScriptAsync("var c=document.getElementById('numbers');c.value;").ToString();
</code>```

How to return the value to label.Test = c?

but returns a value:
System.Threading.Tasks.Taks[CefSharp.JavascriptResponse]

答:
You must use the members of javascriptResponse : success, result & message.
Here's a sample that you could try in your main form code :

```<code>private JavascriptResponse JsScriptResult(string script, int timeout)
{
    if (browserTabControl.SelectedIndex == -1)
      {return null;}

    BrowserTabUserControl tabBrowser = (BrowserTabUserControl)browserTabControl.TabPages(browserTabControl.SelectedIndex).Controls(0);
    IFrame frame = tabBrowser.Browser.GetFocusedFrame();
    Task<JavascriptResponse> Task = frame.EvaluateScriptAsync(script, timeout: TimeSpan.FromMilliseconds(timeout));
    Task.Wait();
    return Task.Result;
}

private void test()
{
    JavascriptResponse result;
    // get a list of input elements with an id
    string script = "var els = document.getElementsByTagName('input');\n var t = [];\nfor (i=0;i<els.length;i++)\n  if (els[i].id) t.push(els[i].id);\n t.join('\\n');";
    result = JsScriptResult(script, 5000);
    if (!result.Success)
    {
        MsgBox(result.Message, MsgBoxStyle.Exclamation, "Script error");
        return;
    }

    // get value for an element with given id
    string id = InputBox(result.Result.ToString, "Id to search ?");
    if (id.Length > 0){
        result = JsScriptResult($"document.getElementById('{id}').value;", 1000);
        MsgBox($"Result = {result.Result}\nMessage = {result.Message}", result.Success ? MsgBoxStyle.Information : MsgBoxStyle.Exclamation, "Script result");
    }
}
</code>```

or in VB.net

```<code>Private Function JsScriptResult(script As String, timeout As Integer) As JavascriptResponse
   If browserTabControl.SelectedIndex = -1 Then
      Return Nothing
   End If
   Dim tabBrowser As BrowserTabUserControl = CType(browserTabControl.TabPages(browserTabControl.SelectedIndex).Controls(0), BrowserTabUserControl)
   Dim frame As IFrame = tabBrowser.Browser.GetFocusedFrame()
   'Execute extension method
   Dim Task As Task(Of JavascriptResponse) = frame.EvaluateScriptAsync(script, timeout:=TimeSpan.FromMilliseconds(timeout))
   Task.Wait()
   Return Task.Result
End Function
Sub test() Handles ConnexionMdhMenuItem.Click
   Dim result As JavascriptResponse
   ' get a list of input elements with an id
   Dim script As String = "
     var els = document.getElementsByTagName('input');
     var t = [];
     for (i=0;i<els.length;i++)
       if (els[i].id) t.push(els[i].id);
     t.join('\n');"

   result = JsScriptResult(script, 5000)
   If Not result.Success Then
      MsgBox(result.Message, MsgBoxStyle.Exclamation, "Script error")
      Return
   End If
   'get value for an element with given id
   Dim id As String = Interaction.InputBox(result.Result.ToString, "Id to search ?")
   If id.Length > 0 Then
      result = JsScriptResult($"document.getElementById('{id}').value;", 1000)
      MsgBox($"Result = {result.Result}{vbCr}Message = {result.Message}",
               If(result.Success, MsgBoxStyle.Information, MsgBoxStyle.Exclamation), "Script result")
   End If
End Sub
</code>```

Body:
I wrote a simple web browser. I can log in to the site, and modify the values of the page. But I have one problem. How to read the value entered into the form?

I've tried:

labeltest.Text =
 chrome.EvaluateScriptAsync("var c=document.getElementById('numbers');c.value;").ToString();

How to return the value to label.Test = c?

but returns a value:
System.Threading.Tasks.Taks[CefSharp.JavascriptResponse]

Body:
You must use the members of javascriptResponse : success, result & message.
Here's a sample that you could try in your main form code :

private JavascriptResponse JsScriptResult(string script, int timeout)
{
    if (browserTabControl.SelectedIndex == -1)
      {return null;}

    BrowserTabUserControl tabBrowser = (BrowserTabUserControl)browserTabControl.TabPages(browserTabControl.SelectedIndex).Controls(0);
    IFrame frame = tabBrowser.Browser.GetFocusedFrame();
    Task<JavascriptResponse> Task = frame.EvaluateScriptAsync(script, timeout: TimeSpan.FromMilliseconds(timeout));
    Task.Wait();
    return Task.Result;
}

private void test()
{
    JavascriptResponse result;
    // get a list of input elements with an id
    string script = "var els = document.getElementsByTagName('input');\n var t = [];\nfor (i=0;i<els.length;i++)\n  if (els[i].id) t.push(els[i].id);\n t.join('\\n');";
    result = JsScriptResult(script, 5000);
    if (!result.Success)
    {
        MsgBox(result.Message, MsgBoxStyle.Exclamation, "Script error");
        return;
    }

    // get value for an element with given id
    string id = InputBox(result.Result.ToString, "Id to search ?");
    if (id.Length > 0){
        result = JsScriptResult($"document.getElementById('{id}').value;", 1000);
        MsgBox($"Result = {result.Result}\nMessage = {result.Message}", result.Success ? MsgBoxStyle.Information : MsgBoxStyle.Exclamation, "Script result");
    }
}

or in VB.net

Private Function JsScriptResult(script As String, timeout As Integer) As JavascriptResponse
   If browserTabControl.SelectedIndex = -1 Then
      Return Nothing
   End If
   Dim tabBrowser As BrowserTabUserControl = CType(browserTabControl.TabPages(browserTabControl.SelectedIndex).Controls(0), BrowserTabUserControl)
   Dim frame As IFrame = tabBrowser.Browser.GetFocusedFrame()
   'Execute extension method
   Dim Task As Task(Of JavascriptResponse) = frame.EvaluateScriptAsync(script, timeout:=TimeSpan.FromMilliseconds(timeout))
   Task.Wait()
   Return Task.Result
End Function
Sub test() Handles ConnexionMdhMenuItem.Click
   Dim result As JavascriptResponse
   ' get a list of input elements with an id
   Dim script As String = "
     var els = document.getElementsByTagName('input');
     var t = [];
     for (i=0;i<els.length;i++)
       if (els[i].id) t.push(els[i].id);
     t.join('\n');"

   result = JsScriptResult(script, 5000)
   If Not result.Success Then
      MsgBox(result.Message, MsgBoxStyle.Exclamation, "Script error")
      Return
   End If
   'get value for an element with given id
   Dim id As String = Interaction.InputBox(result.Result.ToString, "Id to search ?")
   If id.Length > 0 Then
      result = JsScriptResult($"document.getElementById('{id}').value;", 1000)
      MsgBox($"Result = {result.Result}{vbCr}Message = {result.Message}",
               If(result.Success, MsgBoxStyle.Information, MsgBoxStyle.Exclamation), "Script result")
   End If
End Sub


问:
Why is my PHP and HTML code not working?
There is this code that I am trying to write. The user is supposed to guess a random, odd number between 1 and 99 and the code is supposed to include both php and HTML codes.

This is the code I came up with:

```<code><?php

$heading = "Welcome to the guessing game";
$num_to_guess = rand(1,99);
if(!isset($_POST['guess'])){
$message= "Welcome to the guessing game";

} elseif($_POST['guess'] %2==0) {
    $message= "The number you are guessing is not odd!!!";

} elseif($_POST['guess']< $num_to_guess){
    $message= "Your guess is smaller than the secret number";

}elseif($_POST['guess']> $num_to_guess){
    $message= "Your guess is bigger than the secret number";

} else($_POST['guess']= $num_to_guess){
    $message= "You guessed correctly.Now try to guess another number!";
}

?>
<!DOCTYPE html>
<html>
<head>
<title> Guessing Machine </title
</head>
<body>
<form action="" method="POST">
Try to guess the odd number between 1 and 99
<input type="hidden" name="number" value='value="<?php echo $number; ?>">

<br><br>
<input type="submit" name="check" value="check"/><br><br>
</form>
</body>
</html>
</code>```

I know that the code is not completely correct, because it is not giving me the expected result. Can anyone tell me what exactly is wrong with my code? I am very confused. Thank you.

答:
Replace your last ELSEIF with the following codes:

} elseif($_POST['guess']== $num_to_guess){

Body:
There is this code that I am trying to write. The user is supposed to guess a random, odd number between 1 and 99 and the code is supposed to include both php and HTML codes.

This is the code I came up with:

<?php

$heading = "Welcome to the guessing game";
$num_to_guess = rand(1,99);
if(!isset($_POST['guess'])){
$message= "Welcome to the guessing game";

} elseif($_POST['guess'] %2==0) {
    $message= "The number you are guessing is not odd!!!";

} elseif($_POST['guess']< $num_to_guess){
    $message= "Your guess is smaller than the secret number";

}elseif($_POST['guess']> $num_to_guess){
    $message= "Your guess is bigger than the secret number";

} else($_POST['guess']= $num_to_guess){
    $message= "You guessed correctly.Now try to guess another number!";
}

?>
<!DOCTYPE html>

<title> Guessing Machine </title

<form action="" method="POST">
Try to guess the odd number between 1 and 99
<input type="hidden" name="number" value='value="<?php echo $number; ?>">

<input type="submit" name="check" value="check"/>

</form>

I know that the code is not completely correct, because it is not giving me the expected result. Can anyone tell me what exactly is wrong with my code? I am very confused. Thank you.


问:
How to do this query in laravel?
I want to select data from multiple tables in laravel. How can I do a query like this in laravel?
Here is my query which I want to use in laravel with pagination </p>

```<code>$blog = DB::select("select blog_post.*,(select img_name from blog_image WHERE blog_image.bid=blog_post.bid limit 0,1) as img_name,
    (SELECT count(*) FROM likes WHERE likes.bid =blog_post.bid) AS likes,
    (SELECT count(*) FROM comment WHERE comment.bid =blog_post.bid ) as comments ,
    (SELECT count(*) FROM blog_share WHERE blog_share.bid =blog_post.bid ) as  share
    from blog_post WHERE status=1 AND is_draft=0 AND is_publish=1 AND is_delete=0")->paginate(2);
</code>```

答:
It's a pretty standard query. First, you need to create a model for each table and define relationships in the BlogPost model.

To count relations, use withCount() method.

Title: How to do this query in laravel?

Body:
I want to select data from multiple tables in laravel. How can I do a query like this in laravel?
Here is my query which I want to use in laravel with pagination

$blog = DB::select("select blog_post.*,(select img_name from blog_image WHERE blog_image.bid=blog_post.bid limit 0,1) as img_name,
    (SELECT count(*) FROM likes WHERE likes.bid =blog_post.bid) AS likes,
    (SELECT count(*) FROM comment WHERE comment.bid =blog_post.bid ) as comments ,
    (SELECT count(*) FROM blog_share WHERE blog_share.bid =blog_post.bid ) as  share
    from blog_post WHERE status=1 AND is_draft=0 AND is_publish=1 AND is_delete=0")->paginate(2);


问:
Import and transpile external library with Webpack and typescript-loader
I have project that uses Webpack and Typescript (typescript-loader). My tsconfig.json file is pretty straightforward and is set to target ES5:

```<code>{
    "compilerOptions": {
        "outDir": "./public/dist",
        "noImplicitAny": false,
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
    }
}
</code>```

The webpack configuration file contains the following rule for my typescript files:

```<code>module: {
    rules: [{
       test: /\.ts?$/,
       loader: 'ts-loader'
    }]
},
</code>```

All my project files are being compiled as intended to ES5 code and run fine. However, in one of my TS files I import a library installed through NPM: import * as striptags from "striptags"

The problem is that this file is not transpiled into ES5 and ends up with const and let keywords in my bundle that is targeted at ES5 devices. This causes JS errors.

How can I import the external striptags library and transpile it to ES5 so it doesn't break my client-side code?

I'm using TypeScript 2.6.1 and Webpack 3.10.0. Thanks!

答: I noticed that I did not read the readme of the striptags library correctly. It states that you should use the 2.x.x branch for ES5 support. Everything works fine now.</p>

Body:
I have project that uses Webpack and Typescript (typescript-loader). My tsconfig.json file is pretty straightforward and is set to target ES5:

{
    "compilerOptions": {
        "outDir": "./public/dist",
        "noImplicitAny": false,
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
    }
}

The webpack configuration file contains the following rule for my typescript files:

module: {
    rules: [{
       test: /\.ts?$/,
       loader: 'ts-loader'
    }]
},

All my project files are being compiled as intended to ES5 code and run fine. However, in one of my TS files I import a library installed through NPM: import * as striptags from "striptags"

The problem is that this file is not transpiled into ES5 and ends up with const and let keywords in my bundle that is targeted at ES5 devices. This causes JS errors.

How can I import the external striptags library and transpile it to ES5 so it doesn't break my client-side code?

I'm using TypeScript 2.6.1 and Webpack 3.10.0. Thanks!


问:
How do I change the timezone to UTC in postgres permanently?
I have set the timezone in postgresql.conf as follows :-

```<code>- Locale and Formatting -

datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'UTC'
#timezone_abbreviations = 'Default'
</code>```

But When I do see the timezone in postgres server it defaults to 'Asia/Kolkata'.
I have installed the postgres using brew package in MacOs.

答:
setting timezone in postgresql.conf just sets the default for clients without this setting. If you see other value, means client sets it to some local value.

Or alternatively that you did not reload server:

```<code>select pg_reload_conf();
</code>```

To check the setting and what's needed to enable it, you can:

```<code>t=# select * from pg_settings where name = 'TimeZone';
-[ RECORD 1 ]---+----------------------------------------------------------------
name            | TimeZone
setting         | UTC
unit            |
category        | Client Connection Defaults / Locale and Formatting
short_desc      | Sets the time zone for displaying and interpreting time stamps.
extra_desc      |
context         | user
vartype         | string
source          | configuration file
min_val         |
max_val         |
enumvals        |
boot_val        | GMT
reset_val       | UTC
sourcefile      | /Users/vao/t96/postgresql.conf
sourceline      | 556
pending_restart | f
</code>```

pending_restart false means you don't need to restart postgres, but you still need to reload config after change. Also as you see this setting influence client only. And obviously client can easily override ths default.

to set timezone client side, just run set timezone to 'UTC'.

in order to set this for some user permanently, use alter user uname set timezone and same for setting default for db.

Body:
I have set the timezone in postgresql.conf as follows :-

- Locale and Formatting -

datestyle = 'iso, mdy'
#intervalstyle = 'postgres'
timezone = 'UTC'
#timezone_abbreviations = 'Default'

But When I do see the timezone in postgres server it defaults to 'Asia/Kolkata'.
I have installed the postgres using brew package in MacOs.

Body:
setting timezone in postgresql.conf just sets the default for clients without this setting. If you see other value, means client sets it to some local value.

Or alternatively that you did not reload server:

select pg_reload_conf();

To check the setting and what's needed to enable it, you can:

t=# select * from pg_settings where name = 'TimeZone';
-[ RECORD 1 ]---+----------------------------------------------------------------
name            | TimeZone
setting         | UTC
unit            |
category        | Client Connection Defaults / Locale and Formatting
short_desc      | Sets the time zone for displaying and interpreting time stamps.
extra_desc      |
context         | user
vartype         | string
source          | configuration file
min_val         |
max_val         |
enumvals        |
boot_val        | GMT
reset_val       | UTC
sourcefile      | /Users/vao/t96/postgresql.conf
sourceline      | 556
pending_restart | f

pending_restart false means you don't need to restart postgres, but you still need to reload config after change. Also as you see this setting influence client only. And obviously client can easily override ths default.

to set timezone client side, just run set timezone to 'UTC'.

in order to set this for some user permanently, use alter user uname set timezone and same for setting default for db.