问:
VS Code does not stop at any breakpoints on mac
I am trying to test the debugger in VS Code and I believe I have configured my launch.json and tasks.json correctly but the debugger is just not stopping at my breakpoints.

I tried re-installing VS code, re-configuring, trying different source files.. but I just can't get this debugger to run. I am a beginner so most likely something I'm missing.

I expect the debugger to stop at line 8.

writtenassignment.cpp

```<code>#include <iostream>

using namespace std;

int main(int argc, char ** argv){
    int array [9] = {-10, -7, -1, 0, 4, 7, 8, 12, 19};
    int i, j, sum = 4;
    for (i = 0; i <= 8; i++){
        for (j = i + 1; j <= 8; j++){
                int a = array[i];
                int b = array[j];
                cout << "a: " << a << " b: " << b << " i: " << i << " j: " << j << endl;
            if (a + b == sum) {
                cout << a << " + " << b << " = " << sum << endl;
                //exit;
            }
        }
    }
    return -1;
}
</code>```

tasks.json

```<code>    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
</code>```

launch.json

```<code>    "version": "0.2.0",
    "configurations": [
        {
            "name": "(lldb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/writtenassignment",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb"
        }
    ]
}
</code>```

答:
What worked for me while debugging just one file was:

```<code>task.json:
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "gcc build active file",
            "command": "/usr/bin/gcc",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}.o"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        }
    ]
}
</code>```

launch.json

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "gcc",
            "type": "cppdbg",
            "request": "launch",
            "preLaunchTask": "gcc build active file",
            "program": "${fileDirname}/${fileBasenameNoExtension}.o",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "miDebuggerPath": "/usr/bin/gdb",
            "additionalSOLibSearchPath": "."
        }
    ]
}
</code>```

Note I added ".o" after "${fileBasenameNoExtension}".
Next, make sure the c/cpp file is opened and in the active tab.
Now you can start debugging.

Body:
I am trying to test the debugger in VS Code and I believe I have configured my launch.json and tasks.json correctly but the debugger is just not stopping at my breakpoints.

I tried re-installing VS code, re-configuring, trying different source files.. but I just can't get this debugger to run. I am a beginner so most likely something I'm missing.

I expect the debugger to stop at line 8.

writtenassignment.cpp

#include <iostream>

using namespace std;

int main(int argc, char ** argv){
    int array [9] = {-10, -7, -1, 0, 4, 7, 8, 12, 19};
    int i, j, sum = 4;
    for (i = 0; i <= 8; i++){
        for (j = i + 1; j <= 8; j++){
                int a = array[i];
                int b = array[j];
                cout << "a: " << a << " b: " << b << " i: " << i << " j: " << j << endl;
            if (a + b == sum) {
                cout << a << " + " << b << " = " << sum << endl;
                //exit;
            }
        }
    }
    return -1;
}

tasks.json

    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

launch.json

    "version": "0.2.0",
    "configurations": [
        {
            "name": "(lldb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/writtenassignment",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb"
        }
    ]
}

Body:
What worked for me while debugging just one file was:

task.json:
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "gcc build active file",
            "command": "/usr/bin/gcc",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}.o"
            ],
            "options": {
                "cwd": "/usr/bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        }
    ]
}

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "gcc",
            "type": "cppdbg",
            "request": "launch",
            "preLaunchTask": "gcc build active file",
            "program": "${fileDirname}/${fileBasenameNoExtension}.o",
            "args": [],
            "stopAtEntry": true,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "miDebuggerPath": "/usr/bin/gdb",
            "additionalSOLibSearchPath": "."
        }
    ]
}

Note I added ".o" after "${fileBasenameNoExtension}".
Next, make sure the c/cpp file is opened and in the active tab.
Now you can start debugging.


来源: stackexchange

问:
when this code executes, it shows no output. Why is that?
Following code has no output when it executes. Can anyone explain the following code?

int main() {
  int i, j;

  for (i = 0; i < 10; i++) {
    if (i % 2)
      printf("%d\t", i);
    else
      break;
  }
}
```

答:
Your code has two issues:

1.

if (i % 2)

The condition of (i % 2) evaluates to false because the calculation - 0 divided by 2 - result in 0  -> 0 / 2 = 0. The remainder is also 0.

2.

else break;

That provides the result if (i % 2) is not true (which is the case with 0 at the first iteration) you immediately will break out of the for loop. Omit the break; statement in general, if you want to proof if all values from 0 to 9 have an remainder when divided by 2 or not.

Note that to pack break; in an separate else statement is nonetheless redundant.

Side note:

j has no use in your code.

I guess what you want is something like that:

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

int main (void) {
   int i, j;

   for ( i = 0; i < 10; i++ ) {
     if ( ( j = i % 2 ) )
       printf("(%d / 2) has a remainder of %d.\n", i, j);
     else
       printf("(%d / 2) has no remainder.\n", i);
   }
}
</code>```

Output:

```<code>(0 / 2) has no remainder.
(1 / 2) has a remainder of 1.
(2 / 2) has no remainder.
(3 / 2) has a remainder of 1.
(4 / 2) has no remainder.
(5 / 2) has a remainder of 1.
(6 / 2) has no remainder.
(7 / 2) has a remainder of 1.
(8 / 2) has no remainder.
(9 / 2) has a remainder of 1.
</code>```

Try this code online.

Note that by the division 1 / 2, the result 0.5 is raised to the nearest upper integral value 1 because of the implicit double to int conversion.

ContentLicense: CC BY-SA 4.0

Body:
Your code has two issues:

1.

if (i % 2)

The condition of (i % 2) evaluates to false because the calculation - 0 divided by 2 - result in 0  -> 0 / 2 = 0. The remainder is also 0.

2.

else break;

That provides the result if (i % 2) is not true (which is the case with 0 at the first iteration) you immediately will break out of the for loop. Omit the break; statement in general, if you want to proof if all values from 0 to 9 have an remainder when divided by 2 or not.

Note that to pack break; in an separate else statement is nonetheless redundant.

Side note:

j has no use in your code.

I guess what you want is something like that:

#include <stdio.h>

int main (void) {
   int i, j;

   for ( i = 0; i < 10; i++ ) {
     if ( ( j = i % 2 ) )
       printf("(%d / 2) has a remainder of %d.\n", i, j);
     else
       printf("(%d / 2) has no remainder.\n", i);
   }
}

Output:

(0 / 2) has no remainder.
(1 / 2) has a remainder of 1.
(2 / 2) has no remainder.
(3 / 2) has a remainder of 1.
(4 / 2) has no remainder.
(5 / 2) has a remainder of 1.
(6 / 2) has no remainder.
(7 / 2) has a remainder of 1.
(8 / 2) has no remainder.
(9 / 2) has a remainder of 1.

Try this code online.

Note that by the division 1 / 2, the result 0.5 is raised to the nearest upper integral value 1 because of the implicit double to int conversion.


问:
Find path with minimum cost and maximum length given a maximum cost
I'm searching for an algorithm to find a path between two nodes with minimum cost and maximum length given a maximum cost in an undirected weighted complete graph. Weights are non negative.

As I stand now I'm using DFS, and it's pretty slow (high number of nodes and maximum length too). I already discard all the impossible nodes in every iteration of the DFS.

Could someone point me to a known algorithm for better handling of this problem?

To clarify: ideally the algorithm should search for the path of minimum cost, but is allowed to add cost if this means visiting more nodes. It should end when it concludes that it's impossible to reach more than n nodes without crossing the cost limit and it's impossible to reach n nodes with less cost.

Update

Example of a graph. We have to go from A to B. Cost limit is set to 5:

This path (in red) is ok, but the algorithm should continue searching for better solutions

This is better because although the cost is increased to 4, it contains 1 more node

Here the path contains 3 nodes so it's a lot better than before and the cost is an acceptable 5

Finally this solution is even better because the path also contains 3 nodes but with cost 4, with is less than before.

Hope images explain better than text

答:
This problem can formulated as Multi-objective Constraint Satisfaction Problem with priority:

First, solution must satisfy the constraint about maximum cost.

Next, solution must has maximum number of nodes (1st objective).

Finally, solution must has minimum cost (2st objective).

This problem is NP-hard. So, there isn't exact polynomial time algorithm for this problem. But a simple local search algorithm may help you:

First, use Dijkstra algorithm to find minimum cost path, called P. If the cost is bigger than maximum cost, there isn't solution satisfy constraint.

Next, try add more nodes to P by using 2 move operators:

Insert: select a node outside P and insert in best position in P.

Replace: select a node outside P and replace a node inside P (when can't use insert operator).

Finally, try reduce cost by using replace operator.

ContentLicense: CC BY-SA 3.0


问:
"Time ago" from MySQL timestamp
I'm trying to make a table of results including the timestamp for each entry from the database. However, I need the time to be displayed as "X seconds/minutes/hours ago".

I've tried the jQuery timeago plugin with zero success and am now wondering how to do this for each entry.

```<code>$result = mysql_query("SELECT * from realmfeed order by ID asc");

