问:
Cannot start a new React Native CLI project in WebStorm
The react-native-cli is generating the project fine when I use this command in terminal:

```<code>react-native init myapp
</code>```

But for some reason WebStorm cannot create new React Native project. When I try I get this error:

```<code>/home/sagar/.nvm/versions/node/v8.9.1/bin/node
/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js init bookip
/bin/sh: 1: npm: not found
This will walk you through creating a new React Native project in /tmp/1512313270685-0/bookip
Installing react-native...
Consider installing yarn to make this faster: https://yarnpkg.com
{ Error: Command failed: npm install --save --save-exact react-native
    at checkExecSyncError (child_process.js:601:13)
    at execSync (child_process.js:641:13)
    at run (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:294:5)
    at createProject (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
  error: null,
  cmd: 'npm install --save --save-exact react-native',
  file: '/bin/sh',
  args:
   [ '/bin/sh',
     '-c',
     'npm install --save --save-exact react-native' ],
  options:
   { stdio: [ [Object], [Object], [Object] ],
     shell: true,
     file: '/bin/sh',
     args:
      [ '/bin/sh',
        '-c',
        'npm install --save --save-exact react-native' ],
     envPairs:
      [ 'PATH=/home/sagar/bin:/home/sagar/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
        'LC_MEASUREMENT=ne_NP',
        'XAUTHORITY=/home/sagar/.Xauthority',
        'XMODIFIERS=@im=ibus',
        'LC_TELEPHONE=ne_NP',
        'XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop',
        'GDMSESSION=ubuntu',
        'MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path',
        'LC_TIME=ne_NP',
        'GTK_IM_MODULE=ibus',
        'DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Sq2eReOVZr',
        'DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path',
        'XDG_CURRENT_DESKTOP=Unity',
        'LD_LIBRARY_PATH=/home/sagar/apps/WebStorm-172.3757.55/bin:',
        'UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/1000/1240',
        'QT4_IM_MODULE=xim',
        'LC_PAPER=ne_NP',
        'QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1',
        'LOGNAME=sagar',
        'JOB=unity-settings-daemon',
        'PWD=/tmp/1512313270685-0',
        'IM_CONFIG_PHASE=1',
        'LANGUAGE=en_US',
        'SHELL=/bin/bash',
        'LC_ADDRESS=ne_NP',
        'GIO_LAUNCHED_DESKTOP_FILE=/home/sagar/.local/share/applications/jetbrains-webstorm.desktop',
        'GTK2_MODULES=overlay-scrollbar',
        'INSTANCE=',
        'OLDPWD=/home/sagar/apps/WebStorm-172.3757.55/bin',
        'GNOME_DESKTOP_SESSION_ID=this-is-deprecated',
        'UPSTART_INSTANCE=',
        'GTK_MODULES=gail:atk-bridge:unity-gtk-module',
        'CLUTTER_IM_MODULE=xim',
        'XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0',
        'COMPIZ_BIN_PATH=/usr/bin/',
        'SESSIONTYPE=gnome-session',
        'XDG_SESSION_DESKTOP=ubuntu',
        'SHLVL=0',
        'LC_IDENTIFICATION=ne_NP',
        'LC_MONETARY=ne_NP',
        'COMPIZ_CONFIG_PROFILE=ubuntu',
        'QT_IM_MODULE=ibus',
        'UPSTART_JOB=unity7',
        'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64',
        'XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
        'LANG=en_US.UTF-8',
        'GNOME_KEYRING_CONTROL=',
        'XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0',
        'XDG_SESSION_ID=c2',
        'XDG_SESSION_TYPE=x11',
        'DISPLAY=:0',
        'LC_NAME=ne_NP',
        'GDM_LANG=en_US',
        'XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/sagar',
        'UPSTART_EVENTS=xsession started',
        'GPG_AGENT_INFO=/home/sagar/.gnupg/S.gpg-agent:0:1',
        'DESKTOP_SESSION=ubuntu',
        'SESSION=ubuntu',
        'USER=sagar',
        'XDG_MENU_PREFIX=gnome-',
        'GIO_LAUNCHED_DESKTOP_FILE_PID=20103',
        'QT_ACCESSIBILITY=1',
        'LC_NUMERIC=ne_NP',
        'SSH_AUTH_SOCK=/run/user/1000/keyring/ssh',
        'XDG_SEAT=seat0',
        'QT_QPA_PLATFORMTHEME=appmenu-qt5',
        'XDG_VTNR=7',
        'XDG_RUNTIME_DIR=/run/user/1000',
        'HOME=/home/sagar',
        'GNOME_KEYRING_PID=' ],
     killSignal: undefined },
  envPairs:
   [ 'PATH=/home/sagar/bin:/home/sagar/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
     'LC_MEASUREMENT=ne_NP',
     'XAUTHORITY=/home/sagar/.Xauthority',
     'XMODIFIERS=@im=ibus',
     'LC_TELEPHONE=ne_NP',
     'XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop',
     'GDMSESSION=ubuntu',
     'MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path',
     'LC_TIME=ne_NP',
     'GTK_IM_MODULE=ibus',
     'DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Sq2eReOVZr',
     'DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path',
     'XDG_CURRENT_DESKTOP=Unity',
     'LD_LIBRARY_PATH=/home/sagar/apps/WebStorm-172.3757.55/bin:',
     'UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/1000/1240',
     'QT4_IM_MODULE=xim',
     'LC_PAPER=ne_NP',
     'QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1',
     'LOGNAME=sagar',
     'JOB=unity-settings-daemon',
     'PWD=/tmp/1512313270685-0',
     'IM_CONFIG_PHASE=1',
     'LANGUAGE=en_US',
     'SHELL=/bin/bash',
     'LC_ADDRESS=ne_NP',
     'GIO_LAUNCHED_DESKTOP_FILE=/home/sagar/.local/share/applications/jetbrains-webstorm.desktop',
     'GTK2_MODULES=overlay-scrollbar',
     'INSTANCE=',
     'OLDPWD=/home/sagar/apps/WebStorm-172.3757.55/bin',
     'GNOME_DESKTOP_SESSION_ID=this-is-deprecated',
     'UPSTART_INSTANCE=',
     'GTK_MODULES=gail:atk-bridge:unity-gtk-module',
     'CLUTTER_IM_MODULE=xim',
     'XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0',
     'COMPIZ_BIN_PATH=/usr/bin/',
     'SESSIONTYPE=gnome-session',
     'XDG_SESSION_DESKTOP=ubuntu',
     'SHLVL=0',
     'LC_IDENTIFICATION=ne_NP',
     'LC_MONETARY=ne_NP',
     'COMPIZ_CONFIG_PROFILE=ubuntu',
     'QT_IM_MODULE=ibus',
     'UPSTART_JOB=unity7',
     'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64',
     'XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
     'LANG=en_US.UTF-8',
     'GNOME_KEYRING_CONTROL=',
     'XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0',
     'XDG_SESSION_ID=c2',
     'XDG_SESSION_TYPE=x11',
     'DISPLAY=:0',
     'LC_NAME=ne_NP',
     'GDM_LANG=en_US',
     'XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/sagar',
     'UPSTART_EVENTS=xsession started',
     'GPG_AGENT_INFO=/home/sagar/.gnupg/S.gpg-agent:0:1',
     'DESKTOP_SESSION=ubuntu',
     'SESSION=ubuntu',
     'USER=sagar',
     'XDG_MENU_PREFIX=gnome-',
     'GIO_LAUNCHED_DESKTOP_FILE_PID=20103',
     'QT_ACCESSIBILITY=1',
     'LC_NUMERIC=ne_NP',
     'SSH_AUTH_SOCK=/run/user/1000/keyring/ssh',
     'XDG_SEAT=seat0',
     'QT_QPA_PLATFORMTHEME=appmenu-qt5',
     'XDG_VTNR=7',
     'XDG_RUNTIME_DIR=/run/user/1000',
     'HOME=/home/sagar',
     'GNOME_KEYRING_PID=' ],
  stderr: null,
  stdout: null,
  pid: 20527,
  output: [ null, null, null ],
  signal: null,
  status: 127 }
Command `npm install --save --save-exact react-native` failed.
Done
</code>```

It says npm not found when I know it is there.

I have Node 8.9.1 & npm 5.5.1

