问:
pygame.init() fails when run with systemd
I'm trying to run a python pygame script with systemd and for some reason the script just exits without an error.
This is on a Raspberry Pi with Raspian "Jessie lite".

If I run the script manually with "sudo python myscript.py" it works fine.

sudo systemctl status myscript.service reports:

```<code>* myscript.service - Python Script
Loaded: loaded    /etc/systemd/system/myscript.service; enabled)    Active: inactive (dead) since Mon 2016-08-29 04:33:19 UTC; 1s ago
Process: 3275> ExecStart=/usr/bin/python /home/pi/myscript.py (code=killed, signal=HUP)
Main PID: 3275 (code=killed, signal=HUP)
</code>```

If I start the service manually with sudo systemctl start myscript.service the same thing happens.

I've stripped down my script to just the pygame.init() call. This is where it exits.

If I try to initialize the modules manually then "cdrom", "joystick", "threads", and "font" initialize normally but a call to display.init() causes the program to exit. There is no exception raised.

The only resource I could find online is this guy. It seems he ran into the exact same thing I'm seeing.
I've tried strace and if I wait long enough (2 minutes), it will work!
Obviously I can't run with strace all the time. I think it slows down the execution of the initialization to somehow allow it to work.

EDIT:
So the issue appears to be systemd sending a SIGHUP. If this is unhandled in Python the default action is to exit. A quick fix is the catch SIGHUP:

```<code>import signal
def handler(signum, frame):
    pass

try:
    signal.signal(signal.SIGHUP, handler)
except AttributeError:
    # Windows compatibility
    pass
</code>```

So many burning questions. Why does systemd do this? Why does strace fix the issue? Why do some Python scripts get SIGHUP while others don't?

答:
I don't have an answer, but I'm experiencing the same thing, so I'll add some more detail.

Here's the cut-down code:

```<code>#!/usr/bin/python2.7

import logging
from pygame import display
import signal
import time

def handler(signum, frame):
  """Why is systemd sending sighups? I DON'T KNOW."""
  logging.warning("Got a {} signal. Doing nothing".format(signum))

signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGTERM, handler)
signal.signal(signal.SIGCONT, handler)

logging.warning("About to start display.")
try:
  display.init()   # hups
except Exception as ex:
  logging.warning("Got any exception: %s " % ex)

logging.warning("Quitting in 60")
time.sleep(60)
</code>```

Here's the log that produces:

```<code>Jul  8 22:30:27 beardog systemd[1]: Started PyGame Test.
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:About to start display.
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:Got a 1 signal. Doing nothing
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:Got a 18 signal. Doing nothing
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:Quitting in 60
</code>```

It's getting a SIGCONT immediately after the SIGHUP, but no SIGTERM. Systemd claims to only ever send a SIGHUP after a SIGTERM, so maybe it's coming from somewhere else? I can't find anything relevant in the pygame code though.

I've turned on systemd debug logging, but it doesn't print anything interesting.

Here's my systemd config.

```<code>[Unit]
Description=PyGame Test
After=syslog.target network.target network-online.target graphical.target

[Service]
Type=simple
WorkingDirectory=/path/to/code/pygame/
ExecStart=/path/to/code/pygame/why.py
Restart=always
RestartSec=5
LimitNOFILE=10000
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=pygame
SendSIGHUP=no

[Install]
WantedBy=multi-user.target
</code>```

I've tried this as Type=forking, oneshot and dbus (although it isn't any of them). I've also tried TimeoutStartSec=20, but no change. Tested on an Ubuntu Xenial laptop and on a Raspberry pi running Raspbian. Both python2.7 and python3. Code works fine when run manually, and seems to work when run under strace in systemd. /o\

Like the OP, I can work around it by catching the SIGHUP, but after this much debugging I'd love to know what's going on.

Body:
I'm trying to run a python pygame script with systemd and for some reason the script just exits without an error.
This is on a Raspberry Pi with Raspian "Jessie lite".

If I run the script manually with "sudo python myscript.py" it works fine.

sudo systemctl status myscript.service reports:

* myscript.service - Python Script
Loaded: loaded    /etc/systemd/system/myscript.service; enabled)    Active: inactive (dead) since Mon 2016-08-29 04:33:19 UTC; 1s ago
Process: 3275> ExecStart=/usr/bin/python /home/pi/myscript.py (code=killed, signal=HUP)
Main PID: 3275 (code=killed, signal=HUP)

If I start the service manually with sudo systemctl start myscript.service the same thing happens.

I've stripped down my script to just the pygame.init() call. This is where it exits.

If I try to initialize the modules manually then "cdrom", "joystick", "threads", and "font" initialize normally but a call to display.init() causes the program to exit. There is no exception raised.

The only resource I could find online is this guy. It seems he ran into the exact same thing I'm seeing.
I've tried strace and if I wait long enough (2 minutes), it will work!
Obviously I can't run with strace all the time. I think it slows down the execution of the initialization to somehow allow it to work.

EDIT:
So the issue appears to be systemd sending a SIGHUP. If this is unhandled in Python the default action is to exit. A quick fix is the catch SIGHUP:

import signal
def handler(signum, frame):
    pass

try:
    signal.signal(signal.SIGHUP, handler)
except AttributeError:
    # Windows compatibility
    pass

So many burning questions. Why does systemd do this? Why does strace fix the issue? Why do some Python scripts get SIGHUP while others don't?

Body:
I don't have an answer, but I'm experiencing the same thing, so I'll add some more detail.

Here's the cut-down code:

#!/usr/bin/python2.7

import logging
from pygame import display
import signal
import time

def handler(signum, frame):
  """Why is systemd sending sighups? I DON'T KNOW."""
  logging.warning("Got a {} signal. Doing nothing".format(signum))

signal.signal(signal.SIGHUP, handler)
signal.signal(signal.SIGTERM, handler)
signal.signal(signal.SIGCONT, handler)

logging.warning("About to start display.")
try:
  display.init()   # hups
except Exception as ex:
  logging.warning("Got any exception: %s " % ex)

logging.warning("Quitting in 60")
time.sleep(60)

Here's the log that produces:

Jul  8 22:30:27 beardog systemd[1]: Started PyGame Test.
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:About to start display.
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:Got a 1 signal. Doing nothing
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:Got a 18 signal. Doing nothing
Jul  8 22:30:27 beardog pygame[17406]: WARNING:root:Quitting in 60

It's getting a SIGCONT immediately after the SIGHUP, but no SIGTERM. Systemd claims to only ever send a SIGHUP after a SIGTERM, so maybe it's coming from somewhere else? I can't find anything relevant in the pygame code though.

I've turned on systemd debug logging, but it doesn't print anything interesting.

Here's my systemd config.

[Unit]
Description=PyGame Test
After=syslog.target network.target network-online.target graphical.target

[Service]
Type=simple
WorkingDirectory=/path/to/code/pygame/
ExecStart=/path/to/code/pygame/why.py
Restart=always
RestartSec=5
LimitNOFILE=10000
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=pygame
SendSIGHUP=no

[Install]
WantedBy=multi-user.target

I've tried this as Type=forking, oneshot and dbus (although it isn't any of them). I've also tried TimeoutStartSec=20, but no change. Tested on an Ubuntu Xenial laptop and on a Raspberry pi running Raspbian. Both python2.7 and python3. Code works fine when run manually, and seems to work when run under strace in systemd. /o\

Like the OP, I can work around it by catching the SIGHUP, but after this much debugging I'd love to know what's going on.


来源: stackexchange

问:
find dead JavaScript code?
We are refactoring a legacy web app and as a result are "killing" quite a lot of JavaScript code but we're afraid of deleting what we think is dead code due to not being sure.  Is there any tool / technique for positively identifying dead code in JavaScript?</p>

答:
If you want to automate this I'd take a look at https://github.com/joelgriffith/navalia, which exposes an automated API to do just that:

```<code>const { Chrome } = require('navalia');
const chrome = new Chrome();

chrome.goto('http://joelgriffith.net/', { coverage: true })
  .then(() => chrome.coverage('http://joelgriffith.net/main.bundle.js'))
  .then((stats) => console.log(stats)) // Prints { total: 45913, unused: 5572,
  percentUnused: 0.12135996340905626 }
  .then(() => chrome.done());
</code>```

More here: https://joelgriffith.github.io/navalia/Chrome/coverage/

ContentLicense: CC BY-SA 2.5

Title: find dead JavaScript code?

Body:
If you want to automate this I'd take a look at https://github.com/joelgriffith/navalia, which exposes an automated API to do just that:

const { Chrome } = require('navalia');
const chrome = new Chrome();

chrome.goto('http://joelgriffith.net/', { coverage: true })
  .then(() => chrome.coverage('http://joelgriffith.net/main.bundle.js'))
  .then((stats) => console.log(stats)) // Prints { total: 45913, unused: 5572,
  percentUnused: 0.12135996340905626 }
  .then(() => chrome.done());

More here: https://joelgriffith.github.io/navalia/Chrome/coverage/

ContentLicense: CC BY-SA 3.0


问:
CAP theorem: Can I have Consistency and Availability at same time
Wiki says: one is then left with two options: consistency or availability

Why I cannot get rid of Partition tolerance?

What Partition tolerance actually means?

答:
Read "Partition Tolerance" as "Network Partition Tolerance" and everything will start making sense.

For a distributed system to be reliable, it will always need a form of communication between nodes in different locations (network). You cannot get rid of Partition Tolerance (P) because network failure is inevitable.

This does not mean that you cannot aim to have Consistency (C) and Availability (A) for most of the time your system is running, but during a network failure you will need to sacrifice one of them in favor of the other.

See this post from CodaHale for a thorough explanation.


问:
Between NativeBase and Shoutem, which is best to use for React Native?
I find that there are 2 UI components for React Native which are mostly used. I want to use one of them. Which one of them is more easy to use and  customizable ?</p>

答:
I've played around with native-base and Shoutem UI. Both of them fully customized.
I like Shoutem than the other because it has more feature, animation, extension, builder, etc. But unfortunately, Shoutem UI currently doesn't support the latest react-native (>0.40) and expo(> 15.0). So I hold my plan to use this for production.

I think this is because the latest RN deprecated NavigationExperimental and
Expo SDK use react-native-svg >= 5.2.0. CMIIW