echo "<table class='display'>\n";

while($row = mysql_fetch_array($result))
{
    echo "<tr><td><b>".$row['ID']."</b></td>\n";
    echo "<td>".$row['eventType']."</td>\n";
    echo "<td>".$row['server']."</td>\n";
    echo "<td>".$row['realm']."</td>\n";
    echo "<td>".$row['name']."</td>\n";
    echo "<td>".$row['time']."</td>\n</tr>\n\n";
}

echo "</table>\n";
</code>```

How is it possible to create a "time ago" function for each result?

答:
The problem with using PHP to do the time difference calculations is you're assuming the MySQL and PHP servers are in the same time zones. Better to do the difference calculation in the SELECT:

SELECT TIMEDIFF(NOW(), `time`) AS ago FROM realmfeed ORDER BY ID ASC

This will return hh:mm:ss formatted time difference.

Or if you'd prefer just the number of seconds:

SELECT TIME_TO_SEC(TIMEDIFF(NOW(), `time`)) AS secondsAgo FROM realmfeed ORDER BY ID ASC

Title: "Time ago" from MySQL timestamp

Body:
I'm trying to make a table of results including the timestamp for each entry from the database. However, I need the time to be displayed as "X seconds/minutes/hours ago".

I've tried the jQuery timeago plugin with zero success and am now wondering how to do this for each entry.

$result = mysql_query("SELECT * from realmfeed order by ID asc");

echo "
\n";

while($row = mysql_fetch_array($result))
{
    echo "
".$row['ID']."	\n";
    echo "".$row['eventType']."	\n";
    echo "".$row['server']."	\n";
    echo "".$row['realm']."	\n";
    echo "".$row['name']."	\n";
    echo "".$row['time']."	\n
\n\n";
}

echo "
\n";

How is it possible to create a "time ago" function for each result?


问:
ZenCoding is not working in Visual Studio 2017 community edition
I installed web essentials 2017 after downloading it from the Marketplace Link-https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebExtensionPack2017 . Then installed it after closing Visual studio and tried ZenCoding in a razor page. puffff tab doesn't work.

I don't have ReSharper

答:
After going through a lot of blogs, a few suggested the same solution, that we need to follow the installation steps

Install Web Essentials

Install ZenCoding

Then try ZenCoding, if it doesn't work uninstall both i.e. Web Essentials & ZenCoding and follow set 1 & 2.

This worked for me.


问:
How can I stop outputting text, when a condition is met?
I wrote this code to tell me if a bitcoin is below to a certain value, but the problem is that when i run this code, It keeps spamming either conditions "okay" or "not okay". so I'm wondering how can i stop this process, so that when it's below target, it'll just say not okay and stop outputting until price of bitcoin rises.</p>

```<code>target = 9440
while True:
    with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
        data = json.loads(url.read().decode())
    price = float(data.get('bpi').get('USD').get('rate').replace(",", ""))
    if price <= target:
        print("Not okay\n")
    else:
        print("Okay\n")
</code>```

答:
This script will print only a when there's change of value:

```<code>import urllib
from time import sleep

def generate(target):
    previous = float('nan')

    while True:
        sleep(1)    # sleep 1second to not spam the API

        with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
            data = json.loads(url.read().decode())
            value = float(data['bpi']['USD']['rate'].replace(",", ""))

            if previous == value:
                continue

            if value <= target:
                yield 'Okay', value
            else:
                yield 'Not Okay', value

            previous = value

target = 9440
for value in generate(target):
    print(value)
</code>```

Prints:

```<code>('Not Okay', 9550.425)
('Not Okay', 9550.325)
('Not Okay', 9554.63)
('Not Okay', 9554.5233)

... and so on.
</code>```

If you want to get information only when there's change between Okay and Not Okay, you can do this:

```<code>import urllib
from time import sleep

def generate(target):
    previous = float('nan')
    previous_state = ''

    while True:
        sleep(1)    # sleep 1second to not spam the API

        with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
            data = json.loads(url.read().decode())
            value = float(data['bpi']['USD']['rate'].replace(",", ""))

            if previous == value:
                continue

            if value <= target and previous_state != 'Okay':
                previous_state = 'Okay'
                yield previous_state, value
            elif value > target and previous_state != 'Not Okay':
                previous_state = 'Not Okay'
                yield previous_state, value

            previous = value

target = 9553.1
for value in generate(target):
    print(value)
</code>```

Prints:

```<code>('Not Okay', 9553.1017)
('Okay', 9552.9817)
('Not Okay', 9556.5983)