答:
Looks like npm is not on your $PATH. Do you launch WebStorm from terminal, or from desktop/System menu? In the latter case, WebStorm only sees environment variables configured in .profile (login shell), but not in interactive shell configuration files (like ~/.bashrc). Plus, NVM alters interactive shell configuration files only during installation phase (https://github.com/creationix/nvm/blob/v0.28.0/install.sh#L126)

Possible workarounds:

Workaround 1: make required variables available in a login shell (i.e. for Bash, move them from .bashrc to .bash_profile or .profile).

Workaround 2: run IDE from a terminal

Workaround 3: edit WebStorm desktop launcher and set command to /bin/bash -l -i -c  "/path/to/webstorm.sh" (for bash)

Body:
The react-native-cli is generating the project fine when I use this command in terminal:

react-native init myapp

But for some reason WebStorm cannot create new React Native project. When I try I get this error:

/home/sagar/.nvm/versions/node/v8.9.1/bin/node
/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js init bookip
/bin/sh: 1: npm: not found
This will walk you through creating a new React Native project in /tmp/1512313270685-0/bookip
Installing react-native...
Consider installing yarn to make this faster: https://yarnpkg.com
{ Error: Command failed: npm install --save --save-exact react-native
    at checkExecSyncError (child_process.js:601:13)
    at execSync (child_process.js:641:13)
    at run (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:294:5)
    at createProject (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:249:3)
    at init (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:200:5)
    at Object.<anonymous> (/home/sagar/.nvm/versions/node/v8.9.1/lib/node_modules/react-native-cli/index.js:153:7)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
  error: null,
  cmd: 'npm install --save --save-exact react-native',
  file: '/bin/sh',
  args:
   [ '/bin/sh',
     '-c',
     'npm install --save --save-exact react-native' ],
  options:
   { stdio: [ [Object], [Object], [Object] ],
     shell: true,
     file: '/bin/sh',
     args:
      [ '/bin/sh',
        '-c',
        'npm install --save --save-exact react-native' ],
     envPairs:
      [ 'PATH=/home/sagar/bin:/home/sagar/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
        'LC_MEASUREMENT=ne_NP',
        'XAUTHORITY=/home/sagar/.Xauthority',
        'XMODIFIERS=@im=ibus',
        'LC_TELEPHONE=ne_NP',
        'XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop',
        'GDMSESSION=ubuntu',
        'MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path',
        'LC_TIME=ne_NP',
        'GTK_IM_MODULE=ibus',
        'DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Sq2eReOVZr',
        'DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path',
        'XDG_CURRENT_DESKTOP=Unity',
        'LD_LIBRARY_PATH=/home/sagar/apps/WebStorm-172.3757.55/bin:',
        'UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/1000/1240',
        'QT4_IM_MODULE=xim',
        'LC_PAPER=ne_NP',
        'QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1',
        'LOGNAME=sagar',
        'JOB=unity-settings-daemon',
        'PWD=/tmp/1512313270685-0',
        'IM_CONFIG_PHASE=1',
        'LANGUAGE=en_US',
        'SHELL=/bin/bash',
        'LC_ADDRESS=ne_NP',
        'GIO_LAUNCHED_DESKTOP_FILE=/home/sagar/.local/share/applications/jetbrains-webstorm.desktop',
        'GTK2_MODULES=overlay-scrollbar',
        'INSTANCE=',
        'OLDPWD=/home/sagar/apps/WebStorm-172.3757.55/bin',
        'GNOME_DESKTOP_SESSION_ID=this-is-deprecated',
        'UPSTART_INSTANCE=',
        'GTK_MODULES=gail:atk-bridge:unity-gtk-module',
        'CLUTTER_IM_MODULE=xim',
        'XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0',
        'COMPIZ_BIN_PATH=/usr/bin/',
        'SESSIONTYPE=gnome-session',
        'XDG_SESSION_DESKTOP=ubuntu',
        'SHLVL=0',
        'LC_IDENTIFICATION=ne_NP',
        'LC_MONETARY=ne_NP',
        'COMPIZ_CONFIG_PROFILE=ubuntu',
        'QT_IM_MODULE=ibus',
        'UPSTART_JOB=unity7',
        'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64',
        'XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
        'LANG=en_US.UTF-8',
        'GNOME_KEYRING_CONTROL=',
        'XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0',
        'XDG_SESSION_ID=c2',
        'XDG_SESSION_TYPE=x11',
        'DISPLAY=:0',
        'LC_NAME=ne_NP',
        'GDM_LANG=en_US',
        'XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/sagar',
        'UPSTART_EVENTS=xsession started',
        'GPG_AGENT_INFO=/home/sagar/.gnupg/S.gpg-agent:0:1',
        'DESKTOP_SESSION=ubuntu',
        'SESSION=ubuntu',
        'USER=sagar',
        'XDG_MENU_PREFIX=gnome-',
        'GIO_LAUNCHED_DESKTOP_FILE_PID=20103',
        'QT_ACCESSIBILITY=1',
        'LC_NUMERIC=ne_NP',
        'SSH_AUTH_SOCK=/run/user/1000/keyring/ssh',
        'XDG_SEAT=seat0',
        'QT_QPA_PLATFORMTHEME=appmenu-qt5',
        'XDG_VTNR=7',
        'XDG_RUNTIME_DIR=/run/user/1000',
        'HOME=/home/sagar',
        'GNOME_KEYRING_PID=' ],
     killSignal: undefined },
  envPairs:
   [ 'PATH=/home/sagar/bin:/home/sagar/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin',
     'LC_MEASUREMENT=ne_NP',
     'XAUTHORITY=/home/sagar/.Xauthority',
     'XMODIFIERS=@im=ibus',
     'LC_TELEPHONE=ne_NP',
     'XDG_DATA_DIRS=/usr/share/ubuntu:/usr/share/gnome:/usr/local/share:/usr/share:/var/lib/snapd/desktop:/var/lib/snapd/desktop',
     'GDMSESSION=ubuntu',
     'MANDATORY_PATH=/usr/share/gconf/ubuntu.mandatory.path',
     'LC_TIME=ne_NP',
     'GTK_IM_MODULE=ibus',
     'DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-Sq2eReOVZr',
     'DEFAULTS_PATH=/usr/share/gconf/ubuntu.default.path',
     'XDG_CURRENT_DESKTOP=Unity',
     'LD_LIBRARY_PATH=/home/sagar/apps/WebStorm-172.3757.55/bin:',
     'UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/1000/1240',
     'QT4_IM_MODULE=xim',
     'LC_PAPER=ne_NP',
     'QT_LINUX_ACCESSIBILITY_ALWAYS_ON=1',
     'LOGNAME=sagar',
     'JOB=unity-settings-daemon',
     'PWD=/tmp/1512313270685-0',
     'IM_CONFIG_PHASE=1',
     'LANGUAGE=en_US',
     'SHELL=/bin/bash',
     'LC_ADDRESS=ne_NP',
     'GIO_LAUNCHED_DESKTOP_FILE=/home/sagar/.local/share/applications/jetbrains-webstorm.desktop',
     'GTK2_MODULES=overlay-scrollbar',
     'INSTANCE=',
     'OLDPWD=/home/sagar/apps/WebStorm-172.3757.55/bin',
     'GNOME_DESKTOP_SESSION_ID=this-is-deprecated',
     'UPSTART_INSTANCE=',
     'GTK_MODULES=gail:atk-bridge:unity-gtk-module',
     'CLUTTER_IM_MODULE=xim',
     'XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0',
     'COMPIZ_BIN_PATH=/usr/bin/',
     'SESSIONTYPE=gnome-session',
     'XDG_SESSION_DESKTOP=ubuntu',
     'SHLVL=0',
     'LC_IDENTIFICATION=ne_NP',
     'LC_MONETARY=ne_NP',
     'COMPIZ_CONFIG_PROFILE=ubuntu',
     'QT_IM_MODULE=ibus',
     'UPSTART_JOB=unity7',
     'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64',
     'XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
     'LANG=en_US.UTF-8',
     'GNOME_KEYRING_CONTROL=',
     'XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0',
     'XDG_SESSION_ID=c2',
     'XDG_SESSION_TYPE=x11',
     'DISPLAY=:0',
     'LC_NAME=ne_NP',
     'GDM_LANG=en_US',
     'XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/sagar',
     'UPSTART_EVENTS=xsession started',
     'GPG_AGENT_INFO=/home/sagar/.gnupg/S.gpg-agent:0:1',
     'DESKTOP_SESSION=ubuntu',
     'SESSION=ubuntu',
     'USER=sagar',
     'XDG_MENU_PREFIX=gnome-',
     'GIO_LAUNCHED_DESKTOP_FILE_PID=20103',
     'QT_ACCESSIBILITY=1',
     'LC_NUMERIC=ne_NP',
     'SSH_AUTH_SOCK=/run/user/1000/keyring/ssh',
     'XDG_SEAT=seat0',
     'QT_QPA_PLATFORMTHEME=appmenu-qt5',
     'XDG_VTNR=7',
     'XDG_RUNTIME_DIR=/run/user/1000',
     'HOME=/home/sagar',
     'GNOME_KEYRING_PID=' ],
  stderr: null,
  stdout: null,
  pid: 20527,
  output: [ null, null, null ],
  signal: null,
  status: 127 }
Command `npm install --save --save-exact react-native` failed.
Done

It says npm not found when I know it is there.

I have Node 8.9.1 & npm 5.5.1


来源: stackexchange

问:
How to install missing function package of Octave in Mac?
I try to install the symbolic package for the Octave in the Mac, https://octave.sourceforge.io/symbolic/index.html, which path should be set?

More fundamental problem is that I follow the commands suggested by https://octave.sourceforge.io/ to install the symbolic package described as above, but the "pkg install" is always shown "pkg: command not found" in the command line. How to deal with it?

答:
I guess you entered the pgk install command in the osx shell. It has to be issued in octave. Start octave first, then run pgk install symbolic in octave´s command line.
To see installed package list user pkg list command.

ContentLicense: CC BY-SA 3.0


问:
How to pass default value to ajax while retrieving data from mysql in php
I need to get different fields from mysql database table in php using ajax.
I did that using the following code. But I need to get some default value when I load the page without clicking any select button.

My code is

Ajax Code

```<code><script>
    function langchange()
    {

        var langs= $('#langs').val();

       $.ajax({
        type:"POST",
        url:"ajax_lang_change.php",
        data:"id="+langs,
        success:function(value){
            var data=value.split("|_,_|";
             for(var i=0;i<data.length;i++){
            $("#cat_desc"+i).html(data[i]);
        }
    }
            });
    }

    </script>
</code>```

Php/html script

```<code><select name="sources" id="langs"  onchange="langchange();"  placeholder="English">
                                            <?php
                                            $language=mysqli_query($link,"select * from language_reference";
                                            while($lang=mysqli_fetch_array($language))
                                            {
                                            ?>
                                             <option value="<?php echo $lang['lang_id']; ?>" selected="selected"><?php echo $lang['lang_name']; ?>

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

Any help?? Thanks in advance..

答:
If i understand you right, then you can call the langchange() on page load and it will take currently selected option from the langs select element

$(window).load(function(){
    langchange();
});
```

ContentLicense: CC BY-SA 4.0

Body:
I need to get different fields from mysql database table in php using ajax.
I did that using the following code. But I need to get some default value when I load the page without clicking any select button.

My code is

Ajax Code

Php/html script

<select name="sources" id="langs"  onchange="langchange();"  placeholder="English">
                                            <?php
                                            $language=mysqli_query($link,"select * from language_reference";
                                            while($lang=mysqli_fetch_array($language))
                                            {
                                            ?>
                                             <option value="<?php echo $lang['lang_id']; ?>" selected="selected"><?php echo $lang['lang_name']; ?>

                                             </option>
                                            <?php } ?>
                                          </select>

Any help?? Thanks in advance..


问:
Autocompletion in Vim
I'm having trouble with autocompletion. How can I get a code suggestion while I'm typing?

I usually develop in PHP, Ruby, HTML, C and CSS.

答:
For PHP, Padawan with Deoplete are great solutions for having a robust PHP autocompletion in Neovim. I tried a lot of things and Padawan work like a charm!

For Vim you can use Neocomplete instead of Deoplete.

I wrote an article how to make a Vim PHP IDE if somebody is interested. Of course Padawan is part of it.

Title: Autocompletion in Vim


问:
How to get the values from form fields using dynamic created id or id as an variable using jQuery
I have created a small application where I dynamically created form elements and their id using jQuery. Later for form validation i need to get the fields of the the entries. I am able to get the values of the input fields but not able to the file, radio and other select fields. Here is the small code only for file

var x = 1;
function validate() {
  for(i=0;i<10;i++) {
    var filename = $('input[id="f'+ i +'"]').val().replace(/.*(\/|\\)/, '');
    alert(filename);
  }

  return false;
}

$(document).ready(function() {
  $("#fd").on("click",".but",function() {
    $(this).parent().remove();
  });

  $("#c").click(function() {
    var txt = "
<input type='file'id='f"+ x +"'><input type='text' id='t"+ x +"'><button class='but' id='d'> "+ x +" Button </button>
";
    x++;
    $("#fd").append(txt);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="c">Create Element</button>
<br> <br>
<form action="temp.php" onsubmit="return validate()" method="GET">
  <div id="fd">
    <button id="d">First Element</button>
    <input type="submit" name="submit">
  </div>
</form></code>```

How to retrieve data using dynamically created id for form elements.Consider for 10 elements
Thanks for the help.

答:
You can add the same class to all the inputs & use jQuery to get their values as below -

```<code>var inputs = $(".className");    // your class name
// iterate over the inputs any way you want
for(var i = 0; i < inputs.length; i++){
    alert($(inputs[i]).val());
}
</code>```

or this way -

```<code>var valueArray = $('.className').map(function() {
    return this.value;
}).get();
</code>```

Body:
I have created a small application where I dynamically created form elements and their id using jQuery. Later for form validation i need to get the fields of the the entries. I am able to get the values of the input fields but not able to the file, radio and other select fields. Here is the small code only for file

var x = 1;
function validate() {
  for(i=0;i<10;i++) {
    var filename = $('input[id="f'+ i +'"]').val().replace(/.*(\/|\\)/, '');
    alert(filename);
  }

  return false;
}

$(document).ready(function() {
  $("#fd").on("click",".but",function() {
    $(this).parent().remove();
  });

  $("#c").click(function() {
    var txt = "
<input type='file'id='f"+ x +"'><input type='text' id='t"+ x +"'><button class='but' id='d'> "+ x +" Button </button>
";
    x++;
    $("#fd").append(txt);
  });
});

<button id="c">Create Element</button>

<form action="temp.php" onsubmit="return validate()" method="GET">

    <button id="d">First Element</button>
    <input type="submit" name="submit">

</form>

How to retrieve data using dynamically created id for form elements.Consider for 10 elements
Thanks for the help.

Body:
You can add the same class to all the inputs & use jQuery to get their values as below -

var inputs = $(".className");    // your class name
// iterate over the inputs any way you want
for(var i = 0; i < inputs.length; i++){
    alert($(inputs[i]).val());
}

or this way -

var valueArray = $('.className').map(function() {
    return this.value;
}).get();


问:
How to update json file with PHP by using form in Angular 4?
So far I have set the form and service to read the php file which should do the editing of the json file. My current PHP file looks like this.</p>

```<code> if(empty($errors))
            {
            $postdata = file_get_contents("php://input");
            $request = json_decode($postdata);
            $name = $request->name;
            $designation = $request->designation;

            $current_data = file_get_contents('currency.json');
            $array_data = json_decode($current_data, true);
            $extra = array(
                  'name'            =>     $name,

                  'designation'     =>     $designation
            );
            $array_data[] = $extra;
            $final_data = json_encode($array_data);
            if(file_put_contents('currency.json', $final_data))
            {
                  $message = "<label class='text-success'>File Appended Success fully</p>";
            }
           }
           else
           {
                $error = 'JSON File not exits';
           }  `enter code here`

I will appreciate any effort for help.
</code>```

答:
Alright i have spent something like 12 hours and i have a solution for this:

```<code>       if(file_exists('currency.json'))
       {
        $jsonString = file_get_contents("php://input");

        date_default_timezone_set("Europe/Skopje");
        $todayDate= date("d.m.Y");

        $data = json_decode($jsonString);

        $eur=array(
              'currency' => 'EUR',
              'buy' => (double)$data->eurBuy,
              'sell' => (double)$data->eurSell,
              'flag' => "flag--europe"
        );
        $aud=array(
              'currency' => 'AUD',
              'buy' => (double)$data->audBuy,
              'sell' => (double)$data->audSell,
              'flag' => "flag--australia"
              );

        $currencies=array($eur, $aud);

        $obj = array('datum' => $todayDate,'values' => $currencies);

        $newJsonString = json_encode($obj);
        file_put_contents('currency.json', $newJsonString);
</code>```

}

Hopefully soon i will put demo project so i can help more precise in future to ease the developers. Greets!

Body:
So far I have set the form and service to read the php file which should do the editing of the json file. My current PHP file looks like this.

 if(empty($errors))
            {
            $postdata = file_get_contents("php://input");
            $request = json_decode($postdata);
            $name = $request->name;
            $designation = $request->designation;

            $current_data = file_get_contents('currency.json');
            $array_data = json_decode($current_data, true);
            $extra = array(
                  'name'            =>     $name,

                  'designation'     =>     $designation
            );
            $array_data[] = $extra;
            $final_data = json_encode($array_data);
            if(file_put_contents('currency.json', $final_data))
            {
                  $message = "File Appended Success fully
";
            }
           }
           else
           {
                $error = 'JSON File not exits';
           }  `enter code here`

I will appreciate any effort for help.

Body:
Alright i have spent something like 12 hours and i have a solution for this:

       if(file_exists('currency.json'))
       {
        $jsonString = file_get_contents("php://input");

        date_default_timezone_set("Europe/Skopje");
        $todayDate= date("d.m.Y");

        $data = json_decode($jsonString);

        $eur=array(
              'currency' => 'EUR',
              'buy' => (double)$data->eurBuy,
              'sell' => (double)$data->eurSell,
              'flag' => "flag--europe"
        );
        $aud=array(
              'currency' => 'AUD',
              'buy' => (double)$data->audBuy,
              'sell' => (double)$data->audSell,
              'flag' => "flag--australia"
              );

        $currencies=array($eur, $aud);

        $obj = array('datum' => $todayDate,'values' => $currencies);

        $newJsonString = json_encode($obj);
        file_put_contents('currency.json', $newJsonString);

}

Hopefully soon i will put demo project so i can help more precise in future to ease the developers. Greets!


问:
disable and enable click?
I have Splash Screen and button . i want if app install users click in start button and go to main activity . the problem after run app if app install go direct to main activity .. i want only check if app install enable click and if not install disable click  </p>

```<code>  Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.facebook.android");
    if(isAppInstalled) {
        start.setEnabled(true);

        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}
</code>```

答:
Change your code like this</p>

```<code>Button start = (Button) findViewById(R.id.bt_start);
boolean isAppInstalled = appInstalledOrNot("com.facebook.android");
if(isAppInstalled) {
    start.setEnabled(true);
} else {
    start.setEnabled(false);
}
start.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
    Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
    startActivity(Start_screen);
}
});
</code>```

Title: disable and enable click?

Body:
I have Splash Screen and button . i want if app install users click in start button and go to main activity . the problem after run app if app install go direct to main activity .. i want only check if app install enable click and if not install disable click

  Button start = (Button) findViewById(R.id.bt_start);
    boolean isAppInstalled = appInstalledOrNot("com.facebook.android");
    if(isAppInstalled) {
        start.setEnabled(true);

        Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(Start_screen);

    } else {

        start.setEnabled(false);

    }
}

private boolean appInstalledOrNot(String uri) {
    PackageManager pm = getPackageManager();
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException e) {
    }

    return false;
}

Body:
Change your code like this

Button start = (Button) findViewById(R.id.bt_start);
boolean isAppInstalled = appInstalledOrNot("com.facebook.android");
if(isAppInstalled) {
    start.setEnabled(true);
} else {
    start.setEnabled(false);
}
start.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
    Intent Start_screen = new Intent(SplashScreen.this, MainActivity.class);
    startActivity(Start_screen);
}
});


问:
.net schema validation
I am experiencing a problem with validating an xml file against a schema which was generated by svcutil. For the purpose of this question please see below a snippet of code which contains only a simplified XSD schema and the XML document that I am trying to validate:

```<code>Imports System.Xml.Schema

Module Main

    Dim errors As Boolean = False

    Sub Main()

        Try

            Dim xsdMarkup As XElement = _
              <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tns="http://zen/myservices" targetNamespace="http://zen/myservices">

                  <xs:element name="Car" type="tns:CarType"/>

                  <xs:complexType name="CarType">
                      <xs:sequence>
                          <xs:element name="Make" minOccurs="1" maxOccurs="1"/>
                          <xs:element name="Model" minOccurs="1" maxOccurs="1"/>
                      </xs:sequence>
                  </xs:complexType>

              </xs:schema>
            Dim schemas As XmlSchemaSet = New XmlSchemaSet()
            schemas.Add("http://zen/myservices", xsdMarkup.CreateReader)

            Dim doc1 As XDocument = _
             <?xml version='1.0'?>
             <Car>
                 <Makee>content1</Makee>
                 <Model>content1</Model>
             </Car>

            Console.WriteLine("Validating doc1")
            errors = False
            doc1.Validate(schemas, AddressOf XSDErrors)
            Console.WriteLine("doc1 {0}", IIf(errors = True, "did not validate", "validated"))

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

        Console.WriteLine("Hit <ENTER> to exit...")
        Console.ReadKey()

    End Sub

    Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
        Console.WriteLine("{0}", e.Message)
        errors = True
    End Sub

End Module
</code>```

The validation in this particular case should fail (the 'Make' element has been misspelled). Interestingly enough though it passes.

Any ideas what am I missing in this code?

Your help is appreciated.

Zen

答:
All set. I resolved the issue myself. I had accidentally left out the namespaces definition in the XML being validated:

```<code><?xml version='1.0'?>
<Car>
    <Makee>content1</Makee>
    <Model>content1</Model>
</Car>
</code>```

should have been:

```<code><?xml version='1.0'?>
<tns:Car xmlns:tns="http://zen/myservices">
    <Makee>content1</Makee>
    <Model>content1</Model>
</tns:Car>
</code>```

Validation is failing now as expected.

Zen

Title: .net schema validation

Body:
I am experiencing a problem with validating an xml file against a schema which was generated by svcutil. For the purpose of this question please see below a snippet of code which contains only a simplified XSD schema and the XML document that I am trying to validate:

Imports System.Xml.Schema

Module Main

    Dim errors As Boolean = False

    Sub Main()

        Try

            Dim xsdMarkup As XElement = _
              <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:tns="http://zen/myservices" targetNamespace="http://zen/myservices">

                  <xs:element name="Car" type="tns:CarType"/>

                  <xs:complexType name="CarType">
                      <xs:sequence>
                          <xs:element name="Make" minOccurs="1" maxOccurs="1"/>
                          <xs:element name="Model" minOccurs="1" maxOccurs="1"/>
                      </xs:sequence>
                  </xs:complexType>

              </xs:schema>
            Dim schemas As XmlSchemaSet = New XmlSchemaSet()
            schemas.Add("http://zen/myservices", xsdMarkup.CreateReader)

            Dim doc1 As XDocument = _
             <?xml version='1.0'?>
             <Car>
                 <Makee>content1</Makee>
                 <Model>content1</Model>
             </Car>

            Console.WriteLine("Validating doc1")
            errors = False
            doc1.Validate(schemas, AddressOf XSDErrors)
            Console.WriteLine("doc1 {0}", IIf(errors = True, "did not validate", "validated"))

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

        Console.WriteLine("Hit <ENTER> to exit...")
        Console.ReadKey()

    End Sub

    Private Sub XSDErrors(ByVal o As Object, ByVal e As ValidationEventArgs)
        Console.WriteLine("{0}", e.Message)
        errors = True
    End Sub

End Module

The validation in this particular case should fail (the 'Make' element has been misspelled). Interestingly enough though it passes.

Any ideas what am I missing in this code?

Your help is appreciated.

Zen

Body:
All set. I resolved the issue myself. I had accidentally left out the namespaces definition in the XML being validated:

<?xml version='1.0'?>
<Car>
    <Makee>content1</Makee>
    <Model>content1</Model>
</Car>

should have been:

<?xml version='1.0'?>
<tns:Car xmlns:tns="http://zen/myservices">
    <Makee>content1</Makee>
    <Model>content1</Model>
</tns:Car>

Validation is failing now as expected.

Zen

ContentLicense: CC BY-SA 2.5


问:
Xcode 8.0 Command /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
When I compile my code on Xcode Version 8.0 beta 4 (8S188o) I get this single error bringing the compilation to failure:

Command
  /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc
  failed with exit code 1

I tried to clean the project and wipe the derived folder but that did not change things.
What is it and how may I know more about it?

When I try to compile on the terminal the error being reported is:

Invalid bitcast\n  %.asUnsubstituted = bitcast %swift.error* %13 to
  i2, !dbg !438\nLLVM ERROR: Broken function found, compilation
  aborted!\n

答:
I faced this issue when I resolved git conflict for the project file, which was for adding and removing some files.

What I found out is Xcode creates the folder named folder named "Recovered References", just search this from bottom left search option from Xcode and delete it. After you delete it you will only get an error for missing files. Resolve that by adding files again by right-clicking and selecting add files option. Once you are done with it project compiles with no error.


问:
How to differentiate if the command was incorrect or the result is empty for nodejs child_process.execSync
```<code>try {
    var output = child_process.execSync(cmd);
} catch (ex) {
    return 0
}
return output.toString()
</code>```

so I want to differentiate the cases when cmd="lx -a", which is a incorrect command and the case when cmd="ls /home/dir", and /home/dir is a empty directory, so it will generate nothing or empty string.
When I tried it, it seems both cases will be caught by nodejs as exception.

How to differentiate? I thought I can write code like

```<code>if (ex.message.indexOf("not found") >= 0)
</code>```

But it will only cover one case when the command itself is incorrect, what if the parameter is wrong? Or other situations when the error message does not include "not found"?

答: try to use switch case for your positive cases and use the default for any other values of cmd and in default, you can return your custom values.</p>

Body:
try {
    var output = child_process.execSync(cmd);
} catch (ex) {
    return 0
}
return output.toString()

so I want to differentiate the cases when cmd="lx -a", which is a incorrect command and the case when cmd="ls /home/dir", and /home/dir is a empty directory, so it will generate nothing or empty string.
When I tried it, it seems both cases will be caught by nodejs as exception.

How to differentiate? I thought I can write code like

if (ex.message.indexOf("not found") >= 0)

But it will only cover one case when the command itself is incorrect, what if the parameter is wrong? Or other situations when the error message does not include "not found"?


问:
Auto Increment field in Composer
Is there any auto_increment field type is available when creating an Asset instance.
For example, Asset id should be autogenerated field and should be created at runtime, instead of mentioning the value at the application level.
I can achieve it by creating a transaction processor function to check the list of asset and add 1 to increment as an alternative.

Looking for new a feature which will help multiple developers while building an application.

Regards,

Pradeep P

答: the best practice is to generate IDs client side, and send them in via the transaction. You can't for example, be certain that the transaction processor function would guarantee the same number (ID) each time when evaluated on endorsing peers that look at transaction proposals, let alone achieving the same deterministic value when it comes to sending the read/write (results) set back to the client application. The whole point is that the transaction proposal would yield the same asset ID EVERY time (as part of that - by putting it in a TP function, that would not be guaranteed EVERY time).  Rather, you would send in the auto-increment value from the client side,  for something that is ultimately, the responsibility of the client side. </p>

Title: Auto Increment field in Composer


问:
How to slice different verb tenses word ending with -ed,-ing in a list?

So here is the sample list:

[work,worked,working,play,works,lotus]

I want to slice the -ed,-ing,-s form of work,the result should be like this:
 [work,play,lotus]

So,how can i achieve that with pure python code since the NLTK approach seemed to be inaccurate?

答:
You can use the below code:

Code:

```<code>from nltk.stem import PorterStemmer
stemmer = PorterStemmer()

List = ['work','worked','working','play']
List = [stemmer.stem(token) for token in List]
List1=[]
for token in List:
    if token not in List1:
        List1.append(token)
</code>```

Output:

```<code>['work', 'play']
</code>```

Body:
You can use the below code:

Code:

from nltk.stem import PorterStemmer
stemmer = PorterStemmer()

List = ['work','worked','working','play']
List = [stemmer.stem(token) for token in List]
List1=[]
for token in List:
    if token not in List1:
        List1.append(token)

Output:

['work', 'play']


问:
Set keyboard to use only a specific language without let to use change language button. objective c
I try to obligate user to use only a specific language (my device language) and block the keyboard on this specific language. without allow him to change the language with the button.
what I did till now is to add a custom textfield:

```<code>@implementation customTextField

- (NSString *)langFromLocale:(NSString *)locale {
   NSRange r = [locale rangeOfString:@"_"];
   if (r.length == 0) r.location = locale.length;
     NSRange r2 = [locale rangeOfString:@"-"];
   if (r2.length == 0) r2.location = locale.length;
     return [[locale substringToIndex:MIN(r.location, r2.location)]
     lowercaseString];
}

- (UITextInputMode *) textInputMode {
   NSString *myLanguage = [[NSLocale preferredLanguages]
   objectAtIndex:0];
   for (UITextInputMode *tim in [UITextInputMode activeInputModes]) {
       if ([[self langFromLocale:myLanguage ] isEqualToString:[self
       langFromLocale:tim.primaryLanguage]]) return tim;
    }
    return [super textInputMode];
}

@end
</code>```

this allowed me to set the language of keyboard, but when I wanted to remove the change language button I got an answer to change the keyboard from default to ascii. therefore, now the language is usually on english!!!!

waiting for an answer!!
thanx!!

答: this option is not possible in IOS keyboard, the button is default in this mode.</p>

Body:
I try to obligate user to use only a specific language (my device language) and block the keyboard on this specific language. without allow him to change the language with the button.
what I did till now is to add a custom textfield:

@implementation customTextField

- (NSString *)langFromLocale:(NSString *)locale {
   NSRange r = [locale rangeOfString:@"_"];
   if (r.length == 0) r.location = locale.length;
     NSRange r2 = [locale rangeOfString:@"-"];
   if (r2.length == 0) r2.location = locale.length;
     return [[locale substringToIndex:MIN(r.location, r2.location)]
     lowercaseString];
}

- (UITextInputMode *) textInputMode {
   NSString *myLanguage = [[NSLocale preferredLanguages]
   objectAtIndex:0];
   for (UITextInputMode *tim in [UITextInputMode activeInputModes]) {
       if ([[self langFromLocale:myLanguage ] isEqualToString:[self
       langFromLocale:tim.primaryLanguage]]) return tim;
    }
    return [super textInputMode];
}

@end

this allowed me to set the language of keyboard, but when I wanted to remove the change language button I got an answer to change the keyboard from default to ascii. therefore, now the language is usually on english!!!!

waiting for an answer!!
thanx!!


问:
charset=utf-8 in @Consumes is not working
I'm using Jersey 2.16. For rest interface, I need to accept 'application/xml' and produce 'application/xml' with charset=utf-8. My code is,

```<code>@POST
@Produces("application/xml; charset=utf-8")
@Consumes("application/xml; charset=utf-8")
public String process(String request) {
 ...
return response;
</code>```

}

Here, when I send request from Client, I set Content-Type as application/xml;charset=iso-8859-1 which I expect server to throw some error as it does not match with utf-8. But this does not happens. However the charset=utf-8 is set in response. Is this correct way of checking charset for HTTP Request?

答:
You could inject directly with @HeaderParam and then validate the charset in your code. </p>

```<code>public String process(@HeaderParam("Accept-Charset") String charset,  String request) {

 if (charset.equalsIgnoreCase ("utf-8"))
 {
     // do something
 }
 else
 {
   // update your response.
 }
 ...
return response;
</code>```

Body:
I'm using Jersey 2.16. For rest interface, I need to accept 'application/xml' and produce 'application/xml' with charset=utf-8. My code is,

@POST
@Produces("application/xml; charset=utf-8")
@Consumes("application/xml; charset=utf-8")
public String process(String request) {
 ...
return response;

}

Here, when I send request from Client, I set Content-Type as application/xml;charset=iso-8859-1 which I expect server to throw some error as it does not match with utf-8. But this does not happens. However the charset=utf-8 is set in response. Is this correct way of checking charset for HTTP Request?

Body:
You could inject directly with @HeaderParam and then validate the charset in your code.

public String process(@HeaderParam("Accept-Charset") String charset,  String request) {

 if (charset.equalsIgnoreCase ("utf-8"))
 {
     // do something
 }
 else
 {
   // update your response.
 }
 ...
return response;


问:
Where is modify_ldt?
I am looking for the modify_ldt function (or constant for syscall) on ubuntu, but I can't find it's declaration anywhere. It's not in sys/types.h (as the man page suggests), nor in linux/ldt.h (doesn't exist) or linux/unistd.h as says here.

Where is it located?

答: Try using __NR_modify_ldt for the syscall constant.  On my system it's defined in asm/unistd_64.h, which is included from unistd.h

Title: Where is modify_ldt?


问: How to refresh the page

答:
JavaScript provides a handy function called reload on to the location object, you can use it like this:</p>

```<code>window.location.reload()
</code>```

Title: How to refresh the page

Body:
JavaScript provides a handy function called reload on to the location object, you can use it like this:

window.location.reload()


问:
Cannot open SQL editor on macOS High Sierra
Since updating to macOS High Sierra, I have not been able to open the SQL Editor on MySQL Workbench.

When I try to connect to the database, as usual, I'm given the following prompt:

However, after a few seconds, it simply disappears. I'm given no error or any indication from the application that anything went wrong. I've tried redownloading the application, but I'm getting the same result.

edit:
I tried using previous versions of Workbench, and it works perfectly on version 2.6.5.

答:
Version 6.3.10 has been released. Fixed a bug in MacOS HighSierra.

Download here


问:
Does function definition order matter?
In the script below, does the order in which items are declared matter?

For example, if the add_action points to a function that has not yet been defined? Does it matter or should the function declaration always precede any code in which its called?

```<code>add_action('load-categories.php', 'my_admin_init');
function my_admin_init(){
//do something
}
</code>```

答:
As per my personal experience, In some special cases (Like, passing array's in function or function inside a function and so on). It's best option to define the function above the call. Because of this sometimes neither function works nor PHP throw an error.

In normal php functions, it doesn't matter. You can use both of the types.

Title: Does function definition order matter?

Body:
In the script below, does the order in which items are declared matter?

For example, if the add_action points to a function that has not yet been defined? Does it matter or should the function declaration always precede any code in which its called?

add_action('load-categories.php', 'my_admin_init');
function my_admin_init(){
//do something
}


问:
App not installed error with the app already installed from playstore
I have the app installed from playstore and tried installing the release apk of same app in the device by increasing the version code .
App not installed error occuring . If i uninstall the already installed package its working fine but i need to update the existing package wat i have .</p>

答: Its ok. Because you tries to install new release with different no. and package is  same. So , there is lots of conflict to directly install apk.</p>


问:
Reload Data table with new parameter in ajax call
I have added a datatable with an AJAX call in my application. Its working fine, but I need to add some custom filters.

Here is my code

```<code><table id="mydatatable">
    <thead>
        <tr>
            <td>Name</td>
            <td>Age</td>
            <td>Email</td>
        </tr>
    </thead>
</table>
<script>
    $("#mydatatable").DataTable({
        "ajax": {
            url: "ajax.php?action=datatable",
            "type": 'POST',
        },
        "order": [[2, "desc"]],
    });
</script>
</code>```

now I have added custom select box for age >15, >25, >35 on that select box change I need to make AJAX call and refresh the datatable

答:
You can supply data from the select box to your ajax.php script by using ajax.data option. Then use ajax.reload() API method to reload the data when value of select box changes.

Change your ajax.php to filter data based on supplied age request parameter.

For example:

$("#mydatatable").DataTable({
    "ajax": {
        "url": "ajax.php?action=datatable",
        "data": function(data){
           data.age = $('#select-age').val();
        },
        "type": 'POST',
    },
    "order": [[2, "desc"]],
});

// Handle event when select box value changes
$('#select-age').on('change', function(){
   // Reload data
   $("#mydatatable").DataTable().ajax.reload();
});
```

Body:
I have added a datatable with an AJAX call in my application. Its working fine, but I need to add some custom filters.

Here is my code

            Name
            Age
            Email

now I have added custom select box for age >15, >25, >35 on that select box change I need to make AJAX call and refresh the datatable


问:
border and outline overlapping in Internet Explorer
On focus i am adding an outline to a button but the outline is overlapping with the border in Internet Explorer.This is working fine in Chrome.

Code:

```<code> <div id="right" role="button" tabindex="0">
    <div class="rightcontent">
        test
     </div>
 </div>

#right {
height:39px;
dispaly:inline;
width:46px;
}

.rightcontent {
padding: 10px;
width:26px;
height:18px;
border-bottom :1px solid #000;
position:relative;
}
</code>```

Link: http://jsfiddle.net/yhmcLgus/5/

Is this an Internet Explorer bug? Shouldn't outline be outside of elements dimensions?

Please suggest what can be done without changing the height of the element.

答:
outline-offset is one of the methods to set outline outside of an element. But it is not supported well in Internet Explorer. But by using an alternative solution of pseudoelement you can achieve the desired result.

```<code><div id="right" role="button" tabindex="0">
  <div class="rightcontent">
    test
  </div>
</div>

#right {
 height:39px;
 dispaly:inline;
 width:46px;
}

.rightcontent {
  padding: 10px;
  width:26px;
  height:18px;
  border-bottom :1px solid #000;
  position:relative;
}

.rightcontent::after {
  content: "";
  position: absolute;
  top: -2px;
  left: 0px;
  display: block;
  width: 46px;
  height: 41px;
  border: 1px solid red;
}
</code>```

Here is the working Fiddle

Body:
On focus i am adding an outline to a button but the outline is overlapping with the border in Internet Explorer.This is working fine in Chrome.

Code:

        test

#right {
height:39px;
dispaly:inline;
width:46px;
}

.rightcontent {
padding: 10px;
width:26px;
height:18px;
border-bottom :1px solid #000;
position:relative;
}

Link: http://jsfiddle.net/yhmcLgus/5/

Is this an Internet Explorer bug? Shouldn't outline be outside of elements dimensions?

Please suggest what can be done without changing the height of the element.

Body:
outline-offset is one of the methods to set outline outside of an element. But it is not supported well in Internet Explorer. But by using an alternative solution of pseudoelement you can achieve the desired result.

<div id="right" role="button" tabindex="0">
  <div class="rightcontent">
    test
  </div>
</div>

#right {
 height:39px;
 dispaly:inline;
 width:46px;
}

.rightcontent {
  padding: 10px;
  width:26px;
  height:18px;
  border-bottom :1px solid #000;
  position:relative;
}

.rightcontent::after {
  content: "";
  position: absolute;
  top: -2px;
  left: 0px;
  display: block;
  width: 46px;
  height: 41px;
  border: 1px solid red;
}

Here is the working Fiddle


问:
How do I programmatically access data about my database?
I'd like to access the list of tables and for each table report number of rows, disk space used, etc. It would be nice to get these details at the database level, too.

How do I do this programmatically?

答:
Create a SqlConnection to your database and open the connection.

```<code>SqlConnection conn = new SqlConnection("Data Source=Servername;Initial Catalog=Marketing;Integrated Security=SSPI");
conn.Open();
</code>```

Create a SqlCommand and assign the CommandText to the value of SQL you require.

```<code>SqlCommand cmd = new SqlCommand("PLACE SQL HERE", conn);
</code>```

Tables and number of rows:

```<code>SELECT
    [TableName] = so.name,
    [RowCount] = MAX(si.rows)
FROM
    sysobjects so,
    sysindexes si
WHERE
    so.xtype = 'U'
    AND
    si.id = OBJECT_ID(so.name)
GROUP BY
    so.name
ORDER BY
    2 DESC
</code>```

Space used:

```<code>EXEC sp_spaceused 'tablename'
</code>```

Body:
Create a SqlConnection to your database and open the connection.

SqlConnection conn = new SqlConnection("Data Source=Servername;Initial Catalog=Marketing;Integrated Security=SSPI");
conn.Open();

Create a SqlCommand and assign the CommandText to the value of SQL you require.

SqlCommand cmd = new SqlCommand("PLACE SQL HERE", conn);

Tables and number of rows:

SELECT
    [TableName] = so.name,
    [RowCount] = MAX(si.rows)
FROM
    sysobjects so,
    sysindexes si
WHERE
    so.xtype = 'U'
    AND
    si.id = OBJECT_ID(so.name)
GROUP BY
    so.name
ORDER BY
    2 DESC

Space used:

EXEC sp_spaceused 'tablename'


问:
HTML5 Audio Player : Taking from Wayback Machine?
Currently I am trying to grab the audio player of a dead website from Wayback Machine which is a little dated now. ( Wayback Link Here )

I've included this portion into my own website

```<code><section class="player clearfix">
    <div class="player-init preload" data-file="http://example.com/mp3embed-fsszlphd4yu9.mp3"></div>
</section>
</code>```

which from what I'm seeing should display this on our webpage

```<code><section class="player clearfix">
<div class="audioplayer audioplayer-stopped"><div class="player-init preload" data-file="http://example.com/mp3embed-85r10u3gp28b.mp3"><audio src="http://example.com/mp3embed-85r10u3gp28b.mp3" style="width: 0px; height: 0px; visibility: hidden;"></audio></div><div class="audioplayer-playpause"><a href="#"><span class="fa fa-play"></span></a></div><div class="audioplayer-time audioplayer-time-current">00:00</div><div class="audioplayer-bar"><div class="audioplayer-bar-loaded"></div><div class="audioplayer-bar-played"></div></div><div class="audioplayer-time audioplayer-time-duration">00:00</div><div class="audioplayer-volume"><div class="audioplayer-volume-button"><a href="#"><span class="fa fa-volume-up"></span></a></div><div class="audioplayer-volume-adjust"><div><div style="height: 100%;"></div></div></div></div></div>
</section>
</code>```

But on my web page it's displaying nothing, at all even when I include all their old Javascript files, and style sheets on a blank page completely.

答:
HTML5 audio player with display from Wayback Machine with my custom js.

Work

Play/pause button

Duration / current time

Clickable seeker

Volume (3 steps)

Player = {
  maineleSelector : 'section.player',
  $mainEle : null,
  $audioEle : null,
  isPlaying : false,
  fnInit : function() {
    var self = this;
    self.$mainEle = $(self.maineleSelector);
    self.$audioEle = self.$mainEle.find('audio');
    // Toggle play/pause
    self.$mainEle.find('.audioplayer-playpause').on('click',function(){
      // Playing flag
      self.isPlaying = !self.isPlaying;
      // Play/Pause icon
      self._fnUpdatePlayPause();
      // Play/Pause action
      if (self.isPlaying){ self.$audioEle.get(0).play(); } else { self.$audioEle.get(0).pause(); }
    });
    // Timer seekable
    self.$mainEle.find('.audioplayer-bar').on('click', function(e){
      var percent = e.offsetX / this.offsetWidth;
      self.$audioEle.get(0).currentTime = percent * self.$audioEle.get(0).duration;
      self._fnUpdateTime(percent / 100);
    });
    // Audio play
    self.$audioEle.on('play', function(e) {
      self._fnUpdateDuration(e.target.duration);
    });
    // Audio end
    self.$audioEle.on('ended', function(e) {
        self.isPlaying = false;
        self._fnUpdateTime(e.target.currentTime, e.target.duration);
        self._fnUpdatePlayPause();
    });
    // Timer update
    self.$audioEle.on('timeupdate', function(e) {
        self._fnUpdateTime(e.target.currentTime, e.target.duration);
    });
    // Volume update
    self.$mainEle.find('.audioplayer-volume-button').on('click', function(e){
      if (self.$audioEle.get(0).volume >= 0.99) {
        self.$audioEle.get(0).volume = 0.33;
      } else {
        self.$audioEle.get(0).volume += 0.33;
      }
      self._fnUpdateVolume(self.$audioEle.get(0).volume * 100);
    });
  },
  // Play/Pause icon
  _fnUpdatePlayPause : function(){
    this.$mainEle.find('.audioplayer-playpause span')
      .addClass(this.isPlaying ? 'fa-pause' : 'fa-play')
      .removeClass(this.isPlaying ? 'fa-play' : 'fa-pause');
  },
  // Update Length
  _fnUpdateDuration : function(duration){
    this.$mainEle.find('.audioplayer-time-duration').text(this._fnFormatToMMSS(duration));
  },
  // Update Time
  _fnUpdateTime : function(time, duration){
    this.$mainEle.find('.audioplayer-time-current').text(this._fnFormatToMMSS(time));
    this.$mainEle.find('.audioplayer-bar-played').width(Math.round((100 * time) / duration) + '%');
  },
  // Update Volume
  _fnUpdateVolume : function(volumePC){
    var volumneIconEle = this.$mainEle.find('.audioplayer-volume-button span');
    if (volumePC <= 33) {
      volumneIconEle.removeClass().addClass("fa fa-volume-off");
    } else if (volumePC <= 66) {
      volumneIconEle.removeClass().addClass("fa fa-volume-down");
    } else {
      volumneIconEle.removeClass().addClass("fa fa-volume-up");
    }
  },
  _fnFormatToMMSS : function (timeMilisec) {
    var sec_num = Math.round(timeMilisec);
    var minutes = Math.floor((sec_num / 60));
    var seconds = sec_num - (minutes * 60);

    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return minutes+':'+seconds;
  }
}

$( document ).ready(function() {
  Player.fnInit();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>section.player {
    margin-top: 25px;
}

user agent stylesheet
article, aside, footer, header, hgroup, main, nav, section {
    display: block;
}

.audioplayer {
    background: #e2e2e2;
    width: calc(100% - 2px);
    height: 50px;
    border: 1px solid #d9d9d9;
    position: relative;
}

div {
    display: block;
}

.audioplayer-playpause {
    color: #858585;
    width: 17px;
    height: 100%;
    margin-left: 29px;
    font-size: 20px;
    line-height: 50px;
    text-align: center;
    float: left;
    display: block;
}

.audioplayer-time.audioplayer-time-current {
    margin-left: 20px;
    float: left;
}

.audioplayer-time {
    color: #898989;
    width: 40px;
    height: 100%;
    line-height: 50px;
    font-weight: bold;
    font-size: 12px;
    text-align: center;
}

.audioplayer-time.audioplayer-time-duration {
    margin-right: 6px;
    float: left;
}

.audioplayer-bar {
    background: #cccccc;
    width: calc(100% - 238px);
    height: 6px;
    margin: 21px 15px 0px 15px;
    cursor: pointer;
    position: relative;
    float: left;
}

.audioplayer-bar-played {
    display: block;
    position: relative;
    height: 100%;
    padding: 0;
    background: #0082b2;
    width: 0px;
}

.audioplayer-volume {
    color: #858585;
    width: 20px;
    height: 100%;
    margin-left: 16px;
    line-height: 50px;
    font-size: 20px;
    float: left;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

        <audio src="http://techslides.com/demos/samples/sample.mp3" style="width: 0px; height: 0px; visibility: hidden;"></audio>

00:00

00:00

```

Body:
Currently I am trying to grab the audio player of a dead website from Wayback Machine which is a little dated now. ( Wayback Link Here )

I've included this portion into my own website

which from what I'm seeing should display this on our webpage

<audio src="http://example.com/mp3embed-85r10u3gp28b.mp3" style="width: 0px; height: 0px; visibility: hidden;"></audio>

00:00

00:00

But on my web page it's displaying nothing, at all even when I include all their old Javascript files, and style sheets on a blank page completely.

Body:
HTML5 audio player with display from Wayback Machine with my custom js.

Work

Play/pause button

Duration / current time

Clickable seeker

Volume (3 steps)

Player = {
  maineleSelector : 'section.player',
  $mainEle : null,
  $audioEle : null,
  isPlaying : false,
  fnInit : function() {
    var self = this;
    self.$mainEle = $(self.maineleSelector);
    self.$audioEle = self.$mainEle.find('audio');
    // Toggle play/pause
    self.$mainEle.find('.audioplayer-playpause').on('click',function(){
      // Playing flag
      self.isPlaying = !self.isPlaying;
      // Play/Pause icon
      self._fnUpdatePlayPause();
      // Play/Pause action
      if (self.isPlaying){ self.$audioEle.get(0).play(); } else { self.$audioEle.get(0).pause(); }
    });
    // Timer seekable
    self.$mainEle.find('.audioplayer-bar').on('click', function(e){
      var percent = e.offsetX / this.offsetWidth;
      self.$audioEle.get(0).currentTime = percent * self.$audioEle.get(0).duration;
      self._fnUpdateTime(percent / 100);
    });
    // Audio play
    self.$audioEle.on('play', function(e) {
      self._fnUpdateDuration(e.target.duration);
    });
    // Audio end
    self.$audioEle.on('ended', function(e) {
        self.isPlaying = false;
        self._fnUpdateTime(e.target.currentTime, e.target.duration);
        self._fnUpdatePlayPause();
    });
    // Timer update
    self.$audioEle.on('timeupdate', function(e) {
        self._fnUpdateTime(e.target.currentTime, e.target.duration);
    });
    // Volume update
    self.$mainEle.find('.audioplayer-volume-button').on('click', function(e){
      if (self.$audioEle.get(0).volume >= 0.99) {
        self.$audioEle.get(0).volume = 0.33;
      } else {
        self.$audioEle.get(0).volume += 0.33;
      }
      self._fnUpdateVolume(self.$audioEle.get(0).volume * 100);
    });
  },
  // Play/Pause icon
  _fnUpdatePlayPause : function(){
    this.$mainEle.find('.audioplayer-playpause span')
      .addClass(this.isPlaying ? 'fa-pause' : 'fa-play')
      .removeClass(this.isPlaying ? 'fa-play' : 'fa-pause');
  },
  // Update Length
  _fnUpdateDuration : function(duration){
    this.$mainEle.find('.audioplayer-time-duration').text(this._fnFormatToMMSS(duration));
  },
  // Update Time
  _fnUpdateTime : function(time, duration){
    this.$mainEle.find('.audioplayer-time-current').text(this._fnFormatToMMSS(time));
    this.$mainEle.find('.audioplayer-bar-played').width(Math.round((100 * time) / duration) + '%');
  },
  // Update Volume
  _fnUpdateVolume : function(volumePC){
    var volumneIconEle = this.$mainEle.find('.audioplayer-volume-button span');
    if (volumePC <= 33) {
      volumneIconEle.removeClass().addClass("fa fa-volume-off");
    } else if (volumePC <= 66) {
      volumneIconEle.removeClass().addClass("fa fa-volume-down");
    } else {
      volumneIconEle.removeClass().addClass("fa fa-volume-up");
    }
  },
  _fnFormatToMMSS : function (timeMilisec) {
    var sec_num = Math.round(timeMilisec);
    var minutes = Math.floor((sec_num / 60));
    var seconds = sec_num - (minutes * 60);

    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return minutes+':'+seconds;
  }
}

$( document ).ready(function() {
  Player.fnInit();
});

section.player {
    margin-top: 25px;
}

user agent stylesheet
article, aside, footer, header, hgroup, main, nav, section {
    display: block;
}

.audioplayer {
    background: #e2e2e2;
    width: calc(100% - 2px);
    height: 50px;
    border: 1px solid #d9d9d9;
    position: relative;
}

div {
    display: block;
}

.audioplayer-playpause {
    color: #858585;
    width: 17px;
    height: 100%;
    margin-left: 29px;
    font-size: 20px;
    line-height: 50px;
    text-align: center;
    float: left;
    display: block;
}

.audioplayer-time.audioplayer-time-current {
    margin-left: 20px;
    float: left;
}

.audioplayer-time {
    color: #898989;
    width: 40px;
    height: 100%;
    line-height: 50px;
    font-weight: bold;
    font-size: 12px;
    text-align: center;
}

.audioplayer-time.audioplayer-time-duration {
    margin-right: 6px;
    float: left;
}

.audioplayer-bar {
    background: #cccccc;
    width: calc(100% - 238px);
    height: 6px;
    margin: 21px 15px 0px 15px;
    cursor: pointer;
    position: relative;
    float: left;
}

.audioplayer-bar-played {
    display: block;
    position: relative;
    height: 100%;
    padding: 0;
    background: #0082b2;
    width: 0px;
}

.audioplayer-volume {
    color: #858585;
    width: 20px;
    height: 100%;
    margin-left: 16px;
    line-height: 50px;
    font-size: 20px;
    float: left;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<section class="player clearfix">
    <div class="audioplayer audioplayer-stopped">
      <div class="player-init preload">
        <audio src="http://techslides.com/demos/samples/sample.mp3" style="width: 0px; height: 0px; visibility: hidden;"></audio>
      </div>
      <div class="audioplayer-playpause">
        <a href="#"><span class="fa fa-play"></span></a>
      </div>
      <div class="audioplayer-time audioplayer-time-current">00:00</div>
      <div class="audioplayer-bar">
        <div class="audioplayer-bar-played"></div>
      </div>
      <div class="audioplayer-time audioplayer-time-duration">00:00</div>
      <div class="audioplayer-volume">
        <div class="audioplayer-volume-button">
          <a href="#"><span class="fa fa-volume-up"></span></a>
        </div>
        <div class="audioplayer-volume-adjust">
          <div>
            <div style="height: 100%;"></div>
          </div>
        </div>
      </div>
    </div>
</section>


问:
AngularJS pass string to function by ng-click
I am trying to pass a string to a function through ng click, here's an example

HTML

 ng-click="test(STRING_TO_PASS)"

Controller

$scope.test = function(stringOne, stringTwo){
    valueOne = test(STRING_TO_PASS);
}

Edit -

Turns out I was thinking about this the wrong way... not really sure why I asked it, sorry guys!

答:
Your controller function should accept only 1 parameter</p>

```<code>$scope.test = function(stringOne){
    valueOne =  stringOne;
}
</code>```

Body:
Your controller function should accept only 1 parameter

$scope.test = function(stringOne){
    valueOne =  stringOne;
}


问:
Filter elements of array if contained in other
I have two arrays like below format,

```<code>this.originalArray = [{
    id: 10,
    name: 'a',
    roleInfo: [{
        roleID: 5,
        roleName: 'USER'
    }]
},
{
    id: 20,
    name: 'b',
    roleInfo: [{
        roleID: 5,
        roleName: 'Admin',
    }]
 },
 {
     id: 30,
     name: 'c',
     roleInfo: [{
         roleID: 5,
         roleName: 'Support',
     }]
 }]

this.removeElements =
    roleInfo: [{
        roleID: 5,
        roleName: 'Support',
}]
</code>```

Question: How to filter the originalArray that are not there in the removeElements arrays

答:
Try this:</p>

```<code>originalArray.filter(item => removeElements.some(f => f.id == item.id));
</code>```

Body:
I have two arrays like below format,

this.originalArray = [{
    id: 10,
    name: 'a',
    roleInfo: [{
        roleID: 5,
        roleName: 'USER'
    }]
},
{
    id: 20,
    name: 'b',
    roleInfo: [{
        roleID: 5,
        roleName: 'Admin',
    }]
 },
 {
     id: 30,
     name: 'c',
     roleInfo: [{
         roleID: 5,
         roleName: 'Support',
     }]
 }]

this.removeElements =
    roleInfo: [{
        roleID: 5,
        roleName: 'Support',
}]

Question: How to filter the originalArray that are not there in the removeElements arrays

Body:
Try this:

originalArray.filter(item => removeElements.some(f => f.id == item.id));


问:
Select unique records and insert into another table avoiding duplicates in it
i have two table(userfrom and userto).

i want to insert data from "userfrom" table to "userto" and want to implement condition on two column i.e "username" and "date".

Basically i am pasting my data from "userfrom" to table "userto".

Condition before insertion is.

Same "username" with same "date" should not get inserted.
There can be same username but date shold be different.

Only username is identical in between both the tables

Please Note:(On re-run of insert query i dont want same data to be duplicated. This insert query runs for 5 time in 30 min bracket)
Table userfrom:

```<code>1 sampleusername  2017-12-04
2 sampleusername  2017-12-04
3 sampleusername2 2017-12-04
4 sampleusername  2017-12-05
</code>```

Table usertto:

```<code>1 sampleusername  2017-12-04
2 sampleusername2 2017-12-04
3 sampleusername  2017-12-05
</code>```

答:
SQL DEMO

You can use GROUP BY and EXISTS in sql server like below :

```<code>insert into userto (username, date)
select distinct username, date from userfrom uf
where
not exists(select 1 from userto where username=uf.username and date=uf.date)
</code>```

Body:
i have two table(userfrom and userto).

i want to insert data from "userfrom" table to "userto" and want to implement condition on two column i.e "username" and "date".

Basically i am pasting my data from "userfrom" to table "userto".

Condition before insertion is.

Same "username" with same "date" should not get inserted.
There can be same username but date shold be different.

Only username is identical in between both the tables

Please Note:(On re-run of insert query i dont want same data to be duplicated. This insert query runs for 5 time in 30 min bracket)
Table userfrom:

1 sampleusername  2017-12-04
2 sampleusername  2017-12-04
3 sampleusername2 2017-12-04
4 sampleusername  2017-12-05

Table usertto:

1 sampleusername  2017-12-04
2 sampleusername2 2017-12-04
3 sampleusername  2017-12-05

Body:
SQL DEMO

You can use GROUP BY and EXISTS in sql server like below :

insert into userto (username, date)
select distinct username, date from userfrom uf
where
not exists(select 1 from userto where username=uf.username and date=uf.date)


问:
MS Access Checkbox on report row
I would like to add a checkbox to my report rows to be checked per row after i am done with my action for said row.

I have a list of items per report, i want to check the item once im done with it, and the check will remain even if i close the application.

答:
Add a field to the report's source table called and then add a clickable bound checkbox control to the report.

Here are steps for a textbox control.  Just choose a checkbox instead.  (found by scrolling the list of controls in the Design menu)

Title: MS Access Checkbox on report row


答:
this works in (almost) all browsers.

```<code>var a = [1, 2, 3, 4, 5];
var b = [2, 3];

var result = [], found;
for (var i = 0; i < a.length; i++) {
    found = false;
    // find a[i] in b
    for (var j = 0; j < b.length; j++) {
        if (a[i] == b[j]) {
            found = true;
            break;
        }
    }
    if (!found) {
        result.push(a[i]);
    }
}
</code>```

or if compatibility is not an issue

a.filter(i => b.some(j => j.id === i.id));

Title: Filter elements of array if contained in other

Body:
this works in (almost) all browsers.

var a = [1, 2, 3, 4, 5];
var b = [2, 3];

var result = [], found;
for (var i = 0; i < a.length; i++) {
    found = false;
    // find a[i] in b
    for (var j = 0; j < b.length; j++) {
        if (a[i] == b[j]) {
            found = true;
            break;
        }
    }
    if (!found) {
        result.push(a[i]);
    }
}

or if compatibility is not an issue

a.filter(i => b.some(j => j.id === i.id));


问:
How to stop python script when run it from Website (php)
My Project is Lighting Control on Rasp Pi
by use Rasp Pi as Web Server & Control the light by python script
I use the UI on PHP Website to control the light

Here is my php code

```<code><?php
    public function auto1()
    {
        system('sudo -u root -S python /var/www/4led/chktime1.py');
    }

    public function disauto1()
    {
        system('echo raspberry | sudo -u root -S pkill -f chktime1.py');
    }
?>
</code>```

when I press the on button on website to turn auto script It call auto1 and work correctly but this is loop script (I intend to make it loop alltime) but when I press the off button It can't close it because the loop of chktime1.py is still working and cannot open other script or command in disauto1. How can I stop this script from PHP command.

Thank you for your helping

答:
Not sure if your problem is solved but maybe it helps someone else.
You can Touch a File in PHP and check in your chktime1.py if the file is there or not.

```<code><form action="" method="post">
     <input type="submit" name="start" value="start" />
     <input type="submit" name="stop" value="stop" />
</form>

<?php
    if(isset($_POST['start'])){
        system('sudo -u root -S python /var/www/4led/chktime1.py');
    }
    if(isset($_POST['stop'])){
        system('sudo -u root -S touch /var/www/4led/stop-script');
    }
?>
</code>```

you can add this to your Python

```<code>import os, sys

while(true):
   #your code
   if(os.path.isfile('/var/www/4led/stop-script')):
      break

os.system("sudo -u root -S rm /var/www/4led/stop-script")
</code>```

Body:
My Project is Lighting Control on Rasp Pi
by use Rasp Pi as Web Server & Control the light by python script
I use the UI on PHP Website to control the light

Here is my php code

<?php
    public function auto1()
    {
        system('sudo -u root -S python /var/www/4led/chktime1.py');
    }

    public function disauto1()
    {
        system('echo raspberry | sudo -u root -S pkill -f chktime1.py');
    }
?>

when I press the on button on website to turn auto script It call auto1 and work correctly but this is loop script (I intend to make it loop alltime) but when I press the off button It can't close it because the loop of chktime1.py is still working and cannot open other script or command in disauto1. How can I stop this script from PHP command.

Thank you for your helping

Body:
Not sure if your problem is solved but maybe it helps someone else.
You can Touch a File in PHP and check in your chktime1.py if the file is there or not.

<form action="" method="post">
     <input type="submit" name="start" value="start" />
     <input type="submit" name="stop" value="stop" />
</form>

<?php
    if(isset($_POST['start'])){
        system('sudo -u root -S python /var/www/4led/chktime1.py');
    }
    if(isset($_POST['stop'])){
        system('sudo -u root -S touch /var/www/4led/stop-script');
    }
?>

you can add this to your Python

import os, sys

while(true):
   #your code
   if(os.path.isfile('/var/www/4led/stop-script')):
      break

os.system("sudo -u root -S rm /var/www/4led/stop-script")


问:
how to coin toss using python?
I'm new to python and i'm doing a probability question on simulate the result of a coin toss. I read the question but I don't understand how to do it. Here's the question:

"Does python have the capability to generate a random number?
Let’s toss a coin 100 times and write the result to a file where the format of the
line is:

```<code><int> throw number, <int> coin result {1 for a head and 0 for tails}
</code>```

For example:

```<code>1, 1
2, 0
3, 1
</code>```

Open a file called random.dat and write out the results.

Now open the file for reading and read in each line. Extract the result and
assign it to a list called heads or tails depending on the result { 1 or 0}.

Consider the length of the heads and tails list for different values of the number of coin toss"

Can anyone help me with this part of the question? do I need to simulate the probability using a for loop?

答:
```<code>from random import randint

numTosses = 100

fileOut = open("data.dat",'w')

for index in range(numTosses):
    fileOut.write(str(index) + "," \
                             + str(randint(0,1)) \
                             + '\n' )

fileOut.close()

fileIn = open("data.dat",'r')

heads = list()
tails = list()

for line in fileIn.readlines():

    fields = line.split(',')

    if fields[1].strip() == '1':
        heads.append(1)
    else:
        tails.append(1)

print("Number of heads is: " + str(len(heads)))
print("Number of tails is: " + str(len(tails)))

fileIn.close()
</code>```

Title: how to coin toss using python?

Body:
I'm new to python and i'm doing a probability question on simulate the result of a coin toss. I read the question but I don't understand how to do it. Here's the question:

"Does python have the capability to generate a random number?
Let’s toss a coin 100 times and write the result to a file where the format of the
line is:

<int> throw number, <int> coin result {1 for a head and 0 for tails}

For example:

1, 1
2, 0
3, 1

Open a file called random.dat and write out the results.

Now open the file for reading and read in each line. Extract the result and
assign it to a list called heads or tails depending on the result { 1 or 0}.

Consider the length of the heads and tails list for different values of the number of coin toss"

Can anyone help me with this part of the question? do I need to simulate the probability using a for loop?


答:
```<code>this.originalArray =[ { id: 10, name: 'a', roleInfo: [{ roleID: 5, roleName: 'USER' }] },
  { id: 20, name: 'b', roleInfo: [{ roleID: 5, roleName: 'Admin', }] },
   { id: 30, name: 'c', roleInfo: [{ roleID: 5, roleName: 'Support', }] }, ]

   this.removeElements =[
    {
        id: 30,
        name: 'c',
        roleInfo: [{
            roleID: 5,
            roleName: 'Support',
        }]
    }]

    var finalArr = [];
   this.originalArray.forEach(function(d){
   var filterArr =  this.removeElements.filter(function(d1){
      if(d1.id == d.id && d1.name == d.name){
        return d1;
      }
    });
    if(filterArr.length == 0){
      finalArr.push(d);
    }
   })
</code>```


问:
RecyclerView using DiffUtil, prevent to scroll bottom on change
I have a problem with my recyclerViev, specifically with the scrolling.
I have some list, which is updated in real time, some item is added, some removed, and everything is sorted by some parameter.
So the item which was initially first on the list, can have its parameter changed, which will be in different position after the sorting.

So my recyclerView is for example focusing on the initial item, and after change, when some item has "better" parameter is changing position with that initial item.

Problem is, i want to focus on the new item, with "better" parameter when I'm not scrolling, but i don't want to focusing on it when i scroll by touch(so my touch will not be interrupted by scrolling to current first item on the list).

So i don't want to force this code after every change in my recyclerView data:

```<code>recyclerView.scrollToPosition(0);
</code>```

because as i said, i will be interrupted by this scroll when i am touching my recyclerView list and go down to see other items and in the same time there will be a change in my list.

Is there a way to accomplish this?

To be specific, i am using DiffCallback from the DiffUtil, to support animations when there is a change in my current recyclerView list - it compares the old list with another new list and apply all the wanted animations and notifications(item added, removed, changed position). So i never call

```<code>notifyDataSetChanged
</code>```

or anything like that

Here is my DiffUtil callback:

```<code>  public static class DevicesDiffCallback extends DiffUtil.Callback{

    List<DeviceInfo> oldDevices;
    List<DeviceInfo> newDevices;

    public DevicesDiffCallback(List<NexoDeviceInfo> newDevices, List<NexoDeviceInfo> oldDevices) {
        this.newDevices = newDevices;
        this.oldDevices = oldDevices;
    }

    @Override
    public int getOldListSize() {
        return oldDevices != null ? oldDevices.size() : 0;
    }

    @Override
    public int getNewListSize() {
        return newDevices != null ?  newDevices.size() : 0;
    }

    @Override
    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
        return oldDevices.get(oldItemPosition).getNexoIdentifier().getSerialNumber().equals(newDevices.get(newItemPosition).getNexoIdentifier().getSerialNumber());
    }

    @Override
    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
        return oldDevices.get(oldItemPosition).equals(newDevices.get(newItemPosition));
    }

    @Override
    public Object getChangePayload(int oldItemPosition, int newItemPosition) {
        return super.getChangePayload(oldItemPosition, newItemPosition);
    }
}
</code>```

And i set it like this in my adapter, when i get the list of new data to be populated and replace the old data:

```<code> public void setData(List<DeviceInfo> data) {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DevicesDiffCallback(this.mData, data), false);
    diffResult.dispatchUpdatesTo(this);

        mData = data;

}
</code>```

答:
I'm not sure about this answer but, I think your code to call DiffUtil is not proper. Try using this :

```<code>public void addItems(List<Recipe> recipeList) {

    List<Recipe> newRecipeList = new ArrayList<>();
    newRecipeList.addAll(this.recipeList);
    newRecipeList.addAll(recipeList);

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new RecipeDiffUtilCallback(this.recipeList, newRecipeList));
    this.recipeList.addAll(recipeList);
    diffResult.dispatchUpdatesTo(this);
}
</code>```

Body:
I have a problem with my recyclerViev, specifically with the scrolling.
I have some list, which is updated in real time, some item is added, some removed, and everything is sorted by some parameter.
So the item which was initially first on the list, can have its parameter changed, which will be in different position after the sorting.

So my recyclerView is for example focusing on the initial item, and after change, when some item has "better" parameter is changing position with that initial item.

Problem is, i want to focus on the new item, with "better" parameter when I'm not scrolling, but i don't want to focusing on it when i scroll by touch(so my touch will not be interrupted by scrolling to current first item on the list).

So i don't want to force this code after every change in my recyclerView data:

recyclerView.scrollToPosition(0);

because as i said, i will be interrupted by this scroll when i am touching my recyclerView list and go down to see other items and in the same time there will be a change in my list.

Is there a way to accomplish this?

To be specific, i am using DiffCallback from the DiffUtil, to support animations when there is a change in my current recyclerView list - it compares the old list with another new list and apply all the wanted animations and notifications(item added, removed, changed position). So i never call

notifyDataSetChanged

or anything like that

Here is my DiffUtil callback:

  public static class DevicesDiffCallback extends DiffUtil.Callback{

    List<DeviceInfo> oldDevices;
    List<DeviceInfo> newDevices;

    public DevicesDiffCallback(List<NexoDeviceInfo> newDevices, List<NexoDeviceInfo> oldDevices) {
        this.newDevices = newDevices;
        this.oldDevices = oldDevices;
    }

    @Override
    public int getOldListSize() {
        return oldDevices != null ? oldDevices.size() : 0;
    }

    @Override
    public int getNewListSize() {
        return newDevices != null ?  newDevices.size() : 0;
    }

    @Override
    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
        return oldDevices.get(oldItemPosition).getNexoIdentifier().getSerialNumber().equals(newDevices.get(newItemPosition).getNexoIdentifier().getSerialNumber());
    }

    @Override
    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
        return oldDevices.get(oldItemPosition).equals(newDevices.get(newItemPosition));
    }

    @Override
    public Object getChangePayload(int oldItemPosition, int newItemPosition) {
        return super.getChangePayload(oldItemPosition, newItemPosition);
    }
}

And i set it like this in my adapter, when i get the list of new data to be populated and replace the old data:

 public void setData(List<DeviceInfo> data) {
    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DevicesDiffCallback(this.mData, data), false);
    diffResult.dispatchUpdatesTo(this);

        mData = data;

}

Body:
I'm not sure about this answer but, I think your code to call DiffUtil is not proper. Try using this :

public void addItems(List<Recipe> recipeList) {

    List<Recipe> newRecipeList = new ArrayList<>();
    newRecipeList.addAll(this.recipeList);
    newRecipeList.addAll(recipeList);

    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new RecipeDiffUtilCallback(this.recipeList, newRecipeList));
    this.recipeList.addAll(recipeList);
    diffResult.dispatchUpdatesTo(this);
}


答:
You can do</p>

```<code>var reuslt =  originalArray.filter(item => removeElements.find(test => test.id == item.id));
</code>```

Body:
You can do

var reuslt =  originalArray.filter(item => removeElements.find(test => test.id == item.id));


问:
How to accept SOH character from TextField in JAVAFx
I have written  simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.

Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:

```<code>8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP
</code>```

Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:

```<code>8=FIX.4.29=9135=A34=149=TTDS68AP
</code>```

How can I get the SOH character too from the Text Field?

答:
The problem is that javaFX TextField filters invalid characters with the following function:

```<code>private static boolean isInvalidCharacter(char c, boolean newlineIllegal, boolean tabIllegal) {
    if (c == 0x7F) return true;
    if (c == 0xA) return newlineIllegal;
    if (c == 0x9) return tabIllegal;
    if (c < 0x20) return true;
    return false;
}
</code>```

This happens after you paste and before the String is stored in the field. Before this function is called a custom filter can be set and applied, in this filter you can change SOH to something else; it's unicode representation ␁ is a good candidate:

```<code>textField.setTextFormatter(new TextFormatter<>((t) -> {
    t.setText(t.getText().replace((char)1, '\u2401'));
    return t;
}));
</code>```

Adding the above will change it after it's pasted and before it's stored. When you want to use the String from the textField you need to replace it back to SOH with:

```<code>String withSOH = field.getText().replace('\u2401', (char)1);
</code>```

Body:
I have written  simple GUI screen that actually contains a JavaFx textField where the user enters a string and that String I have to pass to TCP client.

Now the problem is user enters a string that contains SOH as the delimiter.
SOH is nothing but "\u001". But when the user enters a String that contains this delimiters then it is removed and only the simple plain text is retrieved. How can I eliminate this. This unique character is very important for me.
For example my string is as follows:

8=FIX.4.2\u001 9=9 \u001 35=A \u001 34=1\u001 49=TTDS68AP

Observer the above String where I have the \u001 character representing SOH. But when I entered this String in the TextField then the result is like:

8=FIX.4.29=9135=A34=149=TTDS68AP

How can I get the SOH character too from the Text Field?

Body:
The problem is that javaFX TextField filters invalid characters with the following function:

private static boolean isInvalidCharacter(char c, boolean newlineIllegal, boolean tabIllegal) {
    if (c == 0x7F) return true;
    if (c == 0xA) return newlineIllegal;
    if (c == 0x9) return tabIllegal;
    if (c < 0x20) return true;
    return false;
}

This happens after you paste and before the String is stored in the field. Before this function is called a custom filter can be set and applied, in this filter you can change SOH to something else; it's unicode representation ␁ is a good candidate:

textField.setTextFormatter(new TextFormatter<>((t) -> {
    t.setText(t.getText().replace((char)1, '\u2401'));
    return t;
}));

Adding the above will change it after it's pasted and before it's stored. When you want to use the String from the textField you need to replace it back to SOH with:

String withSOH = field.getText().replace('\u2401', (char)1);


问:
Xcode Interface Builder 9.1 Collection View Cells have too small "expected height"
Recently, I encountered a problem with the Interface Builder which I failed to solve. I'm using a UICollectionViewController and whenever I add a Cell it immediately shows a orange rectangle (indicating a auto-layout update). Updating the frame/cell doesn't change anything. The warning associated with the orange marking reads "Expected: height=Y, Actual: height=X" where Y is always exactly X-100. That is: When I set a custom cell height of 193, it says "Expected: height=93". This happens no matter which size I enter.

The problem with this is that I have many difficulties with the subviews and their constraints. For instance, if I add a subview with the constraint to keep the same height as the cell, it will be shown as 93 (the expected height), even though my cell should be 193. Layouting becomes impossible.

I tried adding a new cell, same issue. I tried removing every subview and re-adding them, nothing.

Any ideas are highly welcome.

Thank you very much!

答:
I'm not sure if this solved it, but the warning and issue disappeared once I did the following:

Select the CollectionViewController in Interface Builder and set the size to freeform and make the height larger, large enough to show all your template cells. (Plus: maybe refresh the views). That solved the issue for me.


问:
JavaScript invalid date from DateTime Picker
I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.

But my first value (rtime) always gives an invalid date. Where am I wrong?

Note: stime is not editable, the user only uses the DateTime Picker for rtime field.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);```

This result shows that LastOut is an invalid date:

答:
The dates you're picking are probably Month/Day/Year. But your expected date is Day/Month/Year. For example, the date 04/12/2017 is returning April 12th instead of December 4th. You can use a regex on your string to replace and make it in the correct format.

Please check this snippet:

var stime = "28/11/2017 09:18:52" //$("#movesend").val();
var rtime = "04/12/2017 10:16:34" //$("#moveretorna").val();

function parseDate(dateString) {
    return dateString.replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
}

var lastReturn= new Date(parseDate(rtime));
var lastOut= new Date(parseDate(stime));

if(lastReturn>= lastOut)
{
   console.log("This date is after than the other!");
}

console.log(stime);
console.log(rtime);
console.log(lastReturn);
console.log(lastOut);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.

But my first value (rtime) always gives an invalid date. Where am I wrong?

Note: stime is not editable, the user only uses the DateTime Picker for rtime field.

var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';

var lastReturn = new Date(rtime);
var lastOut = new Date(stime);

if (lastReturn >= lastOut) {
  console.log("This date is after than the other!");
}

console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);

This result shows that LastOut is an invalid date:

Body:
The dates you're picking are probably Month/Day/Year. But your expected date is Day/Month/Year. For example, the date 04/12/2017 is returning April 12th instead of December 4th. You can use a regex on your string to replace and make it in the correct format.

Please check this snippet:

var stime = "28/11/2017 09:18:52" //$("#movesend").val();
var rtime = "04/12/2017 10:16:34" //$("#moveretorna").val();

function parseDate(dateString) {
    return dateString.replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
}

var lastReturn= new Date(parseDate(rtime));
var lastOut= new Date(parseDate(stime));

if(lastReturn>= lastOut)
{
   console.log("This date is after than the other!");
}

console.log(stime);
console.log(rtime);
console.log(lastReturn);
console.log(lastOut);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>