问:
C - should I use a variable array of function pointers
This question is about how to solve my problem on the level of how I design my program. For a school project, I'm building a shell, which has several built-in functions. One of these function's purpose (cmd_type) is to check to see if the argument provided is in that list of functions. Here is a partial implementation of it:

```<code>int cmd_type(int argc, char *argv[]) {
    if (argc == 2) {
        for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
            if (strcmp(cmds_name[i], argv[1]) == 0) {
                printf("%s is a shell builtin\n", argv[1]);
                return 0; // found it
            }
        }

        // still need to search path, call stat(path/cmd)
        errmsg("not implemented! type", 1);
    } else {
        err_msg("type", 1);
    }
}
</code>```

Defining manual if statements for every function my shell supports sounds like a bad choice because the list might expand over time, and I need to store the list of function names anyway. So originally, I planned to define an array of function names and an array of their pointers, like so:

```<code>char cmds_name[BUILTIN_FUNC_COUNT-1][16];
char (*cmds_ptr)(int,*char[])[BUILTIN_FUNC_COUNT-1];
// make list of built-in funcs
strcpy(cmds_name[0], "exit");
strcpy(cmds_name[1], "cd");
// make list of func pointers
cmds_ptr[0] = &cmd_exit;
cmds_ptr[1] = &cmd_cd;
</code>```

They're accessed like so:

```<code>// try builtin cmds
for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
    if (strcmp(cmds_name[i], argv[0]) == 0) {
        last_cmd_err = (*cmds_ptr[i])(argc, argv);
        continue; // we found it, so next loop
    }
}
</code>```

Then they'd each happily take (int argc, char *argv[]) as arguments. But the cmd_path() needs access to the list in addition to those arguments, so I'd have to define it as a global, or define a global pointer to it... In the process of researching this, I found this answer, saying a similar approach was really bad style: https://stackoverflow.com/a/41425477/5537652

So my questions are: Is this a good way to solve this problem, or should I just do if/else statements/is there a better way? Would you recommend a global pointer to the array of function names?

答:
I would not go with if-else statements. There is nothing wrong with solution (2) proposed in https://stackoverflow.com/a/41425477/5537652.

You could have a table with a string and a function to service an entry:

```<code>typedef struct cmd_desc
{
  char cmd[80];
  int builtin_cmd(int argc, char **argv, void *extra);
} CMD_DESC;

static CMD_DESC descTable[] =
{
  { "exit",                 cmd_exit      },
  { "cd",                   cmd_cd        },
  { "$ON_OPEN_CMD",         OnOpenCmd     },
  { "$OPEN_EXTRA_CMD",      OpenExtraCmd  },
  { "$AC",                  ActionCmd     },
  { "$AD",                  ActionDataCmd },
  { "$EC",                  ExtraCmd      },
  { "$TC",                  TextCmd       },
  { "",                     NULL          }
};

int cmd_exit (int argc, char **argv, void *extra)
{
  //...
}
</code>```

Access/execution:

```<code>for (int tokenIndex=0; strcmp(descTable[tokenIndex].cmd,""); tokenIndex++) //search table
{
    if ( strcmp( (descTable[tokenIndex]).cmd, argv[0] ) == 0 )
    {
        int ret = (*(descTable[tokenIndex]).builtin_cmd( argc, argv, extra);
    }
}
</code>```

I used the above approach in a my applications and it worked well for me.

The table can be easily expanded and the readability of the table is better than if/else chain.

Body:
This question is about how to solve my problem on the level of how I design my program. For a school project, I'm building a shell, which has several built-in functions. One of these function's purpose (cmd_type) is to check to see if the argument provided is in that list of functions. Here is a partial implementation of it:

int cmd_type(int argc, char *argv[]) {
    if (argc == 2) {
        for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
            if (strcmp(cmds_name[i], argv[1]) == 0) {
                printf("%s is a shell builtin\n", argv[1]);
                return 0; // found it
            }
        }

        // still need to search path, call stat(path/cmd)
        errmsg("not implemented! type", 1);
    } else {
        err_msg("type", 1);
    }
}

Defining manual if statements for every function my shell supports sounds like a bad choice because the list might expand over time, and I need to store the list of function names anyway. So originally, I planned to define an array of function names and an array of their pointers, like so:

char cmds_name[BUILTIN_FUNC_COUNT-1][16];
char (*cmds_ptr)(int,*char[])[BUILTIN_FUNC_COUNT-1];
// make list of built-in funcs
strcpy(cmds_name[0], "exit");
strcpy(cmds_name[1], "cd");
// make list of func pointers
cmds_ptr[0] = &cmd_exit;
cmds_ptr[1] = &cmd_cd;

They're accessed like so:

// try builtin cmds
for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
    if (strcmp(cmds_name[i], argv[0]) == 0) {
        last_cmd_err = (*cmds_ptr[i])(argc, argv);
        continue; // we found it, so next loop
    }
}

Then they'd each happily take (int argc, char *argv[]) as arguments. But the cmd_path() needs access to the list in addition to those arguments, so I'd have to define it as a global, or define a global pointer to it... In the process of researching this, I found this answer, saying a similar approach was really bad style: https://stackoverflow.com/a/41425477/5537652

So my questions are: Is this a good way to solve this problem, or should I just do if/else statements/is there a better way? Would you recommend a global pointer to the array of function names?

Body:
I would not go with if-else statements. There is nothing wrong with solution (2) proposed in https://stackoverflow.com/a/41425477/5537652.

You could have a table with a string and a function to service an entry:

typedef struct cmd_desc
{
  char cmd[80];
  int builtin_cmd(int argc, char **argv, void *extra);
} CMD_DESC;

static CMD_DESC descTable[] =
{
  { "exit",                 cmd_exit      },
  { "cd",                   cmd_cd        },
  { "$ON_OPEN_CMD",         OnOpenCmd     },
  { "$OPEN_EXTRA_CMD",      OpenExtraCmd  },
  { "$AC",                  ActionCmd     },
  { "$AD",                  ActionDataCmd },
  { "$EC",                  ExtraCmd      },
  { "$TC",                  TextCmd       },
  { "",                     NULL          }
};

int cmd_exit (int argc, char **argv, void *extra)
{
  //...
}

Access/execution:

for (int tokenIndex=0; strcmp(descTable[tokenIndex].cmd,""); tokenIndex++) //search table
{
    if ( strcmp( (descTable[tokenIndex]).cmd, argv[0] ) == 0 )
    {
        int ret = (*(descTable[tokenIndex]).builtin_cmd( argc, argv, extra);
    }
}

I used the above approach in a my applications and it worked well for me.

The table can be easily expanded and the readability of the table is better than if/else chain.


问:
React use .push to add to an array with onClick
I am attempting to add to my existing array which is called players (which is an external file "players.js" that's imported into my parent).

I can write:

```<code> players.push({
  name: 'Maul',
  id: 26
});
</code>```

And that works as ID is used for the key and the name is updated in the array.

However if I write

```<code>   handleAddPlayer = () => {
    console.log('i am working');
    players.push({
      name: 'Maul',
      id: 26
    });
  };
</code>```

And on my button I have

```<code>    <div>
      <h4>Add A Player</h4>
      <input />
      <button onClick={this.handleAddPlayer}>Press to Add Player</button>
    </div>
</code>```

And my state is as follows:

```<code>  this.state = {
  id: players.id,
  totalScore: 0,
  countInfo: [],
  evilName: '',
  color: '#6E68C5',
  scoreColor: '#74D8FF',
  fontAwe: 'score-icon',
  incrementcolor: '',
  scoreNameColor: 'white',
  glow: '',
  buttonStyle: 'count-button-start',
  players,
};
</code>```

It does not work.

From here I have two questions:

why won't it update when I click the button but works before not as a function?

I would like to put a name into the input and generate a unique key that's added into my array, players.js

I've tried concatenate and had not a lot of success.

答:
Players is a property on the state object, so you'll want to call setState to update the property:</p>

```<code>handleAddPlayer = () => {
  // create a clone of your array of players; don't modify objects on the state directly
  const players = this.state.players.slice(0);

  players.push({
    name: 'Maul',
    id: 26
  });

  this.setState({
    players: players,
  });
};
</code>```

Body:
I am attempting to add to my existing array which is called players (which is an external file "players.js" that's imported into my parent).

I can write:

 players.push({
  name: 'Maul',
  id: 26
});

And that works as ID is used for the key and the name is updated in the array.

However if I write

   handleAddPlayer = () => {
    console.log('i am working');
    players.push({
      name: 'Maul',
      id: 26
    });
  };

And on my button I have

Add A Player

      <input />
      <button onClick={this.handleAddPlayer}>Press to Add Player</button>

And my state is as follows:

  this.state = {
  id: players.id,
  totalScore: 0,
  countInfo: [],
  evilName: '',
  color: '#6E68C5',
  scoreColor: '#74D8FF',
  fontAwe: 'score-icon',
  incrementcolor: '',
  scoreNameColor: 'white',
  glow: '',
  buttonStyle: 'count-button-start',
  players,
};

It does not work.

From here I have two questions:

why won't it update when I click the button but works before not as a function?

I would like to put a name into the input and generate a unique key that's added into my array, players.js

I've tried concatenate and had not a lot of success.

Body:
Players is a property on the state object, so you'll want to call setState to update the property:

handleAddPlayer = () => {
  // create a clone of your array of players; don't modify objects on the state directly
  const players = this.state.players.slice(0);

  players.push({
    name: 'Maul',
    id: 26
  });

  this.setState({
    players: players,
  });
};


问:
Overwriting a block within an `include`d template from an extended template
I have the following:

base.html

```<code><html>
    {% include 'header.html' %}
    <div>
    {% block content %}Default Content{% endblock %}
    </div>
</html>
</code>```

header.html

```<code><header>
     {% block logo %}Logo 1{% endblock %}
</header>
</code>```

homepage.html

```<code>{% extend 'base.html' %}
{% block logo %}Logo 2{% endblock %}
{% block content %}Yap Yap Yap{% endblock %}
</code>```

Essentially, this doesn't work. When I render the homepage.html I get:

```<code><html>
    <header>Logo 1</header>
    <div>Yap Yap Yap</div>
</html>
</code>```

but If I move the code in header.html into base.html (i.e. get rid of the include altogether) it works ok. Can anyone explain why this is the case?

I have a feeling it has something to do with the included templates getting rendered after their parents have been rendered?

答:
I had a similar problem.  I have a filtered table template which is of form

```<code>{% extends 'base.html' %}
{% include 'filtered_table.html' %}
</code>```

where filtered_table.html is:

```<code>{% load render_table from django_tables2 %}
<div class="panel-body" >
  <form method='GET'>
  <div class="search-form" style="border: 1px solid #000000; background-color:#a3ffaf; overflow: auto;">
{% block render_form %}
    {% for field in filter.form %}
         {{ field.errors }}
         {{ field.label_tag }} {{ field }}
    {% endfor %}
{% endblock %}
    <input type='submit' value='Filter' />
    |
    Displaying {{ filter.qs.count }} of {{ filter.queryset.count }} {{ object_name }}s.
    |
    <a href='{{ request.path }}' >Clear</a> <p>
  </div>

{% if table %}
    {% render_table table %}
{% endif %}

</form>

</div>
</code>```

I may want to specially hand-craft the form, for example by spelling out each field like this:

```<code>{% block render_form %}
{{ filter.form.field1.errors }}
{{ filter.form.field1.label_tag }}
{{ filter.form.field1 }}
<p>

{{ filter.form.field2.errors }}
{{ filter.form.field2.label_tag }}
{{ filter.form.field2 }}
{% endblock %}
</code>```

Unfortunately, because I can't do "extends" twice, I can't get my base layout and customize the filtered table.  So the ugly (because breaks HTML structure in half) way to do this is to simply define  begin_filtered_table.html and end_filtered_table.html.  Then in the customized case I have two includes wrapping the customization, and for the uncustomized case, filtered_form.html is defined like this:

```<code>{% include "begin_filtered_table.html" %}

    {% for field in filter.form %}
         {{ field.errors }}
         {{ field.label_tag }} {{ field }}
    {% endfor %}

{% include "end_filtered_table.html" %}
</code>```

This solves the problem at the expense of being gross.  It would be much easier just to allow multiple extends.

Body:
I have the following:

base.html

    {% include 'header.html' %}

    {% block content %}Default Content{% endblock %}

header.html

     {% block logo %}Logo 1{% endblock %}

homepage.html

{% extend 'base.html' %}
{% block logo %}Logo 2{% endblock %}
{% block content %}Yap Yap Yap{% endblock %}

Essentially, this doesn't work. When I render the homepage.html I get:

    Logo 1

Yap Yap Yap

but If I move the code in header.html into base.html (i.e. get rid of the include altogether) it works ok. Can anyone explain why this is the case?

I have a feeling it has something to do with the included templates getting rendered after their parents have been rendered?

Body:
I had a similar problem.  I have a filtered table template which is of form

{% extends 'base.html' %}
{% include 'filtered_table.html' %}

where filtered_table.html is:

{% load render_table from django_tables2 %}
<div class="panel-body" >
  <form method='GET'>
  <div class="search-form" style="border: 1px solid #000000; background-color:#a3ffaf; overflow: auto;">
{% block render_form %}
    {% for field in filter.form %}
         {{ field.errors }}
         {{ field.label_tag }} {{ field }}
    {% endfor %}
{% endblock %}
    <input type='submit' value='Filter' />
    |
    Displaying {{ filter.qs.count }} of {{ filter.queryset.count }} {{ object_name }}s.
    |
    <a href='{{ request.path }}' >Clear</a> <p>
  </div>

{% if table %}
    {% render_table table %}
{% endif %}

</form>

</div>

I may want to specially hand-craft the form, for example by spelling out each field like this:

{% block render_form %}
{{ filter.form.field1.errors }}
{{ filter.form.field1.label_tag }}
{{ filter.form.field1 }}
<p>

{{ filter.form.field2.errors }}
{{ filter.form.field2.label_tag }}
{{ filter.form.field2 }}
{% endblock %}

Unfortunately, because I can't do "extends" twice, I can't get my base layout and customize the filtered table.  So the ugly (because breaks HTML structure in half) way to do this is to simply define  begin_filtered_table.html and end_filtered_table.html.  Then in the customized case I have two includes wrapping the customization, and for the uncustomized case, filtered_form.html is defined like this:

{% include "begin_filtered_table.html" %}

    {% for field in filter.form %}
         {{ field.errors }}
         {{ field.label_tag }} {{ field }}
    {% endfor %}

{% include "end_filtered_table.html" %}

This solves the problem at the expense of being gross.  It would be much easier just to allow multiple extends.


问:
How can I put a database under git (version control)?
I'm doing a web app, and I need to make a branch for some major changes, the thing is, these changes require changes to the database schema, so I'd like to put the entire database under git as well.

How do I do that? is there a specific folder that I can keep under a git repository? How do I know which one? How can I be sure that I'm putting the right folder?

I need to be sure, because these changes are not backward compatible; I can't afford to screw up.

The database in my case is PostgreSQL

Edit:

Someone suggested taking backups and putting the backup file under version control instead of the database. To be honest, I find that really hard to swallow.

There has to be a better way.

Update:

OK, so there' no better way, but I'm still not quite convinced, so I will change the question a bit:

I'd like to put the entire database under version control, what database engine can I use so that I can put the actual database under version control instead of its dump?

Would sqlite be git-friendly?

Since this is only the development environment, I can choose whatever database I want.

Edit2:

What I really want is not to track my development history, but to be able to switch from my "new radical changes" branch to the "current stable branch" and be able for instance to fix some bugs/issues, etc, with the current stable branch. Such that when I switch branches, the database auto-magically becomes compatible with the branch I'm currently on.
I don't really care much about the actual data.

答:
I've released a tool for sqlite that does what you're asking for. It uses a custom diff driver leveraging the sqlite projects tool 'sqldiff', UUIDs as primary keys, and leaves off the sqlite rowid. It is still in alpha so feedback is appreciated.

Postgres and mysql are trickier, as the binary data is kept in multiple files and may not even be valid if you were able to snapshot it.

https://github.com/cannadayr/git-sqlite


问:
Angular 2+ formgroup setValue in child component form from parent
I have a form component that I want to share between an add member component and an edit member component.  Everything works fine if I put the form code in each component but, well, I don't want to be banned from coding forever because my code isn't DRY.  I'm new at coding.

The problem to be solved is this message in my IDE, Webstorm:

Property 'setValue' does not exist on type 'AddEditFormComponent'.

This message comes from the parent component EditMemberComponent.  First I'll present the form code that I'm trying to share between the edit and add components.

This is the child component, the basic form:

add-edit-form.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
selector: 'app-add-edit-form',
templateUrl: './add-edit-form.component.html'
})

export class AddEditFormComponent implements OnInit {

  addEditMemberForm: FormGroup;

  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.addEditMemberForm = this.fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      mainSkillTitle: ['', Validators.required],
      mainSkills: ['', Validators.required],
      otherSkills: ['', Validators.required],
      links: ['', Validators.required],
      country: ['', Validators.required]
    });
  }
}
</code>```

With a little Angular Material 2 styling the form looks good.

This is the problem parent component:

edit-member.component.ts

```<code>import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { MembersAdminService } from './member-admin.service';
import { Member } from './member-admin.model';
import { AddEditFormComponent } from './add-edit-form.component';

@Component({
  selector: 'app-edit-member',
  templateUrl: './edit-member.component.html'
})

export class EditMemberComponent implements OnInit {

  private memberId: string;
  private memberData;
  private addEditMemberForm: AddEditFormComponent;

  constructor(
      private membersAdminService: MembersAdminService,
      private successService: SuccessService,
      private route: ActivatedRoute,
      private router: Router
  ) {}

  ngOnInit() {
    this.fetchMember();
  }

  fetchMember() {
    this.route.params.forEach((urlParameters) => {
      this.memberId = urlParameters['id'];
      console.log(this.memberId); // Perfect
    });

    // Display the data retrieved from the data model to the form model.
   this.membersAdminService.getMemberById(this.memberId)
      .subscribe(dataLastEmittedFromObserver => {
          this.memberData = dataLastEmittedFromObserver;
          console.log(this.memberData);  // This works fine.  Now to post to form...

          this.addEditMemberForm.setValue({ // HERE IS THE PROBLEM
            firstName: this.memberData.firstName,
            lastName: this.memberData.lastName,
            mainSkillTitle: this.memberData.mainSkillTitle,
            mainSkills: this.memberData.mainSkills,
            otherSkills: this.memberData.otherSkills,
            links: this.memberData.links,
            country: this.memberData.country
          })
      });
   }

}
</code>```

I expected this line to bring all the form code into the parent:

```<code>private addEditMemberForm: AddEditFormComponent;
</code>```

Along with this import I expected .setValue to be available in the parent to the addEditMemberForm property. I expected setValue to populate the child form with the member data so I can edit it.  That isn't happening and I suspect I have an incomplete mental map of how this works.

Help is appreciated of course!

答:
To get hold of AddEditFormComponent i would use @ViewChild

```<code>import { ViewChild } from '@angular/core';