... and so on.
</code>```

Body:
I wrote this code to tell me if a bitcoin is below to a certain value, but the problem is that when i run this code, It keeps spamming either conditions "okay" or "not okay". so I'm wondering how can i stop this process, so that when it's below target, it'll just say not okay and stop outputting until price of bitcoin rises.

target = 9440
while True:
    with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
        data = json.loads(url.read().decode())
    price = float(data.get('bpi').get('USD').get('rate').replace(",", ""))
    if price <= target:
        print("Not okay\n")
    else:
        print("Okay\n")

Body:
This script will print only a when there's change of value:

import urllib
from time import sleep

def generate(target):
    previous = float('nan')

    while True:
        sleep(1)    # sleep 1second to not spam the API

        with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
            data = json.loads(url.read().decode())
            value = float(data['bpi']['USD']['rate'].replace(",", ""))

            if previous == value:
                continue

            if value <= target:
                yield 'Okay', value
            else:
                yield 'Not Okay', value

            previous = value

target = 9440
for value in generate(target):
    print(value)

Prints:

('Not Okay', 9550.425)
('Not Okay', 9550.325)
('Not Okay', 9554.63)
('Not Okay', 9554.5233)

... and so on.

If you want to get information only when there's change between Okay and Not Okay, you can do this:

import urllib
from time import sleep

def generate(target):
    previous = float('nan')
    previous_state = ''

    while True:
        sleep(1)    # sleep 1second to not spam the API

        with urllib.request.urlopen("https://api.coindesk.com/v1/bpi/currentprice.json") as url:
            data = json.loads(url.read().decode())
            value = float(data['bpi']['USD']['rate'].replace(",", ""))

            if previous == value:
                continue

            if value <= target and previous_state != 'Okay':
                previous_state = 'Okay'
                yield previous_state, value
            elif value > target and previous_state != 'Not Okay':
                previous_state = 'Not Okay'
                yield previous_state, value

            previous = value

target = 9553.1
for value in generate(target):
    print(value)

Prints:

('Not Okay', 9553.1017)
('Okay', 9552.9817)
('Not Okay', 9556.5983)

... and so on.


问:
Is + operator overloaded for primitive types?
Already overloaded operators <<,>>,= etc are used many times.

An example that i was thinking of is when we add strings say :

string name = string("munish") + "kumar";

the + operator is overloaded in the string class.

but when we add numbers like 1 + 2( doesn't seem like an overloaded operator call)

I was just wondering how does it happens does the compiler does a binary additon.

I don't need to worry about it much though if the compiler does it so, just a matter of curiosity for me.

答:
Primitive types don't implement operator+ which is actually a function with a weird name. Addition for Primitive type is carried out by CPU instruction such as :

```<code>addl %edx,(%eax) //this adds two integral values loaded at edx and eax
</code>```

You implement operator+ for user-defined types, and compiler generates lots of CPU instructions to carry out the task which you write in operator+.

Body:
Primitive types don't implement operator+ which is actually a function with a weird name. Addition for Primitive type is carried out by CPU instruction such as :

addl %edx,(%eax) //this adds two integral values loaded at edx and eax

You implement operator+ for user-defined types, and compiler generates lots of CPU instructions to carry out the task which you write in operator+.


问:
Dynamic site regeneration GatsbyJS
I have a website in GatsbyJS that has huge datasets of dynamic data fetched on load of a page via React fetch. The data displayed needs to be semi live (e.g. be refreshed every 5 minutes).

I am wondering how do I achieve SSR speeds with this, because dynamic fetch doesn't cut it. Is it cron scheduled rebuild and if so what happens during the replace of the build folder?

答:
You can use a service like Netlify. They provide a WebHook URL that triggers a build upon querying. You could then have a cron, every 5 minutes, hitting this URL to trigger a rebuild. Netlify handles the build for you, only replacing your site if the build succeeded.

If you want to do it yourself, you can maybe use Caddy - a webserver that has a plugin for deploying from git, similar to how Netlify works (only update site if build succeeds). Note: this is not yet supported by Caddy 2 (current version).

Another option is PM2, which also builds your site for your, handling failures gracefully (your site is always up, only replaced when the build succeeds).

Title: Dynamic site regeneration GatsbyJS


问:
converting pandas string data to numeric for decision tree
I am trying to convert several columns of string data into numeric to feed into a classification model. An example dataset with one modification column would be:

input:

```<code>data = [['tom', 10], ['nick', 15], ['juli', 14], ['nick', '12']]
data = pd.DataFrame(data, columns = ['Name', 'Age'])
data
</code>```

output:

```<code>    Name    Age
0   tom     10
1   nick    15
2   juli    14
3   nick    12
</code>```

I realize that scikit learn doesn't handle string data very well, but for now I'd really prefer to press onward with it, if possible (company restrictions). However, my issue is that if I use

```<code>sklearn.preprocessing.LabelEncoder
</code>```

i am able to use '.classes_' to get some numeric values, such as:

input:

```<code>le = preprocessing.LabelEncoder()
le.fit(data['Name'])
le.classes_
vals = le.transform(le.classes_)
vals
</code>```

I get

output:

```<code>array([0, 1, 2])
</code>```

Since this array only contains three values, I cannot use

data['Name'] = vals

for assignment because my column length is 4 and my vals length is 3.

Considering this, is there an alternate way for me to go about this in scikit-learn or is my only option to use a different library?

答:
```<code># prepare input features
def LABEL_Encoding(X):
    objList = data.select_dtypes(include = "object").columns
    print (objList)
    le = LabelEncoder()
    for feat in objList:
        data[feat] = le.fit_transform(data[feat].astype(str))

    return data

</code>```

Body:
I am trying to convert several columns of string data into numeric to feed into a classification model. An example dataset with one modification column would be:

input:

data = [['tom', 10], ['nick', 15], ['juli', 14], ['nick', '12']]
data = pd.DataFrame(data, columns = ['Name', 'Age'])
data

output:

    Name    Age
0   tom     10
1   nick    15
2   juli    14
3   nick    12

I realize that scikit learn doesn't handle string data very well, but for now I'd really prefer to press onward with it, if possible (company restrictions). However, my issue is that if I use

sklearn.preprocessing.LabelEncoder

i am able to use '.classes_' to get some numeric values, such as:

input:

le = preprocessing.LabelEncoder()
le.fit(data['Name'])
le.classes_
vals = le.transform(le.classes_)
vals

I get

output:

array([0, 1, 2])

Since this array only contains three values, I cannot use

data['Name'] = vals

for assignment because my column length is 4 and my vals length is 3.

Considering this, is there an alternate way for me to go about this in scikit-learn or is my only option to use a different library?


问:
Randomizer picks a number from the vector and delete it
So, program picks this number from the vector, it's actually a sequence {1...n} and I want  to print out and delete random number from it. However, everytime program prints out {n...1} sequence.
Example: Vector(1,2,3,4,5) => program picks random number 4 => Vector(1,2,3,5) => random number 1 => Vector(2,3,5) and until Vector(). So, program will print (4,1,...).
In case of this program, it always prints out (5,4,3,2,1) for Vector(1,2,3,4,5).

```<code>int main()
{
    srand(time(NULL));
    rand();
    int toReturn;
    std::cout << "Enter the number of tickets: ";
    std::cin >> toReturn;
    std::cout << std::endl;
    std::vector<int> nums;

    for (int i = 1; i <= toReturn; ++i)
    {
        nums.push_back(i);
    }

    int choice=0;
    bool checked=0;
    while (nums.size() > 0)
    {
        bool inVector=0;
        choice = rand() % toReturn + 1;

        while(inVector == 0)
        {
            choice = rand() % toReturn + 1;

            for (int i = 0; i < nums.size(); ++i)
            {
                if (choice == nums[i])
                {
                    inVector = 1;
                }
                else
                {
                     inVector = 0;
                }
            }
        }
        std::cout << "Why not check the ticket " << choice << std::endl;
        std::cout << "Did u do it right?" << std::endl;
        std::cin >> checked;
        if (checked)
        {
            nums.erase(std::remove(nums.begin(), nums.end(), choice), nums.end());
        }

        else
        {
             continue;
        }
    }
    if (nums.size() == 0)
    {
        std::cout << "You checked all tickets!!!";
    }
    return 0;
}

</code>```

I would be glad if you leave any suggestion to code refactoring

Thanks everybody for help, completely rewrite my program with std::random_shuffle this way:

```<code>#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <random>
int main()
{

    int toReturn;
    std::cout << "Enter the number of tickets: ";
    std::cin >> toReturn;
    std::cout << std::endl;
    std::vector<int> nums;

    for (int i = 1; i <= toReturn; ++i)
    {
        nums.push_back(i);
    }
    std::random_device rd;
    std::mt19937 g(rd());
    int choice = 0;
    std::shuffle(nums.begin(), nums.end(), g);

    while (nums.size() > 0)
    {
        bool checked = 0;
        choice = 0;
        std::cout << "Why not to check " << nums[choice];
        std::cout << std::endl << "Did you do it right?";
        std::cin >> checked;
        if (checked == 1)
        {
            nums.erase(std::remove(nums.begin(), nums.end(), nums[choice]), nums.end());
        }
        choice++;
    }

    std::cout << "You checked all tickets!!!";
    return 0;
}
</code>```

答:
May be you should change this line

```<code>if (choice == nums[i])
</code>```

to this:

```<code>if (choice <= nums[i])
</code>```

Body:
So, program picks this number from the vector, it's actually a sequence {1...n} and I want  to print out and delete random number from it. However, everytime program prints out {n...1} sequence.
Example: Vector(1,2,3,4,5) => program picks random number 4 => Vector(1,2,3,5) => random number 1 => Vector(2,3,5) and until Vector(). So, program will print (4,1,...).
In case of this program, it always prints out (5,4,3,2,1) for Vector(1,2,3,4,5).

int main()
{
    srand(time(NULL));
    rand();
    int toReturn;
    std::cout << "Enter the number of tickets: ";
    std::cin >> toReturn;
    std::cout << std::endl;
    std::vector<int> nums;

    for (int i = 1; i <= toReturn; ++i)
    {
        nums.push_back(i);
    }

    int choice=0;
    bool checked=0;
    while (nums.size() > 0)
    {
        bool inVector=0;
        choice = rand() % toReturn + 1;

        while(inVector == 0)
        {
            choice = rand() % toReturn + 1;

            for (int i = 0; i < nums.size(); ++i)
            {
                if (choice == nums[i])
                {
                    inVector = 1;
                }
                else
                {
                     inVector = 0;
                }
            }
        }
        std::cout << "Why not check the ticket " << choice << std::endl;
        std::cout << "Did u do it right?" << std::endl;
        std::cin >> checked;
        if (checked)
        {
            nums.erase(std::remove(nums.begin(), nums.end(), choice), nums.end());
        }

        else
        {
             continue;
        }
    }
    if (nums.size() == 0)
    {
        std::cout << "You checked all tickets!!!";
    }
    return 0;
}

I would be glad if you leave any suggestion to code refactoring

Thanks everybody for help, completely rewrite my program with std::random_shuffle this way:

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <random>
int main()
{

    int toReturn;
    std::cout << "Enter the number of tickets: ";
    std::cin >> toReturn;
    std::cout << std::endl;
    std::vector<int> nums;

    for (int i = 1; i <= toReturn; ++i)
    {
        nums.push_back(i);
    }
    std::random_device rd;
    std::mt19937 g(rd());
    int choice = 0;
    std::shuffle(nums.begin(), nums.end(), g);

    while (nums.size() > 0)
    {
        bool checked = 0;
        choice = 0;
        std::cout << "Why not to check " << nums[choice];
        std::cout << std::endl << "Did you do it right?";
        std::cin >> checked;
        if (checked == 1)
        {
            nums.erase(std::remove(nums.begin(), nums.end(), nums[choice]), nums.end());
        }
        choice++;
    }

    std::cout << "You checked all tickets!!!";
    return 0;
}

Body:
May be you should change this line

if (choice == nums[i])

to this:

if (choice <= nums[i])


问:
React + Node + Firebase, how to deploy build folder?
I actually had a react app which was running after a build in my node backend folder and run perfectly.

Is it possible to do the same with firebase ?
I manage to run my build folder like this in my firebase.json :

```<code>   "public": "build",

"rewrites": [
  {
    "source": "**",
    "destination": "/index.html"
  }
]
</code>```

But this not contain my node app.
My node app is build approximately like this :

```<code>-myapp
   -/build
   -/route
      -mail.js
   -app.js
</code>```

and app.js contain :

```<code>app.use('/send', mail);
app.use(express.static('build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'))
</code>```

})

My node app is here to send email via nodemailer.

Any idea please ?

答:
You got 2 options

Deploy backend to a server (you can do that for free with Heroku/Netifly etc...), and use fetch at the front end to that endpoint to run the script, because at the same firebase domain both React app and node server are not live together

if you need backend just for sending emails, you might consider use https://www.npmjs.com/package/emailjs-com because they allow sending emails directly from front-end (also with a free limited usage..)

Body:
I actually had a react app which was running after a build in my node backend folder and run perfectly.

Is it possible to do the same with firebase ?
I manage to run my build folder like this in my firebase.json :

   "public": "build",

"rewrites": [
  {
    "source": "**",
    "destination": "/index.html"
  }
]

But this not contain my node app.
My node app is build approximately like this :

-myapp
   -/build
   -/route
      -mail.js
   -app.js

and app.js contain :

app.use('/send', mail);
app.use(express.static('build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'build', 'index.html'))

})

My node app is here to send email via nodemailer.

Any idea please ?


问:
Each time I press submit I want input text box change text
So basically I have a simple form and I want to change the input boxes text different every time you press submit by using PHP. I know my code doesn't work but I don't understand how to solve this problem. Maybe the array is not the best way to do this?</p>

```<code><body>
    <?php
        if(isset($_GET['submit'])) exit();
        $msg= ['One', 'Two', 'Three', '']
    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?php echo (isset($msg)) ? $viesti : ''; ?>">
    </form>