...
@ViewChild(AddEditFormComponent)
private addEditMemberComponent: AddEditFormComponent;
</code>```

and then we can write

```<code>this.addEditMemberComponent.addEditMemberForm.setValue({ // THIS SHOULD WORK
  ...
</code>```

Body:
I have a form component that I want to share between an add member component and an edit member component.  Everything works fine if I put the form code in each component but, well, I don't want to be banned from coding forever because my code isn't DRY.  I'm new at coding.

The problem to be solved is this message in my IDE, Webstorm:

Property 'setValue' does not exist on type 'AddEditFormComponent'.

This message comes from the parent component EditMemberComponent.  First I'll present the form code that I'm trying to share between the edit and add components.

This is the child component, the basic form:

add-edit-form.component.ts

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';

@Component({
selector: 'app-add-edit-form',
templateUrl: './add-edit-form.component.html'
})

export class AddEditFormComponent implements OnInit {

  addEditMemberForm: FormGroup;

  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.addEditMemberForm = this.fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      mainSkillTitle: ['', Validators.required],
      mainSkills: ['', Validators.required],
      otherSkills: ['', Validators.required],
      links: ['', Validators.required],
      country: ['', Validators.required]
    });
  }
}

With a little Angular Material 2 styling the form looks good.

This is the problem parent component:

edit-member.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { MembersAdminService } from './member-admin.service';
import { Member } from './member-admin.model';
import { AddEditFormComponent } from './add-edit-form.component';

@Component({
  selector: 'app-edit-member',
  templateUrl: './edit-member.component.html'
})

export class EditMemberComponent implements OnInit {

  private memberId: string;
  private memberData;
  private addEditMemberForm: AddEditFormComponent;

  constructor(
      private membersAdminService: MembersAdminService,
      private successService: SuccessService,
      private route: ActivatedRoute,
      private router: Router
  ) {}

  ngOnInit() {
    this.fetchMember();
  }

  fetchMember() {
    this.route.params.forEach((urlParameters) => {
      this.memberId = urlParameters['id'];
      console.log(this.memberId); // Perfect
    });

    // Display the data retrieved from the data model to the form model.
   this.membersAdminService.getMemberById(this.memberId)
      .subscribe(dataLastEmittedFromObserver => {
          this.memberData = dataLastEmittedFromObserver;
          console.log(this.memberData);  // This works fine.  Now to post to form...

          this.addEditMemberForm.setValue({ // HERE IS THE PROBLEM
            firstName: this.memberData.firstName,
            lastName: this.memberData.lastName,
            mainSkillTitle: this.memberData.mainSkillTitle,
            mainSkills: this.memberData.mainSkills,
            otherSkills: this.memberData.otherSkills,
            links: this.memberData.links,
            country: this.memberData.country
          })
      });
   }

}

I expected this line to bring all the form code into the parent:

private addEditMemberForm: AddEditFormComponent;

Along with this import I expected .setValue to be available in the parent to the addEditMemberForm property. I expected setValue to populate the child form with the member data so I can edit it.  That isn't happening and I suspect I have an incomplete mental map of how this works.

Help is appreciated of course!

Body:
To get hold of AddEditFormComponent i would use @ViewChild

import { ViewChild } from '@angular/core';

...
@ViewChild(AddEditFormComponent)
private addEditMemberComponent: AddEditFormComponent;

and then we can write

this.addEditMemberComponent.addEditMemberForm.setValue({ // THIS SHOULD WORK
  ...


问:
which javascript files are NOT being used on page load
Is it possible to find out which javascript files are NOT used on a web page without having to add console logs or debug or removing them to see if things break?

I'm looking for a tool, or a command line script or firefox plugin etc.

For example, let's say I have these included in the header:

```<code><script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/functions.js"></script>
<script type="text/javascript" src="js/validation.js"></script>
<script type="text/javascript" src="js/something.js"></script>
</code>```

On the page, calls are only made to functions in functions.js, validation.js and jquery.js. How can I know that something.js is not used and therefore can be safely removed from the header?

I've tried rooting through things like FireBug, chrome's console, yslow and server logs, but these all tell me which scripts have been loaded, i.e. all of them, not which ones have been used.

答:
Only took 7 years :) Also wanted to point out that you can automate this with Navalia: https://github.com/joelgriffith/navalia.

Here's a quick example:

```<code>import { Chrome } from 'navalia';
const chrome = new Chrome();

async function checkCoverage() {
  await chrome.goto('http://joelgriffith.net/', { coverage: true });
  const stats = await chrome.coverage('http://joelgriffith.net/main.bundle.js');
  console.log(stats); // Prints { total: 45913, unused: 5572, percentUnused: 0.12135996340905626 }
  chrome.done();
}

checkCoverage();
</code>```

More here https://joelgriffith.github.io/navalia/Chrome/coverage/.

Body:
Is it possible to find out which javascript files are NOT used on a web page without having to add console logs or debug or removing them to see if things break?

I'm looking for a tool, or a command line script or firefox plugin etc.

For example, let's say I have these included in the header:

On the page, calls are only made to functions in functions.js, validation.js and jquery.js. How can I know that something.js is not used and therefore can be safely removed from the header?

I've tried rooting through things like FireBug, chrome's console, yslow and server logs, but these all tell me which scripts have been loaded, i.e. all of them, not which ones have been used.

Body:
Only took 7 years :) Also wanted to point out that you can automate this with Navalia: https://github.com/joelgriffith/navalia.

Here's a quick example:

import { Chrome } from 'navalia';
const chrome = new Chrome();

async function checkCoverage() {
  await chrome.goto('http://joelgriffith.net/', { coverage: true });
  const stats = await chrome.coverage('http://joelgriffith.net/main.bundle.js');
  console.log(stats); // Prints { total: 45913, unused: 5572, percentUnused: 0.12135996340905626 }
  chrome.done();
}

checkCoverage();

More here https://joelgriffith.github.io/navalia/Chrome/coverage/.


问:
JQuery AJAX Lookup for searching
I have a text box on a web page and I wanted to write some JQuery, AJAX code so that when a user types some text into this field, it looks up values from a column in a database and beings back values that start with the letter(s) that they have typed.  As the user types more characters in text box the selection from the database gets smaller.  The user can then use one of the options to autocomplete their entry.  How do I achieve this and would there be performance considerations here?

Thanks,

Sachin

答:
There is also a really great tool that provides the lookup and provides access to other data elements as well.

https://github.com/nfosci/input-fetcher-dropdown

Title: JQuery AJAX Lookup for searching


问:
Changing the height works for two of my input fields but not the other ones. Why?
So i am trying to make a form field in which i require users to enter their name, email, a subject and a message. I am trying to write code through javascript where if the user hits the send button I have made and does not have any or some of the information not filled out, there will be a red border around that specific input field where they did not fill out the required information. To accomplish this, I made a class in CSS that is added onto those input fields through javascript that adds that red border and decreases the height of the input fields slightly so that the added height through adding the red border does not move the input fields out of place. Everything works fine except when I try to decrease the height of the input fields. The height will only decrease on the name and email fields but not on any of my other fields and it will consequently move the input fields out of place a little bit when the red border is added. I have tried a lot of things but I cannot figure out any solution. I will add my section of code that has this issue. Thanks in advance.

var validate_contact_field = function() {
  var name = document.getElementById("name_field");
  var email = document.getElementById("email_field");
  var subject = document.getElementById("contact_subject_field");
  var message = document.getElementById("contact_message_field");
  if (name.value === "" && email.value === "" && subject.value === "" &&
    message.value === "") {
    document.getElementById("valid").style.display = "none";
    document.getElementById("invalid").style.display = "inline-block";
    document.getElementById("invalid").style.color = "red";
    document.getElementById("invalid").innerHTML = "You did not enter any \
        contact information";
    name.className = name.className + " contact_error";
    email.className = email.className + " contact_error";
  }
}

var input_focus_name = function() {
  var name = document.getElementById("name_field");
  name.className = name.className.replace(" contact_error", "");
}

var input_focus_email = function() {
  var email = document.getElementById("email_field");
  email.className = email.className.replace(" contact_error", "");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  color: rgb(79, 87, 170);
}

input {
  text-indent: 5px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.5);
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  border: none;
}

input:focus {
  outline: none;
}

input::-webkit-input-placeholder {
  font-family: 'myFont', Arial, Helvetica, sans-serif;
  font-size: 15px;
  opacity: 0.5;
}

textarea {
  padding-left: 7px;
  padding-top: 5px;
  padding-right: 7px;
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.5);
  line-height: 20px;
  resize: none;
  border: none;
}

textarea:focus {
  outline: none;
}

textarea::-webkit-input-placeholder {
  font-size: 15px;
  opacity: 0.5;
  font-family: 'myFont', Arial, Helvetica, sans-serif;
}

#contact_inner_div_2 {
  margin-top: 6.7%;
  width: 60%;
  float: left;
}

.contact_name_and_email_fields_span {
  width: 35%;
  float: left;
}

.contact_name_and_email_fields {
  width: 147px;
  height: 30px;
}

#contact_subject_field {
  width: 313px;
  height: 30px;
  margin-top: 10px;
}

#contact_message_field {
  width: 301px;
  height: 141px;
  margin-top: 10px;
}

#contact_send_button {
  display: block;
  margin-top: 7px;
  margin-left: auto;
  margin-right: 60%;
  background-color: rgb(79, 87, 170);
  border: none;
  width: 317px;
  height: 40px;
  cursor: pointer;
}

#text_inside_of_buttion {
  color: black;
  opacity: 0.5;
  font-size: 15px;
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}

.text_align {
  text-align: center;
}

#contact_div_for_span_validator {
  margin-top: 2.5%;
  width: 317px;
}

.contact_validator_spans {
  display: none;
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  font-size: 14px;
}

.contact_error {
  border: 1px solid red;
  width: 146px;
  height: 28px;
}</code>```

<form>

            <input type="text" placeholder="Name"
            class="contact_name_and_email_fields" id="name_field"
            onfocus="input_focus_name();">

            <input type="text" placeholder="Email"
            class="contact_name_and_email_fields" id="email_field"
            onfocus="input_focus_email();">

  <input type="text" placeholder="Subject" id="contact_subject_field" onfocus="input_focus();">
  <textarea placeholder="Message" id="contact_message_field" onfocus="input_focus();"></textarea>
  <button type="button" id="contact_send_button" onclick="validate_contact_field();">
            Send
          </button>

              Validation Passed

              Validation Failed

</form>```

I would have posted a JSFiddle link but for some reason it looks like my javascript was not working on it for some reason.

答:
```<code>function checkField(field) {
    if (field.value == '') {
        //add the error class (border)
         field.classList.add("errorClass")

    }
    else if(field.classList.contains("errorClass")){
        //else if its not empty and has the class remove it
          field.classList.remove("errorClass");
    }
  }
</code>```

Then call it with

onblur="checkField(this);"

with your HTML elements.

Body:
So i am trying to make a form field in which i require users to enter their name, email, a subject and a message. I am trying to write code through javascript where if the user hits the send button I have made and does not have any or some of the information not filled out, there will be a red border around that specific input field where they did not fill out the required information. To accomplish this, I made a class in CSS that is added onto those input fields through javascript that adds that red border and decreases the height of the input fields slightly so that the added height through adding the red border does not move the input fields out of place. Everything works fine except when I try to decrease the height of the input fields. The height will only decrease on the name and email fields but not on any of my other fields and it will consequently move the input fields out of place a little bit when the red border is added. I have tried a lot of things but I cannot figure out any solution. I will add my section of code that has this issue. Thanks in advance.

var validate_contact_field = function() {
  var name = document.getElementById("name_field");
  var email = document.getElementById("email_field");
  var subject = document.getElementById("contact_subject_field");
  var message = document.getElementById("contact_message_field");
  if (name.value === "" && email.value === "" && subject.value === "" &&
    message.value === "") {
    document.getElementById("valid").style.display = "none";
    document.getElementById("invalid").style.display = "inline-block";
    document.getElementById("invalid").style.color = "red";
    document.getElementById("invalid").innerHTML = "You did not enter any \
        contact information";
    name.className = name.className + " contact_error";
    email.className = email.className + " contact_error";
  }
}

var input_focus_name = function() {
  var name = document.getElementById("name_field");
  name.className = name.className.replace(" contact_error", "");
}

var input_focus_email = function() {
  var email = document.getElementById("email_field");
  email.className = email.className.replace(" contact_error", "");
}

span {
  color: rgb(79, 87, 170);
}

input {
  text-indent: 5px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.5);
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  border: none;
}

input:focus {
  outline: none;
}

input::-webkit-input-placeholder {
  font-family: 'myFont', Arial, Helvetica, sans-serif;
  font-size: 15px;
  opacity: 0.5;
}

textarea {
  padding-left: 7px;
  padding-top: 5px;
  padding-right: 7px;
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.5);
  line-height: 20px;
  resize: none;
  border: none;
}

textarea:focus {
  outline: none;
}

textarea::-webkit-input-placeholder {
  font-size: 15px;
  opacity: 0.5;
  font-family: 'myFont', Arial, Helvetica, sans-serif;
}

#contact_inner_div_2 {
  margin-top: 6.7%;
  width: 60%;
  float: left;
}

.contact_name_and_email_fields_span {
  width: 35%;
  float: left;
}

.contact_name_and_email_fields {
  width: 147px;
  height: 30px;
}

#contact_subject_field {
  width: 313px;
  height: 30px;
  margin-top: 10px;
}

#contact_message_field {
  width: 301px;
  height: 141px;
  margin-top: 10px;
}

#contact_send_button {
  display: block;
  margin-top: 7px;
  margin-left: auto;
  margin-right: 60%;
  background-color: rgb(79, 87, 170);
  border: none;
  width: 317px;
  height: 40px;
  cursor: pointer;
}

#text_inside_of_buttion {
  color: black;
  opacity: 0.5;
  font-size: 15px;
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
}

.text_align {
  text-align: center;
}

#contact_div_for_span_validator {
  margin-top: 2.5%;
  width: 317px;
}

.contact_validator_spans {
  display: none;
  font-family: "Avant Garde", Avantgarde, "Century Gothic", CenturyGothic, "AppleGothic", sans-serif;
  font-size: 14px;
}

.contact_error {
  border: 1px solid red;
  width: 146px;
  height: 28px;
}

<form>

            <input type="text" placeholder="Name"
            class="contact_name_and_email_fields" id="name_field"
            onfocus="input_focus_name();">

            <input type="text" placeholder="Email"
            class="contact_name_and_email_fields" id="email_field"
            onfocus="input_focus_email();">

  <input type="text" placeholder="Subject" id="contact_subject_field" onfocus="input_focus();">
  <textarea placeholder="Message" id="contact_message_field" onfocus="input_focus();"></textarea>
  <button type="button" id="contact_send_button" onclick="validate_contact_field();">
            Send
          </button>

              Validation Passed

              Validation Failed

</form>

I would have posted a JSFiddle link but for some reason it looks like my javascript was not working on it for some reason.

Body:
function checkField(field) {
    if (field.value == '') {
        //add the error class (border)
         field.classList.add("errorClass")

    }
    else if(field.classList.contains("errorClass")){
        //else if its not empty and has the class remove it
          field.classList.remove("errorClass");
    }
  }

Then call it with

onblur="checkField(this);"

with your HTML elements.


问:
How can I use mysqli / php to update all records after a query has already been executed?
I have a user form that sets a single record "current". No more than one record can be set to current at a time. So, I present the user a single drop down list, they choose the item they want to set current and hit "UPDATE" at the bottom of the form.

The PHP/Mysqli needs to go in and set all records column "current" to a value of 0 then update the one from the form to a value of "1".

Initially, I just did a simple count the number of rows, and run a bunch of queries to update the column to 0 or 1 if the loop counter = the id of the row. Well... that broke quick as I started doing testing on other portions and the index numbers got higher than the total number of rows. Yes, dumb way to do it initially!

Here's what I tried to do with the PHP / MySQL code:

// $link  is the database link defined elsewhere. This does work as I use it all over the place
$setCurrent = X; // This is the number passed from my form

$init_query = "SELECT id, current FROM myTable";

if ($stmt = $link->$prepare($init_query) {
  $stmt->execute() or die ($stmt->error);
  $stmt ->bind_result($id, $current)
  while ($stmt->fetch()){
    if ($id == $setCurrent){

    $update_sql = "UPDATE myTable SET current ='1' WHERE id='".$setCurrent."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;

    }

    else {
    $update_sql =  "UPDATE myTable SET current ='0' WHERE id='".$id."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;
 }
 $stmt->close();```

This fails and gives me a Fatal error: Uncaught Error: Call to a member function execute on boolean in .....

I am racking my brain over this and can't figure out what the heck is going on. Its been a few years since I have worked in PHP/MySql and this is my first forray into OO Mysqli. Please be gentle :)

答: You're missing two closing curly braces. One for the first if() and the other for while()

Body:
I have a user form that sets a single record "current". No more than one record can be set to current at a time. So, I present the user a single drop down list, they choose the item they want to set current and hit "UPDATE" at the bottom of the form.

The PHP/Mysqli needs to go in and set all records column "current" to a value of 0 then update the one from the form to a value of "1".

Initially, I just did a simple count the number of rows, and run a bunch of queries to update the column to 0 or 1 if the loop counter = the id of the row. Well... that broke quick as I started doing testing on other portions and the index numbers got higher than the total number of rows. Yes, dumb way to do it initially!

Here's what I tried to do with the PHP / MySQL code:

// $link  is the database link defined elsewhere. This does work as I use it all over the place
$setCurrent = X; // This is the number passed from my form

$init_query = "SELECT id, current FROM myTable";

if ($stmt = $link->$prepare($init_query) {
  $stmt->execute() or die ($stmt->error);
  $stmt ->bind_result($id, $current)
  while ($stmt->fetch()){
    if ($id == $setCurrent){

    $update_sql = "UPDATE myTable SET current ='1' WHERE id='".$setCurrent."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;

    }

    else {
    $update_sql =  "UPDATE myTable SET current ='0' WHERE id='".$id."'";
    $stmt2 = $link->prepare($update_sql);
    $stmt2->execute;
 }
 $stmt->close();

This fails and gives me a Fatal error: Uncaught Error: Call to a member function execute on boolean in .....

I am racking my brain over this and can't figure out what the heck is going on. Its been a few years since I have worked in PHP/MySql and this is my first forray into OO Mysqli. Please be gentle :)


问:
what is the best way to transform a java Class into a php class?
I'd like to transform my java Class file intp a php class file. Do you know a good open source tool to do this?

Thanks you very much,

Bat

答: As far as i know there isn't any good automated scripts out there that converts java code to php, best practice would be think through what you want to have done read the php documentation which is very well documented. And try to accomplish the same thing. If you hit any obstacles feel free to come back here and ask whatever it might be. </p>


问:
Xcode5 xcassets - how to bulk replace images?
Say I have a project with 100 images that I've imported into a folder inside the main Images.xcassets file. Then I go and get updates for 67 of those images from my graphics designer - is there an easy way to push those image updates into the xcassets folder?

As it stands, I'm opening the xcassets file in Xcode, and for each of the images that's changed I'm dragging the new image into the little 2x or 1x box - I have to do that 67 times! I can't just drag/drop the files in Finder (the old way) because every image in the xcassets folder has its own subfolder. If I don't use the xcassets file for my images, I can easily update the files by doing this. But xcassets are supposed to "make managing your assets much simpler."

Fine - so what am I missing?

答:
I did not find a quick way, so I wrote one myself. Based on python. Enjoy.
https://github.com/qdvictory/happyxcasset</p>


问:
How to get request header (SOAP) from Apache CXF Interceptor
I'm working on the client side where I have generated classes from wsdl and @Service which calls methods of @WebService generated from the wsdl. My task is to get soap header which is returned when I call method on the server. I have implemented interceptor, marked it as a bean in cxf client configuration. How can I now get the header?

Thanks in advance for your help.

答: I hope you have written SoapActionInInterceptor in READ phase. Then when you override handleMessage method you will have SoapMessage as its parameter and you can take the Soap Header also from it. Check Apache CXF Guide  for more reference


问:
Find matching words in a list and a string
I am writing some code in Python and I want to check if a list of words is in a long string.  I know I could iterate through it multiple times and that may be the same thing but I wanted tp see if there is a faster way to do it.  What I am currently doing is this:

```<code>    all_text = 'some rather long string'
    if "motorcycle" in all_text or 'bike' in all_text or 'cycle' in all_text or 'dirtbike' in all_text:
        print 'found one of em'
</code>```

but what I want to do is this:

```<code>keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if item in keyword_list in all_text:
            print 'found one of em'
</code>```

Is there anyway to do this efficiently?  I realize I could do:

```<code>keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
for item in keyword_list:
      if item in all_text:
            print 'found one of em'
</code>```

But it seems like there would be a better way once the keyword list becomes long.

答:
Using regular expression is probably the fast way.

```<code>re.findall(r'motorcycle|bike|cycle|dirtbike', text)
</code>```

will return all matches of selected words.

Body:
I am writing some code in Python and I want to check if a list of words is in a long string.  I know I could iterate through it multiple times and that may be the same thing but I wanted tp see if there is a faster way to do it.  What I am currently doing is this:

    all_text = 'some rather long string'
    if "motorcycle" in all_text or 'bike' in all_text or 'cycle' in all_text or 'dirtbike' in all_text:
        print 'found one of em'

but what I want to do is this:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if item in keyword_list in all_text:
            print 'found one of em'

Is there anyway to do this efficiently?  I realize I could do:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
for item in keyword_list:
      if item in all_text:
            print 'found one of em'

But it seems like there would be a better way once the keyword list becomes long.

Body:
Using regular expression is probably the fast way.

re.findall(r'motorcycle|bike|cycle|dirtbike', text)

will return all matches of selected words.


问:
symbolicating iPad app crash reports
Here, i am bit new to iPad developement and to objective-c. I am facing a problem here reading device logs. when i browsed through logs, people said that i have build and archive and use that build to the device. so that next time when you connected the device to your machine, device logs will automatically symbolicate the crash logs. But this is not the case.

The steps i am following right now.

put the xcode configuration device and release.

Build -> Build and archive.

Go to Build folder, drag and drop the binary file on Itunes icon and select replace.

after the testing, re-connect the ipad, go to organizer window, select the device, click on device logs.

This shows the symbols only...not any clue of where it is crashed.

eg:the crash report

```<code>Thread 0 Crashed:
0   libSystem.B.dylib               0x30d7c2d4 __kill + 8
1   libSystem.B.dylib               0x30d7c2c4 kill + 4
2   libSystem.B.dylib               0x30d7c2b6 raise + 10
3   libSystem.B.dylib               0x30d90d72 abort + 50
4   libSystem.B.dylib               0x30d7e980 __assert_rtn + 152
5   libgcc_s.1.dylib                0x307e8b4e _Unwind_SjLj_Resume + 26
6   CoreFoundation                  0x35801d50 CFRunLoopRunSpecific + 432
7   CoreFoundation                  0x35801b88 CFRunLoopRunInMode + 52
8   GraphicsServices                0x320c84a4 GSEventRunModal + 108
9   GraphicsServices                0x320c8550 GSEventRun + 56
10  UIKit                           0x341dc322 -[UIApplication _run] + 406
11  UIKit                           0x341d9e8c UIApplicationMain + 664
12  My EF                           0x00002c84 main (main.m:14)
13  My EF                           0x00002c4c start + 32
</code>```

Please let me know if i am doing something wrong.

thanks
suresh

答:
EDIT

It is symbolicating your code - you're doing everything correctly. you can tell because it's saying main.m:14 telling you that the stack trace is on line 14 of main.m

The reason that you can't see anything else is because it's not your code :) The apple libraries are compiled for you - you just link them into your app. It can't tell you the line that crashed because you don't have the code!

This tells you that the crash happened somewhere deep inside apple's code, which isn't good news for you. you need to make this crash happen while you're running it in XCode so you can see exactly what's going on.

Off the top of my head, have you included libgcc_s in your list of linked frameworks?

Yea, it's a tricky one.

The thing that tripped me up was that it doesn't just have to be a build of the same code, it has to be the exact same build that was installed on the app. Rebuilding isn't good enough.

To solve this I use version control (specifically, git). Every time I give out a version of the app to people to test I copy the build folder into a releases/ directory. I then tag it (e.g. release_2010_12_10_showcase) so if they come back with a crash, I can ask them when I gave them the app and checkout the correct version of the build. This means I have the symbols from the build on their app and my code in XCode is exactly the same as the code they were running so I can see where the crash happened and fix it :) Then, using the magic of git, I can merge my change into my latest code :)

NS I have not used archiving apps yet - it sounds like you're doing the right thing but I think there's some sort of magic going on that only Apple understand :) I also like having everything in my version control and I don't know enough about archives in XCode to be comfortable with it. Though that probably means that I should just learn how they work!

Title: symbolicating iPad app crash reports

Body:
Here, i am bit new to iPad developement and to objective-c. I am facing a problem here reading device logs. when i browsed through logs, people said that i have build and archive and use that build to the device. so that next time when you connected the device to your machine, device logs will automatically symbolicate the crash logs. But this is not the case.

The steps i am following right now.

put the xcode configuration device and release.

Build -> Build and archive.

Go to Build folder, drag and drop the binary file on Itunes icon and select replace.

after the testing, re-connect the ipad, go to organizer window, select the device, click on device logs.

This shows the symbols only...not any clue of where it is crashed.

eg:the crash report

Thread 0 Crashed:
0   libSystem.B.dylib               0x30d7c2d4 __kill + 8
1   libSystem.B.dylib               0x30d7c2c4 kill + 4
2   libSystem.B.dylib               0x30d7c2b6 raise + 10
3   libSystem.B.dylib               0x30d90d72 abort + 50
4   libSystem.B.dylib               0x30d7e980 __assert_rtn + 152
5   libgcc_s.1.dylib                0x307e8b4e _Unwind_SjLj_Resume + 26
6   CoreFoundation                  0x35801d50 CFRunLoopRunSpecific + 432
7   CoreFoundation                  0x35801b88 CFRunLoopRunInMode + 52
8   GraphicsServices                0x320c84a4 GSEventRunModal + 108
9   GraphicsServices                0x320c8550 GSEventRun + 56
10  UIKit                           0x341dc322 -[UIApplication _run] + 406
11  UIKit                           0x341d9e8c UIApplicationMain + 664
12  My EF                           0x00002c84 main (main.m:14)
13  My EF                           0x00002c4c start + 32

Please let me know if i am doing something wrong.

thanks
suresh


问:
How can I add JPEGs to an asset catalog in Xcode?
Is it possible to add assets other than PNG files to an Xcode Asset Catalog?

When I drag JPEG files into an Asset Catalog they aren't accepted by the UI.

答:
Try this.
Quickly import resource scripts to resolve import speed and rename issues.
https://github.com/qdvictory/happyxcasset</p>


问:
No requests module error
I'm trying to write a web parser script using requests module. Here is my current code:

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)
</code>```

But when I run the code, it says:

```<code>Traceback (most recent call last):
  File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
    import requests