</body>
</code>```

答:
You could write something like this:</p>

```<code><?php
    session_start();

    $msgArray= array('One', 'Two', 'Three', '');
    // if $_SESSION['msgIndex'] is not set, we initialize it, or it will take 0 value every loading page
    if (!isset($_SESSION['msgIndex'])) { $_SESSION['msgIndex'] = 0;  }

    if (isset($_GET['submit'])) {
        getMessage();
    }

    // We save msgIndex in a $_SESSION variable cause even if the user reload the page, we keep the value
    function getMessage() {
        if ($_SESSION['msgIndex'] >= 0) {
            $_SESSION['msgIndex'] += 1;
        } if ($_SESSION['msgIndex'] > 3) {
            $_SESSION['msgIndex'] = 0;
        }
    }
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?= $msgArray[$_SESSION['msgIndex']] ?>">
</form>
</code>```

Body:
So basically I have a simple form and I want to change the input boxes text different every time you press submit by using PHP. I know my code doesn't work but I don't understand how to solve this problem. Maybe the array is not the best way to do this?

    <?php
        if(isset($_GET['submit'])) exit();
        $msg= ['One', 'Two', 'Three', '']
    ?>

    <form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?php echo (isset($msg)) ? $viesti : ''; ?>">
    </form>

Body:
You could write something like this:

<?php
    session_start();

    $msgArray= array('One', 'Two', 'Three', '');
    // if $_SESSION['msgIndex'] is not set, we initialize it, or it will take 0 value every loading page
    if (!isset($_SESSION['msgIndex'])) { $_SESSION['msgIndex'] = 0;  }

    if (isset($_GET['submit'])) {
        getMessage();
    }

    // We save msgIndex in a $_SESSION variable cause even if the user reload the page, we keep the value
    function getMessage() {
        if ($_SESSION['msgIndex'] >= 0) {
            $_SESSION['msgIndex'] += 1;
        } if ($_SESSION['msgIndex'] > 3) {
            $_SESSION['msgIndex'] = 0;
        }
    }
?>

<form action="<?php echo $_SERVER['PHP_SELF']?>">
    <input type="submit" name="submit" value="Paina nappi">
    <input type="text" name="msg" value="<?= $msgArray[$_SESSION['msgIndex']] ?>">
</form>


问:
Connecting to remote TFS 2010 instance gives TF30063 error
I connect to a remote TFS 2010 instance using Visual Studio 2010.  I can Get Latest for all files within a particular project except for one database backup file.  When I try to Get Latest on this file I get the following error:

TF30063: You are not authorized to access Microsoft-IIS/6.0

I've tried clearing my local VS client cache, but that doesn't help.  There are no entries in the Event Logs to give any clues as to what is going on.

Any help appreciated, or any ideas where I can find out more diagnostic information via would be appreciated.

Colin.

Update : Trace information shows the following, no real pointers

```<code>06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Completed download: id = 0 in 61866          ms, active = 1
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Web method response: [xxxxx.homeserver.com] Ver-Download: Napier.bak 61866 ms
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Recorded m_exception in UpDownAsyncResult.Completed(): Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at      Microsoft.TeamFoundation.VersionControl.Client.FileUploader.HandleErrorResponse(HttpWebResponse response)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Caught and converted to non-fatal error: Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream)  at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Converted to non-fatal: Microsoft.TeamFoundation.VersionControl.Client.VersionControlException: C:\code\Remote\Napier\Trunk\Database Backups\Napier.bak: TF30063: You are not authorized to access Microsoft-IIS/6.0. Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not   authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream) at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) DownloadFiles: 62061 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) Acknowledgements: 0 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115349 ms) CreateWebRequest() -- Uri: https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) request.AutomaticDecompression: GZip
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) Web method running: [https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx] QueryItemsExtended[VersionControl]
06/01/2011 15:45:09 (pid 5560, tid 2784, 115649 ms) HTTP headers:
Content-Length: 1247
Cache-Control: private, max-age=0
Content-Type: application/soap+xml; charset=utf-8
Date: Wed, 01 Jun 2011 14:43:27 GMT
Server: Microsoft-IIS/6.0
Via: 1.1 Clearswift SECURE Web Gateway
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
</code>```

答:
Ok, so I've fixed it.  I took the size of the database backup file down to 1.5Mb by removing obsolete data sets from it and it worked.

Not sure if it was a TFS problem or a work proxy problem - maybe a 25Mb file transfer limit imposed.  The latter seems more likely to me.

Body:
I connect to a remote TFS 2010 instance using Visual Studio 2010.  I can Get Latest for all files within a particular project except for one database backup file.  When I try to Get Latest on this file I get the following error:

TF30063: You are not authorized to access Microsoft-IIS/6.0

I've tried clearing my local VS client cache, but that doesn't help.  There are no entries in the Event Logs to give any clues as to what is going on.

Any help appreciated, or any ideas where I can find out more diagnostic information via would be appreciated.

Colin.

Update : Trace information shows the following, no real pointers

06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Completed download: id = 0 in 61866          ms, active = 1
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Web method response: [xxxxx.homeserver.com] Ver-Download: Napier.bak 61866 ms
06/01/2011 15:45:09 (pid 5560, tid 5216, 115007 ms) Recorded m_exception in UpDownAsyncResult.Completed(): Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at      Microsoft.TeamFoundation.VersionControl.Client.FileUploader.HandleErrorResponse(HttpWebResponse response)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Caught and converted to non-fatal error: Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream)  at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
06/01/2011 15:45:09 (pid 5560, tid 5216, 115008 ms) Converted to non-fatal: Microsoft.TeamFoundation.VersionControl.Client.VersionControlException: C:\code\Remote\Napier\Trunk\Database Backups\Napier.bak: TF30063: You are not authorized to access Microsoft-IIS/6.0. Microsoft.TeamFoundation.TeamFoundationServerUnauthorizedException: TF30063: You are not   authorized to access Microsoft-IIS/6.0. at Microsoft.TeamFoundation.VersionControl.Client.Client.EndDownloadFile(IAsyncResult asyncResult, Stream& downloadStream) at Microsoft.TeamFoundation.VersionControl.Client.AsyncGetFileState.Completed(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) DownloadFiles: 62061 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115193 ms) Acknowledgements: 0 ms
06/01/2011 15:45:09 (pid 5560, tid 2784, 115349 ms) CreateWebRequest() -- Uri: https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) request.AutomaticDecompression: GZip
06/01/2011 15:45:09 (pid 5560, tid 2784, 115355 ms) Web method running: [https://xxxxxx.homeserver.com/tfs/DefaultCollection/VersionControl/v1.0/repository.asmx] QueryItemsExtended[VersionControl]
06/01/2011 15:45:09 (pid 5560, tid 2784, 115649 ms) HTTP headers:
Content-Length: 1247
Cache-Control: private, max-age=0
Content-Type: application/soap+xml; charset=utf-8
Date: Wed, 01 Jun 2011 14:43:27 GMT
Server: Microsoft-IIS/6.0
Via: 1.1 Clearswift SECURE Web Gateway
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET


问:
How are JavaScript expression evaluated?
In JavaScript, can someone explain the results of the 2 following expressions:

"4" + 4 and  4 + "4"

Thanks!

答:
Expressions in JS work on two prime principles.

B O D M  A(includes concat) S

Left to right order of execution

However, its not straight forward

for + operator

as far as it encounters numbers it will do math addition using left to right execution, However,as soon as it encounters a string, it concatenates the result (that's calculated till encountering a string) with rest of the expression.

//left to right execution
console.log(10+10+"10") //2010, (10+10) of numtype + "10" of stringtype concat(20+"10")

console.log(10+10+"10"+10+10) //20101010,
//(10+10) of number  type + "10" stringtype(now since a string is enc.) + (10+10) of number type would act as strings and get concatenated = 20+"10"+"1010"

console.log("10"+[10,10,10]+10) //1010,10,1010
//"10"of stringtype + array of numtypes + 10 of numtype
// "10" concats with first element of array, last number 10 concats with last element of array.```
</div>
</div>
</p>
<h1>for all other operators such as -,*,/,^...</h1>
<p>if all occurrences are numbers/numbers as string, it will do the respective math operation treating "numbers as string" to be numbers.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log("10"-10) //0
console.log("10"/10) //1
console.log("10"*10) //100
console.log(10+"10"*10) //110 //BODMAS
console.log(Math.pow(10,"10")) //10000000000</code>```

if there are occurrences of non-numeric strings,arrays,objects in the middle of expression that involve (-,*,/,^...)math operations, it will always return NaN

console.log(10-{id:1,name:"hey"}-10) //NaN
console.log(10-10-"hey"-10-10-10) //NaN
console.log("hey"/10) //NaN
console.log("hey"* 3) //NaN
console.log(["hey","hey"]*"3") //NaN
console.log("10"/[10,10,10]/10) //NaN```

Body:
Expressions in JS work on two prime principles.

B O D M  A(includes concat) S

Left to right order of execution

However, its not straight forward

for + operator

as far as it encounters numbers it will do math addition using left to right execution, However,as soon as it encounters a string, it concatenates the result (that's calculated till encountering a string) with rest of the expression.

//left to right execution
console.log(10+10+"10") //2010, (10+10) of numtype + "10" of stringtype concat(20+"10")

console.log(10+10+"10"+10+10) //20101010,
//(10+10) of number  type + "10" stringtype(now since a string is enc.) + (10+10) of number type would act as strings and get concatenated = 20+"10"+"1010"

console.log("10"+[10,10,10]+10) //1010,10,1010
//"10"of stringtype + array of numtypes + 10 of numtype
// "10" concats with first element of array, last number 10 concats with last element of array.

for all other operators such as -,*,/,^...

if all occurrences are numbers/numbers as string, it will do the respective math operation treating "numbers as string" to be numbers.

console.log("10"-10) //0
console.log("10"/10) //1
console.log("10"*10) //100
console.log(10+"10"*10) //110 //BODMAS
console.log(Math.pow(10,"10")) //10000000000

if there are occurrences of non-numeric strings,arrays,objects in the middle of expression that involve (-,*,/,^...)math operations, it will always return NaN

console.log(10-{id:1,name:"hey"}-10) //NaN
console.log(10-10-"hey"-10-10-10) //NaN
console.log("hey"/10) //NaN
console.log("hey"* 3) //NaN
console.log(["hey","hey"]*"3") //NaN
console.log("10"/[10,10,10]/10) //NaN


问:
PowerPC and the clrlslwi -or- rlwinm instruction
I've read the other posts here, but still have a question about PPC and rlwinm.

The example I'm looking at is:

```<code>li  r0, 0x100
clrlslwi  r9, r0, 27,5 (which afaik is the same as rlwinm r9, r0,5,22,26)
</code>```

First I load r0 = 0x100
Then Left Shift r0 by 5 so r0 = 0x2000  (No overflow, so no rotate needed)

Make a Mask with bits 22 to 26 set = 0x3e0

AND r0 with the Mask = 0x2000 AND 0x3E0 = 0

I must be doing something wrong...this would always net 0
What am I missing?

答:
yes that's true (Clear left and shift left word immediate)

clrlslwi rA,rS,b,n (n ≤ b ≤ 31) = rlwinm rA,rS,n,b – n,31 – n

so
clrlslwi  r9, r0, 27,5 = rlwinm r9, r0, 5, 22(27-5), 26(31-5)

Body:
I've read the other posts here, but still have a question about PPC and rlwinm.

The example I'm looking at is:

li  r0, 0x100
clrlslwi  r9, r0, 27,5 (which afaik is the same as rlwinm r9, r0,5,22,26)

First I load r0 = 0x100
Then Left Shift r0 by 5 so r0 = 0x2000  (No overflow, so no rotate needed)

Make a Mask with bits 22 to 26 set = 0x3e0

AND r0 with the Mask = 0x2000 AND 0x3E0 = 0

I must be doing something wrong...this would always net 0
What am I missing?


问:
google indexing text retrieved by ajax or javascript after page load
a couple of google questions:

1 - is there ANY chance that google will "see" text retrieved using ajax?

the user selects from a chain of select boxes and some text from the Db is displayed.

2 - if i change the page title using javascript, outside the HEAD area, will google index the modified title?

sorry if these are trivial  questions and thanx for any reply

have a nice day :-)

答:
What Google sees is what you see when you disable javascript on your browser. So the answer to both your questions is no.

The correct way to have all the data of your site indexed is to degrade gracefully inside  tags. For example, you could offer an interface to browse all the content of your database, using list and sublists of requests that point to proper result pages, that are well integrated in your site.

Warning note: your content must really be a noscript version of your site. If you create a special site, it becomes cloaking, which is forbidden.

Update: Since 2014, Google seems to support everything you can think of (including javascript and ajax).

Body:
What Google sees is what you see when you disable javascript on your browser. So the answer to both your questions is no.

The correct way to have all the data of your site indexed is to degrade gracefully inside <noscript> tags. For example, you could offer an interface to browse all the content of your database, using list and sublists of requests that point to proper result pages, that are well integrated in your site.

Warning note: your content must really be a noscript version of your site. If you create a special site, it becomes cloaking, which is forbidden.

Update: Since 2014, Google seems to support everything you can think of (including javascript and ajax).


问:
How to write a platform independent wrapper function in C++
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

```<code>void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}
</code>```

Calling WrapperSprintf function1:

```<code>char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}
</code>```

Calling WrapperSprintf function2:

```<code>void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath,"%ls", strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}
</code>```

答:
You can use vsnprintf and _vsnprintf instead of snprintf and _snprintf respectively inside WrapperSprintf. These functions uses variable argument list.

Reference:

http://www.cplusplus.com/reference/cstdio/vsnprintf/

https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/vsnprintf-vsnprintf-vsnprintf-l-vsnwprintf-vsnwprintf-l?view=vs-2019

Body:
I am using snprintf to send the output to the buffer. Using C++ 11 and for desktop application.

As of now I am doing it only for windows. But from now onwards it has to support for different platforms (Windows, Linux and Mac)

To support for multiple platforms, I am planning to write a wrapper function with #if tags.

but here the challenge I am facing is, when invoking WrapperSprintf from different places of the project the number of parameters are different.

How to write a common wrapper that can be used from different places with different no of parameters passed to WrapperSprintf function?

I tried the wrapper function like as shown below. Please help me how to proceed with this:

void WrapperSprintf( char buffer, const char *format, ... )
{
#if defined(_WIN32)
    _snprintf_s(buffer, sizeof(buffer), format,...);
#else
    snprintf(buffer, sizeof(buffer), format, ...);
#endif
}

Calling WrapperSprintf function1:

char m_systemTime[20];

char* CUPSManager ::getSystemTime()
{
    time_t rawtime;
    struct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );

    WrapperSprintf(m_systemTime,"%d-%d-%d :%d:%d:%d" , timeinfo ->tm_year +1900,
             timeinfo ->tm_mon +1,
             timeinfo->tm_mday,
             timeinfo->tm_hour,
             timeinfo->tm_min,
             timeinfo->tm_sec);
    return m_systemTime;
}

Calling WrapperSprintf function2:

void getDevicePath()
{
    wstring strDevPath;
    strDevPath = (LPCWSTR)cDevicePath;
    char cDevPath[2048];
    WrapperSprintf(cDevPath,"%ls", strDevPath.c_str());
    int nPathLength = strlen(cDevPath);
...
}


问:
next-i18next has bug Apostrophe is displayed as '
I am using next-i18next. I have a bug has bug Apostrophe is displayed as '
How I can fix it?

答: It was interpolation, specifically escapeValue: false.


问:
react-native react-native-vector-icons: How to use font awesome icons
In my react-native application I have added this library react-native-vector-icons to use icons. From the github page, FontAwesome is listed among the bundled icon sets. But I don't see how I can reference a fontawesome item in my  element. It seems that I can only use "ios-xxx", "md-xxx" or "log-xxx".

When I try something like:

<Icon name='fa-rss' style={{marginRight:10}} />
```

I get this warning:

Body:
In my react-native application I have added this library react-native-vector-icons to use icons. From the github page, FontAwesome is listed among the bundled icon sets. But I don't see how I can reference a fontawesome item in my  element. It seems that I can only use "ios-xxx", "md-xxx" or "log-xxx".

When I try something like:

<Icon name='fa-rss' style={{marginRight:10}} />

I get this warning:

Body:
Since there is a very large amount of them, and I don't want to import them all, I ended up importing each icon I need as an SVG.

Download font awesome free package https://fontawesome.com/download

add react-native-svg to your project

then paste it to your JSX file

import * as React from "react";

import { SvgXml, SvgProps } from 'react-native-svg'

const xml = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M470.1 231.3s7.6 37.2 9.3 45H446c3.3-8.9 16-43.5 16-43.5-.2.3 3.3-9.1 5.3-14.9l2.8 13.4zM576 80v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V80c0-26.5 21.5-48 48-48h480c26.5 0 48 21.5 48 48zM152.5 331.2L215.7 176h-42.5l-39.3 106-4.3-21.5-14-71.4c-2.3-9.9-9.4-12.7-18.2-13.1H32.7l-.7 3.1c15.8 4 29.9 9.8 42.2 17.1l35.8 135h42.5zm94.4.2L272.1 176h-40.2l-25.1 155.4h40.1zm139.9-50.8c.2-17.7-10.6-31.2-33.7-42.3-14.1-7.1-22.7-11.9-22.7-19.2.2-6.6 7.3-13.4 23.1-13.4 13.1-.3 22.7 2.8 29.9 5.9l3.6 1.7 5.5-33.6c-7.9-3.1-20.5-6.6-36-6.6-39.7 0-67.6 21.2-67.8 51.4-.3 22.3 20 34.7 35.2 42.2 15.5 7.6 20.8 12.6 20.8 19.3-.2 10.4-12.6 15.2-24.1 15.2-16 0-24.6-2.5-37.7-8.3l-5.3-2.5-5.6 34.9c9.4 4.3 26.8 8.1 44.8 8.3 42.2.1 69.7-20.8 70-53zM528 331.4L495.6 176h-31.1c-9.6 0-16.9 2.8-21 12.9l-59.7 142.5H426s6.9-19.2 8.4-23.3H486c1.2 5.5 4.8 23.3 4.8 23.3H528z"/></svg>`

export const VisaIcon = (props: SvgProps) => <SvgXml xml={xml} {...props} />

Don't forget to pass width, height and fill properties to your icon.


问:
Redirecting back doesn't work anymore
I'm having some truble redirecting my users to the previous page.

Here is an example of an update method in the movies controller.

```<code>def update
  @movie = Movie.find(params[:id])
  if @movie.update_attributes(params[:movie])
    flash[:notice] = "The given movie is now updated."
  end
  respond_with(@movie, location: :back)
end
</code>```

I'm getting this error.

undefined method 'hash_for_back_url' for #<Module:0x00000103eeaaa8> on the respond_with line.

I'm using Rails 3.1 rc1 with Ruby 1.9.

It works when doing something like this.

respond_with(@movie, location: request.referer)

Anyone knows why the :back argument won't work?

答:
In that case respond_with is expecting :location to be the result of a url helper method like in respond_with(@movie, :location => movie_url(@movie))

You probably should be using one of this methods instead:

redirect to an information page with redirect_to @movie, which is equivalent to redirect_to movie_path(@movie)

render the form again with the updated data with render :action => :edit (:edit represent the action used to display the form)

Title: Redirecting back doesn't work anymore

Body:
I'm having some truble redirecting my users to the previous page.

Here is an example of an update method in the movies controller.

def update
  @movie = Movie.find(params[:id])
  if @movie.update_attributes(params[:movie])
    flash[:notice] = "The given movie is now updated."
  end
  respond_with(@movie, location: :back)
end

I'm getting this error.

undefined method 'hash_for_back_url' for #<Module:0x00000103eeaaa8> on the respond_with line.

I'm using Rails 3.1 rc1 with Ruby 1.9.

It works when doing something like this.

respond_with(@movie, location: request.referer)

Anyone knows why the :back argument won't work?


问:
Kivy error (python 2.7) : sdl2 import error
I'm trying to use kivy on my Python 2.7 project (in a PyCharm - Windows 10 environment), but I get the following error.

If someone can help me ? Thanks !

PS : I tried many times uninstalling/reinstalling libraries etc and doing what suggested on posts like this one, but it doesn't work : Kivy not working (Error: Unable to find any valuable Window provider.)

```<code>[INFO   ] [Logger      ] Record log in C:\Users\cyril\.kivy\logs\kivy_18-03-25_0.txt
 C:\Users\cyril\venv\lib\site-packages\kivy\modules\__init__.py:128: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
   if path not in sys.path:
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Window      ] Unable to find any valuable Window provider.
sdl2 - ImportError: DLL load failed: Le module sp�cifi� est introuvable.
  File "C:\Users\cyril\venv\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\cyril\venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 26, in <module>
    from kivy.core.window._window_sdl2 import _WindowSDL2Storage

[CRITICAL] [App         ] Unable to get a Window, abort.

Process finished with exit code 1
</code>```

答: Checked everything, reinstalled etc. still no luck, but after using the -d (debug) option the errormessage expanded and suggested there might be another sdl2.dll in the path. After some trial and error I found one in windows\system32. Moving it out of the way made the error disappear.</p>

Body:
I'm trying to use kivy on my Python 2.7 project (in a PyCharm - Windows 10 environment), but I get the following error.

If someone can help me ? Thanks !

PS : I tried many times uninstalling/reinstalling libraries etc and doing what suggested on posts like this one, but it doesn't work : Kivy not working (Error: Unable to find any valuable Window provider.)

[INFO   ] [Logger      ] Record log in C:\Users\cyril\.kivy\logs\kivy_18-03-25_0.txt
 C:\Users\cyril\venv\lib\site-packages\kivy\modules\__init__.py:128: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
   if path not in sys.path:
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Window      ] Unable to find any valuable Window provider.
sdl2 - ImportError: DLL load failed: Le module sp�cifi� est introuvable.
  File "C:\Users\cyril\venv\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\cyril\venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 26, in <module>
    from kivy.core.window._window_sdl2 import _WindowSDL2Storage

[CRITICAL] [App         ] Unable to get a Window, abort.

Process finished with exit code 1


问:
Debug Tornado Web Server in Pycharm
Is there anyone who can debug the code run in Tornado Web Server in Pycharm?

I searched the question in google, but I can not found the answer.

答:
Here are the steps I used:

In your PyCharm project, create a new Python file called tornado_test.py and paste the contents of the hello world example on Tornado's docs.

Right click on the newly created file and select Debug 'tornado_test'

Create a breakpoint on line 13 ( self.write("Hello, world") ) using left-click next to the line number

Open a browser and go to http://127.0.0.1:8888/ (it should start waiting for a response)

Go back to PyCharm and your breakpoint should be activated (you can now debug the code, see variables such as request for example)