ImportError: No module named 'requests'
</code>```

Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?

答:
Even after you have pip3-installed requests, the code shown won't do anything. The

```<code>    if __name__ == "__main__"
</code>```

test and everything after it is part of an else block in the view function.  Back this line and the block that follows out to the left margin.

Title: No requests module error

Body:
I'm trying to write a web parser script using requests module. Here is my current code:

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"],
  stdout=subprocess.PIPE).communicate()[0]
  return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
  global numberOfSockets
  global numberOfViewers
  while True:
    if numberOfSockets < numberOfViewers:
      numberOfSockets += 1
      print ("Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers))
      urls.append(getURL())

def view(): # Opens connections to send views
  global numberOfSockets
  while True:
    url=q.get()
    requests.head(url)
    if (url in urlsUsed):
      urls.remove(url)
      urlsUsed.remove(url)
      numberOfSockets -= 1
    else:
      urlsUsed.append(url)
      q.task_done()

      if __name__ == '__main__':
        for i in range(0, builderThreads):
          threading.Thread(target = build).start()

          while True:
            while (numberOfViewers != numberOfSockets): # Wait until sockets are built
              time.sleep(1)

              q=Queue(concurrent*2)
              for i in range(concurrent):
                try:
                  t=threading.Thread(target=view)
                  t.daemon=True
                  t.start()
                except:
                  print ('thread error')
                  try:
                    for url in urls:
                      print (url)
                      q.put(url.strip())
                      q.join()
                  except KeyboardInterrupt:
                    sys.exit(1)

But when I run the code, it says:

Traceback (most recent call last):
  File "C:\Users\flamelier\Desktop\Twitch.py", line 1, in <module>
    import requests
ImportError: No module named 'requests'

Why am I getting this error? How do I install this module?
Will this error keep repeating for all the scripts henceforth?
How can I prevent such similar errors in the future?

Body:
Even after you have pip3-installed requests, the code shown won't do anything. The

    if __name__ == "__main__"

test and everything after it is part of an else block in the view function.  Back this line and the block that follows out to the left margin.


问:
Ignoring a function's return to save memory in Python
This might not even be an issue but I've got a couple of related Python questions that will hopefully help clear up a bit of debugging I've been stuck on for the past week or two.

If you call a function that returns a large object, is there a way to ignore the return value in order to save memory?

My best example is, let's say you are piping a large text file, line-by-line, to another server and when you complete the pipe, the function returns a confirmation for every successful line.  If you pipe too many lines, the returned list of confirmations could potentially overrun your available memory.

```<code>for line in lines:
    connection.put(line)