Screenshot (don't worry about the blurred parts - those are just other files I had in my project):

Of course you need to have Tornado installed in the (virtual) Python environment you use in PyCharm.

Title: Debug Tornado Web Server in Pycharm


问:
Julia: find maximum along columns in array
Suppose we have an array defined like this:

```<code>a=[1 2; 3 4; 5 5; 7 9; 1 2];
</code>```

In Matlab, we could find the maximum values by writing:

```<code> [x y] = max(a)
   x =
     7     9
</code>```

In Julia, we could use:

```<code>  a=[1 2; 3 4; 5 5; 7 9; 1 2]
  findmax(a,1)
</code>```

returning:

```<code> ([7 9],

  [4 9])
</code>```

However, I am interested not only in finding [7 9] for the two columns, but also their relative position within each column, like [4, 4]. Of course, I can write a bit more of coding lines, but can I do it directly with findmax?

答:
This is mentioned in the comments but I figured I'd do a response that's easy to see. I have version 1.0.3, so I don't know what's the earliest version that allows this. But now you can just do

```<code>julia> findmax(a) #Returns 2D index of overall maximum value
(9, CartesianIndex(4, 2))

julia> findmax(a[:,1]) #Returns 1D index of max value in column 1
(7, 4)

julia> findmax(a[:,2]) #Returns 1D index of max value in column 2
(9, 4)
</code>```

Hope this makes things easier.

Body:
Suppose we have an array defined like this:

a=[1 2; 3 4; 5 5; 7 9; 1 2];

In Matlab, we could find the maximum values by writing:

 [x y] = max(a)
   x =
     7     9

In Julia, we could use:

  a=[1 2; 3 4; 5 5; 7 9; 1 2]
  findmax(a,1)

returning:

 ([7 9],

  [4 9])

However, I am interested not only in finding [7 9] for the two columns, but also their relative position within each column, like [4, 4]. Of course, I can write a bit more of coding lines, but can I do it directly with findmax?

Body:
This is mentioned in the comments but I figured I'd do a response that's easy to see. I have version 1.0.3, so I don't know what's the earliest version that allows this. But now you can just do

julia> findmax(a) #Returns 2D index of overall maximum value
(9, CartesianIndex(4, 2))

julia> findmax(a[:,1]) #Returns 1D index of max value in column 1
(7, 4)

julia> findmax(a[:,2]) #Returns 1D index of max value in column 2
(9, 4)

Hope this makes things easier.


问:
Swift Firebase auto-Login not showing another ViewController
I want to set the root-VC to the Home-VC if Firebase got an loged-In User. The console says that the user was found but the VC is not changing.

Here is my code:

```<code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    //FirebaseConfigure
    FirebaseApp.configure()

    Auth.auth().addStateDidChangeListener { auth,user in
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if user != nil {
        print("User found")

        UserService.observeUserProfile(user!.uid) { userProfile in
        UserService.currentUserProfile = userProfile
        }

        let controller = storyboard.instantiateViewController(withIdentifier: "Home")
        self.window?.rootViewController = controller
        self.window?.makeKeyAndVisible()
    }else{
        print("User not found")
        UserService.currentUserProfile = nil
        let controller = storyboard.instantiateViewController(withIdentifier: "Out")
        self.window?.rootViewController = controller
        self.window?.makeKeyAndVisible()
               }
           }

    return true
}
</code>```

And here my Storyboard:

答:
To override rootViewController programmatically you need to first disable the main interface of the app which defaults to Main.storyboard file. Here is how you do it:

Delete these lines from the info.plist file (open as source code).

<key>UIMainStoryboardFile</key>
<string>Main</string>
```

<ol start="2">
<li>If your project is using <code>UISceneDelegate</code> then delete this one as well:</li>
</ol>

<pre class="lang-xml prettyprint-override"><code><key>UISceneStoryboardFile</key>
<string>Main</string>
</code>```

Body:
I want to set the root-VC to the Home-VC if Firebase got an loged-In User. The console says that the user was found but the VC is not changing.

Here is my code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    //FirebaseConfigure
    FirebaseApp.configure()

    Auth.auth().addStateDidChangeListener { auth,user in
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    if user != nil {
        print("User found")

        UserService.observeUserProfile(user!.uid) { userProfile in
        UserService.currentUserProfile = userProfile
        }

        let controller = storyboard.instantiateViewController(withIdentifier: "Home")
        self.window?.rootViewController = controller
        self.window?.makeKeyAndVisible()
    }else{
        print("User not found")
        UserService.currentUserProfile = nil
        let controller = storyboard.instantiateViewController(withIdentifier: "Out")
        self.window?.rootViewController = controller
        self.window?.makeKeyAndVisible()
               }
           }

    return true
}

And here my Storyboard:

Body:
To override rootViewController programmatically you need to first disable the main interface of the app which defaults to Main.storyboard file. Here is how you do it:

Delete these lines from the info.plist file (open as source code).

<key>UIMainStoryboardFile</key>
<string>Main</string>

If your project is using UISceneDelegate then delete this one as well:

<key>UISceneStoryboardFile</key>
<string>Main</string>


问:
Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1"
I am trying to use heatmaps for Xception model (with modified top layer):

import tensorflow as to
import cv2
import numpy as np
label = 1
IMAGE_PATH = '/home/piyush/Desktop/HV/hv_2/deep-viz-keras/images/doberman.png'

img = tf.keras.preprocessing.image.load_img(IMAGE_PATH, target_size=(299, 299))
img = tf.keras.preprocessing.image.img_to_array(img)

model_path = '/home/piyush/Desktop/temp/model.h5'
model = tf.keras.models.load_model(model_path)
inputs = tf.keras.Input(shape=(299,299,3))
#print(model.summary())
#print([layer.shape for layer in model.get_layer('xception').layers])
final = tf.keras.Model(inputs=model.inputs, outputs=model.output)
print(model.inputs)
#extractor = tf.keras.Model(inputs=inputs, outputs=[layer.output for layer in model.layers])
conv_layer = tf.keras.Model(inputs=inputs,outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)
```

<p>If I run this, I got the following error:</p>

```        conv_layer = tf.keras.Model(inputs=inputs, outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []
```

答:
SOLVED :

conv_layer = tf.keras.Model(inputs= model.get_layer('xception').inputs,outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

The reason that the model is disconnected so the input and output should be of same model.

Body:
I am trying to use heatmaps for Xception model (with modified top layer):

import tensorflow as to
import cv2
import numpy as np
label = 1
IMAGE_PATH = '/home/piyush/Desktop/HV/hv_2/deep-viz-keras/images/doberman.png'

img = tf.keras.preprocessing.image.load_img(IMAGE_PATH, target_size=(299, 299))
img = tf.keras.preprocessing.image.img_to_array(img)

model_path = '/home/piyush/Desktop/temp/model.h5'
model = tf.keras.models.load_model(model_path)
inputs = tf.keras.Input(shape=(299,299,3))
#print(model.summary())
#print([layer.shape for layer in model.get_layer('xception').layers])
final = tf.keras.Model(inputs=model.inputs, outputs=model.output)
print(model.inputs)
#extractor = tf.keras.Model(inputs=inputs, outputs=[layer.output for layer in model.layers])
conv_layer = tf.keras.Model(inputs=inputs,outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

If I run this, I got the following error:

        conv_layer = tf.keras.Model(inputs=inputs, outputs=model.get_layer('xception').get_layer('block14_sepconv2_act').output)

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 299, 299, 3), dtype=float32) at layer "input_1". The following previous layers were accessed without issue: []