response = connection.execute()
</code>```

If you remove the response variable, I believe the return value is still loaded into memory so is there a way to ignore/block the return value when you don't really care about the response?

More background: I'm using the redis-python package to pipeline a large number of set-additions.  My processes occasionally die with out-of-memory issues even though the file itself is not THAT big and I'm not entirely sure why.  This is just my latest hypothesis.

答: I think the confirmation response is not big enough to overrun your memory. In python, when you read lines from file , the lines is always in memory which cost large memory resource. </p>

Body:
This might not even be an issue but I've got a couple of related Python questions that will hopefully help clear up a bit of debugging I've been stuck on for the past week or two.

If you call a function that returns a large object, is there a way to ignore the return value in order to save memory?

My best example is, let's say you are piping a large text file, line-by-line, to another server and when you complete the pipe, the function returns a confirmation for every successful line.  If you pipe too many lines, the returned list of confirmations could potentially overrun your available memory.

for line in lines:
    connection.put(line)
response = connection.execute()

If you remove the response variable, I believe the return value is still loaded into memory so is there a way to ignore/block the return value when you don't really care about the response?

More background: I'm using the redis-python package to pipeline a large number of set-additions.  My processes occasionally die with out-of-memory issues even though the file itself is not THAT big and I'm not entirely sure why.  This is just my latest hypothesis.


问:
Unity (Object name vs gameobject)
I'm taking an online class for game development using unity, the instructor can at sometimes be vague. I am under the impression that using gameobject is the same as using the game objects name(in this case it is MusicPlayer), but when I try and replace MusicPlayer instance with gameobject instance, I get the errorCS0246: The type or namespace name `gameobject' could not be found. Are you missing a using directive or an assembly reference? I am just trying to understand the difference between the two. Thank you in advance.

```<code>using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
static MusicPlayer instance = null;
 void Awake(){
    if (instance != null){
    Destroy(gameObject);
    Debug.Log("Duplicate MusicPlayer Destroyed");
    }

    else{
    instance = this;
    GameObject.DontDestroyOnLoad(gameObject);
    Debug.Log("Original MusicPlayer Created!");
    }
}
}
</code>```

This is the code that I am getting error with:

```<code>using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
public static gameobject instance = null;

void Awake(){
    if (instance != null){
    Destroy(gameObject);
    Debug.Log("Duplicate MusicPlayer Destroyed");
    }

    else{
    instance = this;
    GameObject.DontDestroyOnLoad(gameObject);
    Debug.Log("Original MusicPlayer Created!");
    }
}
}
</code>```

答:
There is a difference between gameObject and GameObject. Notice the capitalized "G" in the second one.

GameObject is a class. You can create an instance of it like this:

```<code>GameObject myobject = new GameObject("PhilipBall");
</code>```

or you can make it a public variable and assign it from the Editor:

```<code>public  GameObject myobject;
</code>```

gameObject is a variable that is created from GameObject. It is declared like the myobject variable example above.

The reason you can't see it is because it is declared inside a class named Component. Then a class called Behaviour inherits from that Component class. There is another class named MonoBehaviour which inherits from the Behaviour class. Finally, your script which is called MusicPlayer  inherits from MonoBehaviour when you did public class MusicPlayer : MonoBehaviour. Because of this you inherit the gameObject variable and can use it.

The gameObject variable type of GameObject class and is used to refer to the GameObject this script is attached to.

I want to know why I cannot use gameObject and must use the name of
  the gameObject

You can actually do that. Just replace public static gameobject instance = null; with public static GameObject instance = null; then instance = this; with instance = this.gameObject;.

```<code>public class MusicPlayer : MonoBehaviour
{
    public static GameObject instance = null;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            Debug.Log("Duplicate MusicPlayer Destroyed");
        }

        else
        {
            instance = this.gameObject;
            GameObject.DontDestroyOnLoad(gameObject);
            Debug.Log("Original MusicPlayer Created!");
        }
    }
}
</code>```

When you use this, you are referring to this script which is MusicPlayer. When you use this.gameObject, you are referring to this GameObject this script is attached to.

Why is public static GameObject instance = null; not used by your instructor?

This is because they want to access the MusicPlayer script variables, functions during run-time.They don't need the GameObject. Now, this can be done with a GameObject but you will have to perform extra steps such as using GetComponent in order to use a variable or call a function in that script.

For example, you have a function named "runFunction" in that script and you want to call it. With the first example, you can just do:

```<code>MusicPlayer.instance.runFunction();
</code>```

With the second example, you have to do:

```<code>MusicPlayer.instance.GetComponent<MusicPlayer>().runFunction();
</code>```

That's the big difference and also note that GetComponent is expensive.

Title: Unity (Object name vs gameobject)

Body:
I'm taking an online class for game development using unity, the instructor can at sometimes be vague. I am under the impression that using gameobject is the same as using the game objects name(in this case it is MusicPlayer), but when I try and replace MusicPlayer instance with gameobject instance, I get the errorCS0246: The type or namespace name `gameobject' could not be found. Are you missing a using directive or an assembly reference? I am just trying to understand the difference between the two. Thank you in advance.

using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
static MusicPlayer instance = null;
 void Awake(){
    if (instance != null){
    Destroy(gameObject);
    Debug.Log("Duplicate MusicPlayer Destroyed");
    }

    else{
    instance = this;
    GameObject.DontDestroyOnLoad(gameObject);
    Debug.Log("Original MusicPlayer Created!");
    }
}
}

This is the code that I am getting error with:

using UnityEngine;
using System.Collections;
public class MusicPlayer : MonoBehaviour {
public static gameobject instance = null;

void Awake(){
    if (instance != null){
    Destroy(gameObject);
    Debug.Log("Duplicate MusicPlayer Destroyed");
    }

    else{
    instance = this;
    GameObject.DontDestroyOnLoad(gameObject);
    Debug.Log("Original MusicPlayer Created!");
    }
}
}

Body:
There is a difference between gameObject and GameObject. Notice the capitalized "G" in the second one.

GameObject is a class. You can create an instance of it like this:

GameObject myobject = new GameObject("PhilipBall");

or you can make it a public variable and assign it from the Editor:

public  GameObject myobject;

gameObject is a variable that is created from GameObject. It is declared like the myobject variable example above.

The reason you can't see it is because it is declared inside a class named Component. Then a class called Behaviour inherits from that Component class. There is another class named MonoBehaviour which inherits from the Behaviour class. Finally, your script which is called MusicPlayer  inherits from MonoBehaviour when you did public class MusicPlayer : MonoBehaviour. Because of this you inherit the gameObject variable and can use it.

The gameObject variable type of GameObject class and is used to refer to the GameObject this script is attached to.

I want to know why I cannot use gameObject and must use the name of
  the gameObject

You can actually do that. Just replace public static gameobject instance = null; with public static GameObject instance = null; then instance = this; with instance = this.gameObject;.

public class MusicPlayer : MonoBehaviour
{
    public static GameObject instance = null;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
            Debug.Log("Duplicate MusicPlayer Destroyed");
        }

        else
        {
            instance = this.gameObject;
            GameObject.DontDestroyOnLoad(gameObject);
            Debug.Log("Original MusicPlayer Created!");
        }
    }
}

When you use this, you are referring to this script which is MusicPlayer. When you use this.gameObject, you are referring to this GameObject this script is attached to.

Why is public static GameObject instance = null; not used by your instructor?

This is because they want to access the MusicPlayer script variables, functions during run-time.They don't need the GameObject. Now, this can be done with a GameObject but you will have to perform extra steps such as using GetComponent in order to use a variable or call a function in that script.

For example, you have a function named "runFunction" in that script and you want to call it. With the first example, you can just do:

MusicPlayer.instance.runFunction();

With the second example, you have to do:

MusicPlayer.instance.GetComponent<MusicPlayer>().runFunction();

That's the big difference and also note that GetComponent is expensive.


问:
Getting maxlength from array
I'm trying to get the longest description from $productDetail array, but it returns empty array elements:

```<code>$desc = array_map(function($a) {
            return (!!$desc && strlen($desc) < strlen($a["desc"])) ?
                $a["desc"] : $desc;
        }, $productDetail);
</code>```

答:
```<code>$desc = array_reduce(array_map(function($a) { return $a["desc"]; }, $productDetail),
            function ($a, $b) { return strlen($a) > strlen($b) ? $a : $b; }
        );
</code>```

Title: Getting maxlength from array

Body:
I'm trying to get the longest description from $productDetail array, but it returns empty array elements:

$desc = array_map(function($a) {
            return (!!$desc && strlen($desc) < strlen($a["desc"])) ?
                $a["desc"] : $desc;
        }, $productDetail);


问:
Add many images to xcodes asset catalog - how to manage naming and 1x,2x,3x for each?
I have an app where I would like to add many images (500+) to xcode's asset catalog. Adding the 1x images was easy, I simply had to drag the first folder. However to add the 2x and 3x images it seems I would need to drag each image in manually, and I'd prefer not to do that. The 3 different sizes for each image are all named the same, w/ just different sizes. Is there anyway to automate this process?</p>

答:
Happyxcasset is a python script that easily imports resource files into xcassets in Xcode.
https://github.com/qdvictory/happyxcasset
You will like it.

ContentLicense: CC BY-SA 4.0


问:
Why am I not able to access the result of multiple networking calls?
In my Node app I am trying to get shipment data for packages. I need a way to get the json data and append it to an object or something so that I can pass it to my render page (using pug).

This is my code:

```<code>    var test;

    for(var i = 0; i < result.length; i++) {
        var currentNumber = result[i].trackingNumber;
        ups.track(currentNumber, function(err, tracking) {
            test += tracking
        });
    }

    res.send(result)
</code>```

It seems that anything I do inside of the ups.track has no scope into the var test, and I can't think of a better way to do this. Any help would be appreciated.

答:
The first problem is that test is undefined at the start. That's bad. You want a default value of the same type you expect it to be var test = "";

The big problem, though, is that you are sending before any of those ups callbacks ever return.

You've fired off 18 (or whatever) requests to UPS, but you've returned result before the UPS server even got the first request, let alone completed them all.

Rather than show you the really hairy code that might be written to make things work in your loops, I'd recommend trying something like this:

```<code>const track = trackingNumber =>
  new Promise((resolve, reject) =>
    ups.track(trackingNumber, (err, data) =>
      err ? reject(err) : resolve(data)));

Promise.all(result.map(info => track(info.trackingNumber)))
  .then(trackingNumbers => trackingNumbers.join(''))
  .then(bigStringOfNumbers => res.send(bigStringOfNumbers));
</code>```

Learning about Promises, Promise.all(), and [].map() is going to be a much more helpful path than trying to build out the complex callback version of this solution.

Body:
In my Node app I am trying to get shipment data for packages. I need a way to get the json data and append it to an object or something so that I can pass it to my render page (using pug).

This is my code:

    var test;

    for(var i = 0; i < result.length; i++) {
        var currentNumber = result[i].trackingNumber;
        ups.track(currentNumber, function(err, tracking) {
            test += tracking
        });
    }

    res.send(result)

It seems that anything I do inside of the ups.track has no scope into the var test, and I can't think of a better way to do this. Any help would be appreciated.

Body:
The first problem is that test is undefined at the start. That's bad. You want a default value of the same type you expect it to be var test = "";

The big problem, though, is that you are sending before any of those ups callbacks ever return.

You've fired off 18 (or whatever) requests to UPS, but you've returned result before the UPS server even got the first request, let alone completed them all.

Rather than show you the really hairy code that might be written to make things work in your loops, I'd recommend trying something like this:

const track = trackingNumber =>
  new Promise((resolve, reject) =>
    ups.track(trackingNumber, (err, data) =>
      err ? reject(err) : resolve(data)));

Promise.all(result.map(info => track(info.trackingNumber)))
  .then(trackingNumbers => trackingNumbers.join(''))
  .then(bigStringOfNumbers => res.send(bigStringOfNumbers));

Learning about Promises, Promise.all(), and [].map() is going to be a much more helpful path than trying to build out the complex callback version of this solution.


问:
String to Double in Java
I have in my Java app double numbers. I need to convert String to Double, but string representation of number is

, - separates decimal part of number (
  example    1,5  eq 6/4 )

. - separates groups of three digits (
  example  1.000.000  eq 1000000 )

.
How to achieve this conversion String to Double ?

答: Use the parse method in DecimalFormat.</p>

Title: String to Double in Java

Body: Use the parse method in DecimalFormat.


问:
Security concerns calling an ASP.NET WebAPI from both the client and controller in an MVC app
I have an ASP.NET Core Web API application that is separate from my ASP.NET Core MVC application (UI). I didn't want to combine them for several reasons since in the future many different clients might need to access the API.

The MVC application makes calls to the API two different ways:

1. Using System.Net.HttpClient in the MVC controllers to populate the View Models.

2. When making jQuery AJAX calls I figured it would be best to directly call the API. (Note: I enabled CORS to allow calls from the MVC application). This would be the same thing as an Angular client making calls directly to the API.

My questions:

Is what I am doing pretty common making calls to the API directly from the client with jQuery and additionally System.Net.HttpClient in the Controllers when not using AJAX and just loading the view data. Should the AJAX calls go to the MVC controller first then let them MVC controller make a DELETE request using System.Net.HttpClient so I am never directly calling the API from the client?

What would the security concerns be? I am a bit nervous calling the API directly from jQuery. I feel like anyone can pretent they are localhost:6000 (my MVC port) and make a DELETE request to localhost:6001/api/users/1 (my API port).

答:
You absolutely correct to be concerned about this. You should be securing your application from this making sure any requests to access these API methods are authorized.

I recommend reading 10 Points to Secure Your ASP.NET MVC Applications. for an overview on how to protect your application from this kind of attack and several other common security vulnerabilities.


问:
Scroll to element only if not in view - jQuery
I know a variation on this has been asked several times; I've been browsing SO for a while now but either I'm doing something wrong or I haven't found what I need.

I have a structure of nested comments, pretty much the same as the Facebook Comments plugin, and whenever reply is clicked, a small form with textarea and a button appear at the bottom of the comments.

Again, the behaviour is the same as the Facebook Comments plugin and I want to achieve the same when it comes to scrolling the newly add textarea into view.

I've tried the scrollTo plugin, and it works smoothly but, even if I manually scroll to the very bottom of the page, the scroll animation will always reset the scroll position and begin from the top.

For the record, this is how I'm calling scrollTo:

```<code>$.scrollTo($('#addReply_1'), 800);
</code>```

where addReply_1 is the div containing the form. I've stried scrolling to the form itself and to the textarea. Same results.

Is there a way to scroll to an element only if its not already visible?

I've tried many solutions offered on SO, like Scroll to an element using jQuery, but none seem to behave as desired; even Scroll to a particular element w/ jQuery or Check if element is visible after scrolling displays the same "jumpy" behaviour.

UPDATE: Online demo to show behaviour

I've uploaded an html demo page that shows the behaviour I'm complaining about: http://www.wouldbebetter.com/demo/comment-demo.htm

Just scroll to the bottom of the page and click any of the Reply links to see the "jumpy" scrolling I'm referring to.

Note that this demo uses the scrollintoview plugin of @Robert Koritnik's answer, but the behaviour is the same if I use, for instance, ScrollTo.

答:
JQuery is not required for this.

This function just shows the specified element:

```<code>function scrollIntoView(elm) {
    if(elm) {
        let bnd=elm.getBoundingClientRect();
        if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
        else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
        }
    return elm;
    }
</code>```

The following more capable function allows a container of the desired element to be scrolled into view, also providing the ability to easily ensure that the entire container is made visible so that half-occluded visuals are avoided.

```<code>/**
  * Scroll the specified element into view, optionally first searching for a specific container and
  * first making that visible. This function does it's best to scroll the entire container into view
  * but ultimately ensures that as much of the element as fits in the viewport will be visible.
  *
  * #### Arguments:
  *
  *     elm (DOMElement)    The element to make visible.
  *     contag (string)     Optional name of a container tag. Ignored if blank/null/omitted.
  *     conprp (string)     Optional name of a container property to also match. Ignored if blank/null/omitted.
  *     conval (string)     Optional value of the container property. Ignored if `conprp` is not supplied; defaults to "" if omitted.
  */
function scrollIntoView(elm,contag,conprp,conval) {
    if(elm) {
        if(contag || conprp) {
            let con;
            if(conval==null) { conval=""; }
            for(con=elm; con!=null && con.tagName!="BODY"; con=con.parentNode) {
                if((!contag || contag==con.tagName) && (!conprp || con[conprp]==conval)) {
                    break;                                                                          // matched container tag and property
                    }
                }
            if(con) { scrollIntoView(con); }
            }

        let bnd=elm.getBoundingClientRect();

        if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
        else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
        }
    return elm;
    }
</code>```

This makes it easy to, for example, show this when scrolling up:

instead of this:

Body:
I know a variation on this has been asked several times; I've been browsing SO for a while now but either I'm doing something wrong or I haven't found what I need.

I have a structure of nested comments, pretty much the same as the Facebook Comments plugin, and whenever reply is clicked, a small form with textarea and a button appear at the bottom of the comments.

Again, the behaviour is the same as the Facebook Comments plugin and I want to achieve the same when it comes to scrolling the newly add textarea into view.

I've tried the scrollTo plugin, and it works smoothly but, even if I manually scroll to the very bottom of the page, the scroll animation will always reset the scroll position and begin from the top.

For the record, this is how I'm calling scrollTo:

$.scrollTo($('#addReply_1'), 800);

where addReply_1 is the div containing the form. I've stried scrolling to the form itself and to the textarea. Same results.

Is there a way to scroll to an element only if its not already visible?

I've tried many solutions offered on SO, like Scroll to an element using jQuery, but none seem to behave as desired; even Scroll to a particular element w/ jQuery or Check if element is visible after scrolling displays the same "jumpy" behaviour.

UPDATE: Online demo to show behaviour

I've uploaded an html demo page that shows the behaviour I'm complaining about: http://www.wouldbebetter.com/demo/comment-demo.htm

Just scroll to the bottom of the page and click any of the Reply links to see the "jumpy" scrolling I'm referring to.

Note that this demo uses the scrollintoview plugin of @Robert Koritnik's answer, but the behaviour is the same if I use, for instance, ScrollTo.

Body:
JQuery is not required for this.

This function just shows the specified element:

function scrollIntoView(elm) {
    if(elm) {
        let bnd=elm.getBoundingClientRect();
        if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
        else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
        }
    return elm;
    }

The following more capable function allows a container of the desired element to be scrolled into view, also providing the ability to easily ensure that the entire container is made visible so that half-occluded visuals are avoided.

/**
  * Scroll the specified element into view, optionally first searching for a specific container and
  * first making that visible. This function does it's best to scroll the entire container into view
  * but ultimately ensures that as much of the element as fits in the viewport will be visible.
  *
  * #### Arguments:
  *
  *     elm (DOMElement)    The element to make visible.
  *     contag (string)     Optional name of a container tag. Ignored if blank/null/omitted.
  *     conprp (string)     Optional name of a container property to also match. Ignored if blank/null/omitted.
  *     conval (string)     Optional value of the container property. Ignored if `conprp` is not supplied; defaults to "" if omitted.
  */
function scrollIntoView(elm,contag,conprp,conval) {
    if(elm) {
        if(contag || conprp) {
            let con;
            if(conval==null) { conval=""; }
            for(con=elm; con!=null && con.tagName!="BODY"; con=con.parentNode) {
                if((!contag || contag==con.tagName) && (!conprp || con[conprp]==conval)) {
                    break;                                                                          // matched container tag and property
                    }
                }
            if(con) { scrollIntoView(con); }
            }

        let bnd=elm.getBoundingClientRect();

        if     (bnd.top<0                    ) { elm.scrollIntoView(true );      }
        else if(bnd.bottom>window.innerHeight) { elm.scrollIntoView(bnd.top<=0); }
        }
    return elm;
    }

This makes it easy to, for example, show this when scrolling up:

instead of this:


问:
How to localize DotNetBar DatePicker?
How to localize the DatePicker component of the DotNetBar to show a localized Calendar?

Even when changing the input language, it still shows the English calendar.
What's the solution?

答:
You just need to add handler for LocalizationKeys.LocalizeString static event.

Below is an example to localize the text for DateTimeInput control.

In your static void Main() method,

```<code>DevComponents.DotNetBar.LocalizationKeys.LocalizeString += new DotNetBarManager.LocalizeStringEventHandler(LocalizeString);

private static void LocalizeString(object sender, LocalizeEventArgs e)
    {
        if (e.Key == LocalizationKeys.MonthCalendarTodayButtonText)
        {
            e.LocalizedValue = Properties.Resources.MonthCalendarTodayButtonText;
        }
        if (e.Key == LocalizationKeys.MonthCalendarClearButtonText)
        {
            e.LocalizedValue = Properties.Resources.MonthCalendarClearButtonText;
        }

        e.Handled = true;
    }
</code>```

You can refer to official docs here. http://www.devcomponents.com/kb2/?p=523

Title: How to localize DotNetBar DatePicker?

Body:
You just need to add handler for LocalizationKeys.LocalizeString static event.

Below is an example to localize the text for DateTimeInput control.

In your static void Main() method,

DevComponents.DotNetBar.LocalizationKeys.LocalizeString += new DotNetBarManager.LocalizeStringEventHandler(LocalizeString);

private static void LocalizeString(object sender, LocalizeEventArgs e)
    {
        if (e.Key == LocalizationKeys.MonthCalendarTodayButtonText)
        {
            e.LocalizedValue = Properties.Resources.MonthCalendarTodayButtonText;
        }
        if (e.Key == LocalizationKeys.MonthCalendarClearButtonText)
        {
            e.LocalizedValue = Properties.Resources.MonthCalendarClearButtonText;
        }

        e.Handled = true;
    }

You can refer to official docs here. http://www.devcomponents.com/kb2/?p=523


问:
Ajax Auto-Lookup function for text box
I am designing a php page.In that i have text box.I want autofill (just like google search text box)option for that.I am new to jquery.I am slow in implementing.If anyone knw pls guide me.I want a simple code so that i can paste and check it.I surfed website.All are complex .</p>

答:
For an input field, you may also need secondary data that can be received from the server.  This tool provides the ability to use that data intuitively.

https://github.com/nfosci/input-fetcher-dropdown

Title: Ajax Auto-Lookup function for text box


问:
How to do In-App Purchases ink ivy using Google Play
I have written a kivy android app and was wondering how to implement in-app purchases. I need a good system that won't create too many bugs due to the fact that I don't want to be liable for loads of refunds due to the code not working correctly.  Thanks, Sean</p>

答: https://developer.android.com/google/play/billing/index.html read this doc, maybe is gonna help you</p>