问:
Unable to install ansible-awx
I am trying to install AWX but it fails with below error

Version info

```<code>ansible --version
ansible 2.4.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.6.6 (r266:84292, Aug 18 2016, 08:36:59) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]
</code>```

docker --version

```<code>Docker version 1.6.1, build a8a31ef/1.6.1

pip install docker-py --trusted-host pypi.python.org
Requirement already satisfied: docker-py in /usr/lib/python3.6/site-packages
Requirement already satisfied: websocket-client>=0.32.0 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: requests!=2.11.0,>=2.5.2 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: six>=1.4.0 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: docker-pycreds>=0.2.1 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: idna<2.7,>=2.5 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
</code>```

Error

```<code> ansible-playbook -i inventory install.yml

PLAY [Build and deploy AWX] **************************************************************************************************************************************************************************************************

TASK [check_vars : include_tasks] ********************************************************************************************************************************************************************************************
skipping: [localhost]

TASK [check_vars : include_tasks] ********************************************************************************************************************************************************************************************
included: /root/awx-devel/installer/check_vars/tasks/check_docker.yml for localhost

TASK [check_vars : postgres_data_dir should be defined] **********************************************************************************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "failed": false,
    "msg": "All assertions passed"
}

TASK [check_vars : host_port should be defined] ******************************************************************************************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "failed": false,
    "msg": "All assertions passed"
}

TASK [image_build : Get Version from checkout if not provided] ***************************************************************************************************************************************************************
changed: [localhost -> localhost]

TASK [image_build : Set global version if not provided] **********************************************************************************************************************************************************************
ok: [localhost]

TASK [image_build : Verify awx-logos directory exists for official install] **************************************************************************************************************************************************
skipping: [localhost]

TASK [image_build : Copy logos for inclusion in sdist] ***********************************************************************************************************************************************************************
skipping: [localhost]

TASK [image_build : Set sdist file name] *************************************************************************************************************************************************************************************
ok: [localhost]

TASK [image_build : AWX Distribution] ****************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "awx-.tar.gz"
}

TASK [image_build : Stat distribution file] **********************************************************************************************************************************************************************************
ok: [localhost -> localhost]

TASK [image_build : Clean distribution] **************************************************************************************************************************************************************************************
changed: [localhost -> localhost]

TASK [image_build : Build sdist builder image] *******************************************************************************************************************************************************************************
fatal: [localhost -> localhost]: FAILED! => {"changed": false, "failed": true, "msg": "Failed to import docker-py - No module named requests.exceptions. Try `pip install docker-py`"}
        to retry, use: --limit @/root/awx-devel/installer/install.retry

PLAY RECAP *******************************************************************************************************************************************************************************************************************
localhost                  : ok=9    changed=2    unreachable=0    failed=1
</code>```

Can anyone point me what I am doing wrong?

Also is there a way we can install AWX in virtual machines without docker/container , just like any other application ?

答:
Ansible tells you:

```<code>python version = 2.6.6
</code>```

Pip tells you:

```<code>Requirement already satisfied: docker-py in /usr/lib/python3.6/site-packages
</code>```

Compare the Python version numbers above and fix.

Title: Unable to install ansible-awx

Body:
I am trying to install AWX but it fails with below error

Version info

ansible --version
ansible 2.4.0.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.6/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.6.6 (r266:84292, Aug 18 2016, 08:36:59) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)]

docker --version

Docker version 1.6.1, build a8a31ef/1.6.1

pip install docker-py --trusted-host pypi.python.org
Requirement already satisfied: docker-py in /usr/lib/python3.6/site-packages
Requirement already satisfied: websocket-client>=0.32.0 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: requests!=2.11.0,>=2.5.2 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: six>=1.4.0 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: docker-pycreds>=0.2.1 in /usr/lib/python3.6/site-packages (from docker-py)
Requirement already satisfied: idna<2.7,>=2.5 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/lib/python3.6/site-packages (from requests!=2.11.0,>=2.5.2->docker-py)

Error

 ansible-playbook -i inventory install.yml

PLAY [Build and deploy AWX] **************************************************************************************************************************************************************************************************

TASK [check_vars : include_tasks] ********************************************************************************************************************************************************************************************
skipping: [localhost]

TASK [check_vars : include_tasks] ********************************************************************************************************************************************************************************************
included: /root/awx-devel/installer/check_vars/tasks/check_docker.yml for localhost

TASK [check_vars : postgres_data_dir should be defined] **********************************************************************************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "failed": false,
    "msg": "All assertions passed"
}

TASK [check_vars : host_port should be defined] ******************************************************************************************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "failed": false,
    "msg": "All assertions passed"
}

TASK [image_build : Get Version from checkout if not provided] ***************************************************************************************************************************************************************
changed: [localhost -> localhost]

TASK [image_build : Set global version if not provided] **********************************************************************************************************************************************************************
ok: [localhost]

TASK [image_build : Verify awx-logos directory exists for official install] **************************************************************************************************************************************************
skipping: [localhost]

TASK [image_build : Copy logos for inclusion in sdist] ***********************************************************************************************************************************************************************
skipping: [localhost]

TASK [image_build : Set sdist file name] *************************************************************************************************************************************************************************************
ok: [localhost]

TASK [image_build : AWX Distribution] ****************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "awx-.tar.gz"
}

TASK [image_build : Stat distribution file] **********************************************************************************************************************************************************************************
ok: [localhost -> localhost]

TASK [image_build : Clean distribution] **************************************************************************************************************************************************************************************
changed: [localhost -> localhost]

TASK [image_build : Build sdist builder image] *******************************************************************************************************************************************************************************
fatal: [localhost -> localhost]: FAILED! => {"changed": false, "failed": true, "msg": "Failed to import docker-py - No module named requests.exceptions. Try `pip install docker-py`"}
        to retry, use: --limit @/root/awx-devel/installer/install.retry

PLAY RECAP *******************************************************************************************************************************************************************************************************************
localhost                  : ok=9    changed=2    unreachable=0    failed=1

Can anyone point me what I am doing wrong?

Also is there a way we can install AWX in virtual machines without docker/container , just like any other application ?

Body:
Ansible tells you:

python version = 2.6.6

Pip tells you:

Requirement already satisfied: docker-py in /usr/lib/python3.6/site-packages

Compare the Python version numbers above and fix.


来源: stackexchange

问:
Error: Package: python-devel-2.6.6-64.el6.x86_64 Requires: python-libs(x86-64) = 2.6.6-64.el6 found: python-libs-2.6.6-66.el6_8.x86_64
I am getting this error on running python setup.py for installing cffi python module.

```<code>c/cffi1_module.c: At top level:
c/cffi1_module.c:128: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
c/cffi1_module.c:150: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
c/_cffi_backend.c:6691: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘init_cffi_backend’
error: command 'gcc' failed with exit status 1
error: command 'gcc' failed with exit status 1,

So this error on googling shows that I need to install python devel and on doing that I get the error below:

Error: Package: python-devel-2.6.6-64.el6.x86_64 (rhel-6-server-rpms)
           Requires: python-libs(x86-64) = 2.6.6-64.el6
           Installed: python-libs-2.6.6-66.el6_8.x86_64 (@rhel6-patch-channel-may2015)
               python-libs(x86-64) = 2.6.6-66.el6_8
</code>```

According to the error- Requires: python-libs(x86-64) = 2.6.6-64.el6 but installed is- python-libs(x86-64) = 2.6.6-66.el6_8, so how can I change it?

答: Your rhel-6-server-rpms channel is not the official version.  The current rhel-6-server-rpms channel contents actually has Python at version 2.6.6-66.el6_8.x86_64, so the problem would not happen with it.  You need to look at yum repolist -v output and double-check that you are using the official repositories.  (You will need an active Red Hat Enterprise Linux subscription to access these repositories.)

ContentLicense: CC BY-SA 3.0

Body:
I am getting this error on running python setup.py for installing cffi python module.

c/cffi1_module.c: At top level:
c/cffi1_module.c:128: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
c/cffi1_module.c:150: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘*’ token
c/_cffi_backend.c:6691: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘init_cffi_backend’
error: command 'gcc' failed with exit status 1
error: command 'gcc' failed with exit status 1,

So this error on googling shows that I need to install python devel and on doing that I get the error below:

Error: Package: python-devel-2.6.6-64.el6.x86_64 (rhel-6-server-rpms)
           Requires: python-libs(x86-64) = 2.6.6-64.el6
           Installed: python-libs-2.6.6-66.el6_8.x86_64 (@rhel6-patch-channel-may2015)
               python-libs(x86-64) = 2.6.6-66.el6_8

According to the error- Requires: python-libs(x86-64) = 2.6.6-64.el6 but installed is- python-libs(x86-64) = 2.6.6-66.el6_8, so how can I change it?


问:
How to copy files from local to hdfs using oozie
I am trying to copy files from my edge node to HDFS using oozie. Many suggested to setup password less ssh to get this done.

Iam unable to login to oozie user as it is a service user.

Is there any other way other than password less ssh.

Thanks in advance.

答:
Other than password less ssh there are two more options :
1. My preferred option : Use JSch java library and create a java application which will accept a shell script to be executed as argument. Using the JSch , it will perform ssh on the configured edge node and execute the shell script on the edge node. In the jsch, you can configure, the edgenode username and password. Use 'JCEKS' file to store the password.
Then add a Java Action in Oozie to run the java application created using JSch.
2. Use "/usr/bin/expect" library to create a shell script, which will perform ssh on edgenode and then run the configured shell script. More details are here Use expect in bash script to provide password to SSH command</p>


问:
Use global parent selector with Sass and CSS Module
How can I style my React component using Sass and CSS modules based on the existence of a GLOBAL parent selector (in this case isOpen)?

Rendered HTML:

```<code><div class="isOpen">
   <div class="MyContainer__MyStyle___u9dTa">
      My react component
   </div>
</div>
</code>```

My Sass file:

```<code>.MyStyle
   margin-left: 100px
   color: black

// TODO: Override MyStyle if 'isOpen' is on parent, e.g. something like:
.MyStyle
   :global(.isOpen) &
      margin-left: 0
      color: red
</code>```

The code above gives error: Property "global" must be followed by a ':'

答:
Though it's a little late for me to answer, I think I found the answer and I'll post it for those who may encounter this problem in the future.

The problem is in Sass you have to escape the :global keyword with \:global in order to make CSS module works as you expected.

The discussion can be found at https://github.com/webpack-contrib/sass-loader/issues/448.

Body:
How can I style my React component using Sass and CSS modules based on the existence of a GLOBAL parent selector (in this case isOpen)?

Rendered HTML:

      My react component

My Sass file:

.MyStyle
   margin-left: 100px
   color: black

// TODO: Override MyStyle if 'isOpen' is on parent, e.g. something like:
.MyStyle
   :global(.isOpen) &
      margin-left: 0
      color: red

The code above gives error: Property "global" must be followed by a ':'


问:
Django: Add field to model formset
I can I add fields to a model formset? It seems you can add fields if you user normal formset but not with model formsets (at least it's not the same way). I don't think I should use inline formset either ..?

I want to let users edit their photoalbum (django-photologue). So far I've manage to do this:

```<code>PhotoFormSet = modelformset_factory(Photo,
                                       exclude=(
                                        'effect',
                                        'caption',
                                        'title_slug',
                                        'crop_from',
                                        'is_public',
                                        'slug',
                                        'tags'
                                       ))

context['gallery_form'] = PhotoFormSet(queryset=self.object.gallery.photos.all())
</code>```

The problem is that I have  to add a checkbox for each photo saying "Delete this photo" and a radio select saying "Set this to album cover".

Thanks in advance!

答:
You can add fields. Just define a form in the normal way, then tell modelformset_factory to use that as the basis for the formset:

```<code>MyPhotoForm(forms.ModelForm):
    delete_box = forms.BooleanField()

    class Meta:
        model = Photo
        exclude=('effect',
                 'caption',
                 'title_slug',
                 'crop_from',
                 'is_public',
                 'slug',
                 'tags'
                ))

PhotoFormSet = modelformset_factory(Photo, form=MyPhotoForm)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Django: Add field to model formset

Body:
I can I add fields to a model formset? It seems you can add fields if you user normal formset but not with model formsets (at least it's not the same way). I don't think I should use inline formset either ..?

I want to let users edit their photoalbum (django-photologue). So far I've manage to do this:

PhotoFormSet = modelformset_factory(Photo,
                                       exclude=(
                                        'effect',
                                        'caption',
                                        'title_slug',
                                        'crop_from',
                                        'is_public',
                                        'slug',
                                        'tags'
                                       ))

context['gallery_form'] = PhotoFormSet(queryset=self.object.gallery.photos.all())

The problem is that I have  to add a checkbox for each photo saying "Delete this photo" and a radio select saying "Set this to album cover".

Thanks in advance!

Body:
You can add fields. Just define a form in the normal way, then tell modelformset_factory to use that as the basis for the formset:

MyPhotoForm(forms.ModelForm):
    delete_box = forms.BooleanField()

    class Meta:
        model = Photo
        exclude=('effect',
                 'caption',
                 'title_slug',
                 'crop_from',
                 'is_public',
                 'slug',
                 'tags'
                ))

PhotoFormSet = modelformset_factory(Photo, form=MyPhotoForm)


问:
Show loading image when Chart is loading
I am using a CanvasJs chart. The chart is working fine. The Chart is taking time to load. I wanted to show a loading image until the chart loads. CanvasJs charts have no defined attributes for this. Any help is appreciated.

Html:

JS:
chart = CanvasJS.Chart("chartContainer1", {});

答:
You can add loader-image(gif) or some text within the chart-container div so that image/text is shown in the div till the chart is initialized.

setTimeout(function(){
var chart = new CanvasJS.Chart("chartContainer", {
 title: {
   text: "Basic Column Chart"
  },
 data: [
 {
  type: "column",
  dataPoints: [
   { x: 10, y: 71 },
   { x: 20, y: 55 },
   { x: 30, y: 50 },
   { x: 40, y: 65 },
   { x: 50, y: 95 },
   { x: 60, y: 68 },
   { x: 70, y: 28 },
   { x: 80, y: 34 },
   { x: 90, y: 14 }
  ]
 }
 ]
});

chart.render();
},2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img{
  display: block;
  margin: auto;
}</code>```

```

Body:
You can add loader-image(gif) or some text within the chart-container div so that image/text is shown in the div till the chart is initialized.

setTimeout(function(){
var chart = new CanvasJS.Chart("chartContainer", {
 title: {
   text: "Basic Column Chart"
  },
 data: [
 {
  type: "column",
  dataPoints: [
   { x: 10, y: 71 },
   { x: 20, y: 55 },
   { x: 30, y: 50 },
   { x: 40, y: 65 },
   { x: 50, y: 95 },
   { x: 60, y: 68 },
   { x: 70, y: 28 },
   { x: 80, y: 34 },
   { x: 90, y: 14 }
  ]
 }
 ]
});

chart.render();
},2000);

img{
  display: block;
  margin: auto;
}

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 250px; width: 100%;">
  <img src="https://i.imgur.com/fXUIBfi.gif" alt="Chart will Render Here..."/>
</div>


问:
how to get ipv4 address of particular adapter via batch script in windows 10
I am trying to fetch the ipv4 address of the particular adapter(say Ethernet adapter Local Area Connection* 14) is there any command or script to do that in windows 10 . if somebody already had done in past thanks to share it .

Input -- adapter name

Output -- only adapter's ip address

答:
use netsh

in a batch file

```<code>@echo off
for /f "tokens=3 delims=: " %%I in ('netsh interface IPv4 show addresses "Ethernet adapter Local Area Connection" ^| findstr /C:"IP Address"') do echo %%I
</code>```

if used from command line and not in batch, remove one set of the % in %%I like this.

```<code>for /f "tokens=3 delims=: " %I in ('netsh interface IPv4 show addresses "Ethernet adapter Local Area Connection" ^| findstr /C:"IP Address"') do echo %I
</code>```

Body:
use netsh

in a batch file

@echo off
for /f "tokens=3 delims=: " %%I in ('netsh interface IPv4 show addresses "Ethernet adapter Local Area Connection" ^| findstr /C:"IP Address"') do echo %%I

if used from command line and not in batch, remove one set of the % in %%I like this.

for /f "tokens=3 delims=: " %I in ('netsh interface IPv4 show addresses "Ethernet adapter Local Area Connection" ^| findstr /C:"IP Address"') do echo %I


问:
Can Codeigniter Transaction Start When Another Transaction Running on The Same Table?
I have model named demon_model that contain method like below:

```<code>class Hell_model extends CI_Model {
   function insert_demon_to_hell()
   {
       $this->db->trans_start();
       //insert to helldb for example
       //update to helldb for example
       $this->db->trans_complete();
   }
}
</code>```

I have controller named demon_controller that like this

```<code>//REST CONTROLLER INCLUDED HERE

class Demon_controller extends REST_CONTROLLER {
    function contruct() {
        //LOAD HELL MODEL HERE
    }

    function demon () {
       $demon_id = $this->get('demon_id');
       $this->hell_model->insert_demon_to_hell($demon_id);
    }
}
</code>```

This API will call when someone meet the demon. The question is when two or more person meet the demon (invoke the function) at the sametime will the query still run on the same table even though I already use transaction in the model function?.

答:
Transactions do not controll concurrency, they just ensure that all modifications are done or none of them. It is the locking mechanism that controls concurrency.

Therefore the number of transactions running at the same time is theoretically unlimited. However, what and when they can do is restricted by the locks implicitly or explicitly set by the statements within the transactions.

One more important thing: db->trans_start() starts a database transaction, not a CI transaction. This means that the transaction applies to the changes done on the db level only, not on changes done on CI level. E.g. if you make a change to a property to a CI object that is not persisted in the database, then a rollback will not affect the value of that property.

Body:
I have model named demon_model that contain method like below:

class Hell_model extends CI_Model {
   function insert_demon_to_hell()
   {
       $this->db->trans_start();
       //insert to helldb for example
       //update to helldb for example
       $this->db->trans_complete();
   }
}

I have controller named demon_controller that like this

//REST CONTROLLER INCLUDED HERE

class Demon_controller extends REST_CONTROLLER {
    function contruct() {
        //LOAD HELL MODEL HERE
    }

    function demon () {
       $demon_id = $this->get('demon_id');
       $this->hell_model->insert_demon_to_hell($demon_id);
    }
}

This API will call when someone meet the demon. The question is when two or more person meet the demon (invoke the function) at the sametime will the query still run on the same table even though I already use transaction in the model function?.


问:
Machine learning algorithm - Boosting, number of interaction depth, d
I am learning boosting algorithm. I have been thinking of why small number of interaction depth works better than larger number? And how do people usually choose the number of interaction depth to be used?

Thank you!

答:
If you mean interaction depth in trees. (R)

Overfitting can be your problem.

You will adapt to much on your training data which is only assumed to give a full image of your test data.

Think of it like fitting a polynomial to a set of points and afterwards you add unknown points. The higher your order of the polynomial the better you can fit your known data (more or less) but this may result in a peaky function.
If you add new points it is likely that they are not covered by your function.


问:
How add shared-library to my library project in QT
May i load external library in my library project? If yes. How i can do this.
With Qlibrary? or typically include in pro file LIBS += -L /lib -lmylib and add *.h file to project?

Sorry for my English))))

答: Just go to your respective Qt .pro file in Qt Creator IDE itself, and right click on empty area and choose "Add Library", Select external Library and click next, now click on browse in front of include path text box and choose the .lib file you want to include and select the platforms you want to target and now click next and finish the process. To add .h file, first copy the .h file in your project folder, and right click on the header under solution explorer, and click on add existinf file, now select your .h file and add it.</p>


问:
Killing Java Process from C# Console App
I hate to post about this again but I answered my own last post thinking I fixed it (which I didn't). Basically when my c# .NET application shuts down, I want to remove the running Java process that it created. The initial problem was that I was trying to save processID to a static class member variable (which obviously didnt work). I found a Global Class example online and used that instead, however it still isn't shutting down the process.

Debugging it isn't working properly. I guess it just creates a new instance of the application rather than running the one that I built, and even setting the working directory to the "Bin" directory doesn't work. So I am just having to run my .exe from the Bin directory at the moment.

```<code>namespace MinecraftDaemon
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Minecraft Daemon...");

            Arguments CommandLine = new Arguments(args);

            // Hook ProcessExit Event
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(Current_ProcessExit);

            if (CommandLine["file"] != null && CommandLine["memory"] != null)
            {
                // Launch the Application (Command Line Parameters)
                LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
            }
            else
            {
                // Launch the Application (Default Parameters)
                LaunchMinecraft("minecraft_server.jar", "1024");
            }
        }

        public static void LaunchMinecraft(String file, String memoryValue)
        {
            String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M ";
            String args = memParams + "-jar " + file + " nogui";
            ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;

            try
            {
                using (Process minecraftProcess = Process.Start(processInfo))
                {
                    GlobalClass.ProcessID = minecraftProcess.Id;
                    Console.WriteLine("Process ID is " + GlobalClass.ProcessID);
                    minecraftProcess.WaitForExit();
                }
            }
            catch
            {
                // Log Error
            }
        }

        static void Current_ProcessExit(object sender, EventArgs e)
        {
            // Loop the Current Windows Processes
            foreach (Process winProcess in Process.GetProcesses())
            {
                Console.WriteLine("WinProcessID is " + winProcess.Id + " GlobalClass.ProcessID is " + GlobalClass.ProcessID);

                // If this is our Process, shut it down
                if (winProcess.Id == GlobalClass.ProcessID)
                {
                    Process.GetProcessById(GlobalClass.ProcessID).Kill();
                }
            }
        }
    }
}
</code>```

答: This was resolved by switching from catching the Event AppDomain.CurrentDomain.ProcessExit to using SetConsoleCtrlHandler();</p>

Body:
I hate to post about this again but I answered my own last post thinking I fixed it (which I didn't). Basically when my c# .NET application shuts down, I want to remove the running Java process that it created. The initial problem was that I was trying to save processID to a static class member variable (which obviously didnt work). I found a Global Class example online and used that instead, however it still isn't shutting down the process.

Debugging it isn't working properly. I guess it just creates a new instance of the application rather than running the one that I built, and even setting the working directory to the "Bin" directory doesn't work. So I am just having to run my .exe from the Bin directory at the moment.

namespace MinecraftDaemon
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Minecraft Daemon...");

            Arguments CommandLine = new Arguments(args);

            // Hook ProcessExit Event
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(Current_ProcessExit);

            if (CommandLine["file"] != null && CommandLine["memory"] != null)
            {
                // Launch the Application (Command Line Parameters)
                LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
            }
            else
            {
                // Launch the Application (Default Parameters)
                LaunchMinecraft("minecraft_server.jar", "1024");
            }
        }

        public static void LaunchMinecraft(String file, String memoryValue)
        {
            String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M ";
            String args = memParams + "-jar " + file + " nogui";
            ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;

            try
            {
                using (Process minecraftProcess = Process.Start(processInfo))
                {
                    GlobalClass.ProcessID = minecraftProcess.Id;
                    Console.WriteLine("Process ID is " + GlobalClass.ProcessID);
                    minecraftProcess.WaitForExit();
                }
            }
            catch
            {
                // Log Error
            }
        }

        static void Current_ProcessExit(object sender, EventArgs e)
        {
            // Loop the Current Windows Processes
            foreach (Process winProcess in Process.GetProcesses())
            {
                Console.WriteLine("WinProcessID is " + winProcess.Id + " GlobalClass.ProcessID is " + GlobalClass.ProcessID);

                // If this is our Process, shut it down
                if (winProcess.Id == GlobalClass.ProcessID)
                {
                    Process.GetProcessById(GlobalClass.ProcessID).Kill();
                }
            }
        }
    }
}


问:
how to send mail on specified date and time using mysql and php
what I have is,

user specified date and time in the database.

a php script to send mail.

Required

trigger php script when specified date and time arrives.

I am using local apache server

Example: A wants to send mail to B in 5 days from now. A enters date and time in database and after 5 days it will automatically sent by running php mailer script.

Is there any way of scheduling this?

答:
Write a function to get the sender and receiver list from DB for executing date.

```<code>ex:  check php date is equal to DB date to sent the email.
Add the php script to a cron job
</code>```

Check the sample code

```<code>$queryToGetuserListToSendEmail = "select * from userlist where date_toSend_email = ''". date("Y-m-d H:i:s")."'";
$userListToSendEmail = array();//senders relievers and other details taken from DB to send emails

foreach ($userListToSendEmail as $usersToSendEmail){
//sendEmail
}
</code>```

Cron job for running the job every day 2.30 A.M (add this in your cron tab)

```<code>30 2 * * * php /pathtoyourfile
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Write a function to get the sender and receiver list from DB for executing date.

ex:  check php date is equal to DB date to sent the email.
Add the php script to a cron job

Check the sample code

$queryToGetuserListToSendEmail = "select * from userlist where date_toSend_email = ''". date("Y-m-d H:i:s")."'";
$userListToSendEmail = array();//senders relievers and other details taken from DB to send emails

foreach ($userListToSendEmail as $usersToSendEmail){
//sendEmail
}

Cron job for running the job every day 2.30 A.M (add this in your cron tab)

30 2 * * * php /pathtoyourfile


问:
Find the content and increment value from Ruby
I have json file which contains following peace of lines.
I need to find and increment the last number "1.39.25.1" like 1.39.25.2, 1.39.25.3 so on by a ruby code.

```<code>    "appVersion": {
    "buildFlavour": "varation",
    "customisation": "MY.VER.NUM",
    "version": "1.39.25.1"
},
</code>```

Please help on this

Body:
I have json file which contains following peace of lines.
I need to find and increment the last number "1.39.25.1" like 1.39.25.2, 1.39.25.3 so on by a ruby code.

    "appVersion": {
    "buildFlavour": "varation",
    "customisation": "MY.VER.NUM",
    "version": "1.39.25.1"
},

Please help on this

Body:
*others, last = "1.39.25.1".split(".")
[*others, last.next].join(".")
# => "1.39.25.2"


问:
Javascript dynamic nested objects
I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.

I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?

here is the code:

var s = "key1.key2.key3.key4";

var a = s.split('.');

var obj = {};
var temp = obj;

for (var k =0; k < a.length; k++) {
 temp = temp[a[k]] = {};
  console.log(temp);
}

console.log(obj);```
</div>
</div>
</p>

<p>why is there a <code>var temp = obj</code>?</p>

<p>what does this line do?:</p>

```temp = temp[a[k]] = {};
```

also, the console.log(temp) inside the loop always logs an empty object {}, why?

Thanks for the feedback!

答:
Your question boils down to this (comments inline)

var x  = {};
var y = x;
y[ "a" ] = {}; //reference to x stays so x also becomes { "a": {} }
y = y["a"]; //now y effectively becomes {} but has the same reference to y["a"] as assignment works right to left hence property `a` is becomes non-enumerable and hence shadowed.
console.log( "First Run" );
console.log( y ); //prints {}
console.log( x ); //prints { "a": {} }

y[ "a" ] = {}; //y still has a non-enumerable property `a`
y = y["a"]; //same as above y = y["a"], y again becomes {}
console.log( "Second Run" );
console.log( y ); //prints {} again
console.log( x ); //prints { "a": { "a": {} } }```

Outputs

First Run

{}

{   "a": {} }

Second Run

{}

{   "a": {
      "a": {}   } }

Title: Javascript dynamic nested objects

Body:
I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.

I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?

here is the code:

var s = "key1.key2.key3.key4";

var a = s.split('.');

var obj = {};
var temp = obj;

for (var k =0; k < a.length; k++) {
 temp = temp[a[k]] = {};
  console.log(temp);
}

console.log(obj);

why is there a var temp = obj?

what does this line do?:

temp = temp[a[k]] = {};

also, the console.log(temp) inside the loop always logs an empty object {}, why?

Thanks for the feedback!

Body:
Your question boils down to this (comments inline)

var x  = {};
var y = x;
y[ "a" ] = {}; //reference to x stays so x also becomes { "a": {} }
y = y["a"]; //now y effectively becomes {} but has the same reference to y["a"] as assignment works right to left hence property `a` is becomes non-enumerable and hence shadowed.
console.log( "First Run" );
console.log( y ); //prints {}
console.log( x ); //prints { "a": {} }

y[ "a" ] = {}; //y still has a non-enumerable property `a`
y = y["a"]; //same as above y = y["a"], y again becomes {}
console.log( "Second Run" );
console.log( y ); //prints {} again
console.log( x ); //prints { "a": { "a": {} } }

Outputs

First Run

{}

{   "a": {} }

Second Run

{}

{   "a": {
      "a": {}   } }


问:
binary split and the options
Why is this function returning 3 elements ?</p>

```<code>[<<"12345">>,<<"67890">>,<<>>]

test3()->
    test4(<<"12345\r\n67890\r\n">>).
test4(Data)->
    X = binary:split(Data, [<<"\r\n">>],[global]),
    X.
</code>```

答:
```<code>binary:split(Subject,Pattern,Options)
</code>```

will split the binary object into the part of the binary that is before the splitting delimiter, and the parts after.

Consider adding the trim options for the binary:split, i.e.

```<code>binary:split(Data, [<<"\r\n">>],[trim,global]),
</code>```

Title: binary split and the options

Body:
Why is this function returning 3 elements ?

[<<"12345">>,<<"67890">>,<<>>]

test3()->
    test4(<<"12345\r\n67890\r\n">>).
test4(Data)->
    X = binary:split(Data, [<<"\r\n">>],[global]),
    X.

Body:
binary:split(Subject,Pattern,Options)

will split the binary object into the part of the binary that is before the splitting delimiter, and the parts after.

Consider adding the trim options for the binary:split, i.e.

binary:split(Data, [<<"\r\n">>],[trim,global]),


问:
Intent couldnt be initialized even after multiple tries
I have created this small program but i cant seem to make it run. It gives an error saying that intent hasnt been initialized. What should i do?

```<code>Spinner mySpinner1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.which));
    myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner1.setAdapter(myAdapter1);

    mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
           Intent intent = new Intent(MainActivity.this, intent.class);
            switch (position) {
                case 1:
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
            startActivity(intent);
        }
</code>```

EDIT 1 : Added few more lines of code to make the whole situation clearer

答:
The second argument you are passing is wrong, intent require valid activity class in second argument while redirect to activity.

```<code> Intent intent = new Intent(MainActivity.this, intent.class);
</code>```

remove your line with this

```<code>        switch (position) {
            case 1:
               Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            break;
        }
</code>```

Happy coding!!

Body:
I have created this small program but i cant seem to make it run. It gives an error saying that intent hasnt been initialized. What should i do?

Spinner mySpinner1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.which));
    myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner1.setAdapter(myAdapter1);

    mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
           Intent intent = new Intent(MainActivity.this, intent.class);
            switch (position) {
                case 1:
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
            startActivity(intent);
        }

EDIT 1 : Added few more lines of code to make the whole situation clearer

Body:
The second argument you are passing is wrong, intent require valid activity class in second argument while redirect to activity.

 Intent intent = new Intent(MainActivity.this, intent.class);

remove your line with this

        switch (position) {
            case 1:
               Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                startActivity(intent);
            break;
        }

Happy coding!!


问:
NodeJS Change variable from within a function
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

```<code>app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});
</code>```

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

答:
You can solve this problem using Promise. Your api call is async. So it will not wait to complete the api call. it just executes console.log(). That's why you are getting undefined. I'm not sure about your node version. if promises are not available you could use bluebird library.</p>

```<code>app.get('/:steamid', function(req, res) {

   var steamID;

   new Promise(function(resolve, reject){
    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
       resolve(res);
    });
  }).then(function(res){
      steamID = res;
      console.log('Steam64: ' + steamId);
    }
});
</code>```

Body:
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

Body:
You can solve this problem using Promise. Your api call is async. So it will not wait to complete the api call. it just executes console.log(). That's why you are getting undefined. I'm not sure about your node version. if promises are not available you could use bluebird library.

app.get('/:steamid', function(req, res) {

   var steamID;

   new Promise(function(resolve, reject){
    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
       resolve(res);
    });
  }).then(function(res){
      steamID = res;
      console.log('Steam64: ' + steamId);
    }
});


问:
How to create Sticker Keyboard App in android & IOS
I am trying to develop an App that with custom Keyboard in both Android & IOS.

With that custom keyboard i could send sticker or image through whatsApp, Instagram etc.

I need to develop a keyboard with following design

I tried some example in android from https://code.tutsplus.com/tutorials/create-a-custom-keyboard-on-android--cms-22615.

it is working fine but it showing keyboard with alphanumeric character.

Actually need show custom images.

so is there any suggestion or tutorial available, please help me.

答: For IOS have a look at https://github.com/SamuelZhaoY/ios-emojikeyboard and study.</p>


问:
Convert len() to a string value within a string concatenation expression
How do I convert the len() value to be a string to successfully print the a string expression?

```<code>vacation = ['Rick', 'Paris', 'Tom', 'James']

print("I live with " + len(vacation) + " people")
</code>```

I got the error

```<code>Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
   print("I live with " + len(vacation) + " people")
TypeError: must be str, not int
</code>```

答:
```<code>vacation = ['Rick', 'Paris', 'Tom', 'James']

print(f"I live with {len(vacation)} people")
</code>```

https://docs.python.org/3/reference/lexical_analysis.html for more info.

Body:
How do I convert the len() value to be a string to successfully print the a string expression?

vacation = ['Rick', 'Paris', 'Tom', 'James']

print("I live with " + len(vacation) + " people")

I got the error

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
   print("I live with " + len(vacation) + " people")
TypeError: must be str, not int

Body:
vacation = ['Rick', 'Paris', 'Tom', 'James']

print(f"I live with {len(vacation)} people")

https://docs.python.org/3/reference/lexical_analysis.html for more info.


问:
What does this PHP error mean?
What does the following error message mean?

```<code>Warning: mysql_data_seek() [function.mysql-data-seek]: Offset 0 is invalid for MySQL result index 3 (or the query data is unbuffered) in \\nawinfs03\home\users\web\b1878\rh.slmarble\php\getproductDB.php on line 6
or die('
</code>```

Code:

```<code>if (!mysql_data_seek($results, $num)) {
    echo "<h1 style='padding:10%'>Coming soon!</h1>";
}
</code>```

答:
I don't think you're query is returning anything. From the PHP manual:

..if the result set is empty
  (mysql_num_rows() == 0), a seek to 0
  will fail with a E_WARNING..

http://php.net/manual/en/function.mysql-data-seek.php

Title: What does this PHP error mean?

Body:
What does the following error message mean?

Warning: mysql_data_seek() [function.mysql-data-seek]: Offset 0 is invalid for MySQL result index 3 (or the query data is unbuffered) in \\nawinfs03\home\users\web\b1878\rh.slmarble\php\getproductDB.php on line 6
or die('

Code:

if (!mysql_data_seek($results, $num)) {
    echo "
Coming soon!
";
}


问:
Nested ifelse calls inside dplyr::mutate returns same values for each row
Dear stackoverflow community,

I am still a beginner in R and have encountered the following issue that I can't find a solution to on stackoverflow or the wider web. It seems pretty straight forward to me but I have no idea what I am missing or which coding conventions I am violating. The problem below is part of a larger function but the example below reproduces the issue.

I have two data frames a and b and would like to create a new variable foo1 in a using a nested ifelse statement with conditions based on elements from both a and b.

```<code>a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4))

a <- mutate(a, foo1 = ifelse(is.na(b$foo[1]), NA,
                             ifelse(a$foo == "a", "a", "f")))
</code>```

What I would expect or am looking for is the following:
The first ifelse statement checks whether the value in the first row of b is NA.
Since it is not in this case, it should jump to the second ifelse statement and give me

```<code>a <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4), foo1=c("a","f","f","f"))
</code>```

since the first row of a$foo is a and the others are not a (b,c,d).

What it does give me instead is

```<code>a <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4), foo1=c("a","a","a","a"))
</code>```

It prints "a" in all rows of foo1 instead of recognising that rows 2 to 4 should be assigned the else statement and thus "f". Is this due to the different dimensions of the ifelse conditions, i.e. the first ifelse condition is based on a single element whereas the second is supposed to evaluate every row of a$foo individually, which it does not seem to do.

The larger function not shown here uses an is.na() condition inside the first ifelse loop. I am, however, suspecting that it's not due to the is.na statement but more likely due to the fact that I am using two ifelse conditions that call elements from two different data frames.

UPDATE: Prem's solution to add rowwise() to the pipe fixed the issue for the simplified example given above but unfortunately not for the more complicated example. The more complicated example uses lapply to apply the function to a list of data frames (a,b,c and d). As in the simplified example above it uses a second data frame as a look up table for the first ifelse statement. Here is the code:

```<code>a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))

List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)

List2 <- lapply(seq_along(List), function(i) {
  a <- filter(LookUp, bar == names(List[i]))
temp <- List[[i]] %>%
  rowwise() %>%
  mutate(foo1 = ifelse(is.na(LookUp$foo[1]), NA,
                       ifelse(List[[i]]$foo == "a", "a", "f"))) %>%
  data.frame()
} )
</code>```

Now for all data frames all values in the new column foo1 are assigned the value "a". What I want is foo1 = c("a","f","f","f") for all list elements except list element 2, which should give me foo1 = c(NA, NA, NA, NA) given the first ifelse statement.

Also, some of the data frames in my list are very large. Rowwise() substantially slows down the function. Is there a better/faster way to code my function?

UPDATE 2: My apologies for further complicating this issue. Prem's second solution using Map() worked a charm for the example I had given. Unfortunately, I made a mistake in my more complex example. I specified to use is.na(LookUp$foo[1]) in the first ifelse statement instead of is.na(a$foo[1]) as intended. a is the subset lookup table storing information about the variable names for each element of my list. If I change my code to is.na(a$foo[1]), however, the Map() solution no longer works because the function does not specify how to cycle through i. I want the code to subset the lookup table differently for each function run. The updated value of b$bar should therefore be c(NA,NA,NA,NA)
Code below is the updated one.

```<code>a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))

List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)

List2 <- lapply(seq_along(List), function(i) {
  LookUp2 <- filter(LookUp, bar == names(List[i]))
temp <- List[[i]] %>%
  rowwise() %>%
  mutate(foo1 = ifelse(is.na(LookUp2$bar[1]), NA,
                       ifelse(List[[i]]$foo == "a", "a", "f"))) %>%
  data.frame()
} )
</code>```

I tried to add name as a second vector that allows me to dynamically change i in my function following what has been suggested in this post How do I extract the index or name of the list item within FUN of lapply? but without success. It continues to give me identical row values within and between list elements.
Thanks for your help and patience.

```<code>a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","a","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","a","a","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","a","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))
List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)
List_new <- Map(function(x, name) {
  i = which(LookUp$bar == name)
  Lookup2 <- filter(LookUp, bar == names(List[i]))
  x %>%
    rowwise() %>%
    mutate(foo1=ifelse(is.na(Lookup2$bar[1]), NA,
                       ifelse(foo == "a", "a", "f")))
}, List, names(List))
List_new
</code>```

Any help would be very much appreciated.

答:
Hope this helps!

```<code>#sample data
a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4))

library(dplyr)
a %>%
  rowwise() %>%
  mutate(foo1 = ifelse(is.na(b$foo[1]), NA,
                             ifelse(foo == "a", "a", "f"))) %>%
  data.frame()
</code>```

Output is:

```<code>  foo bar foo1
1   a   e    a
2   b   f    f
3   c   g    f
4   d   h    f
</code>```

UPDATE: solution to the added requirement

```<code>#sample data
a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))
List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)
List_new <- Map(function(x) {
  x %>%
    rowwise() %>%
    mutate(foo1=ifelse(is.na(LookUp$foo[1]), NA,
                     ifelse(foo == "a", "a", "f")))
}, List)
List_new
</code>```

Body:
Dear stackoverflow community,

I am still a beginner in R and have encountered the following issue that I can't find a solution to on stackoverflow or the wider web. It seems pretty straight forward to me but I have no idea what I am missing or which coding conventions I am violating. The problem below is part of a larger function but the example below reproduces the issue.

I have two data frames a and b and would like to create a new variable foo1 in a using a nested ifelse statement with conditions based on elements from both a and b.

a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4))

a <- mutate(a, foo1 = ifelse(is.na(b$foo[1]), NA,
                             ifelse(a$foo == "a", "a", "f")))

What I would expect or am looking for is the following:
The first ifelse statement checks whether the value in the first row of b is NA.
Since it is not in this case, it should jump to the second ifelse statement and give me

a <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4), foo1=c("a","f","f","f"))

since the first row of a$foo is a and the others are not a (b,c,d).

What it does give me instead is

a <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4), foo1=c("a","a","a","a"))

It prints "a" in all rows of foo1 instead of recognising that rows 2 to 4 should be assigned the else statement and thus "f". Is this due to the different dimensions of the ifelse conditions, i.e. the first ifelse condition is based on a single element whereas the second is supposed to evaluate every row of a$foo individually, which it does not seem to do.

The larger function not shown here uses an is.na() condition inside the first ifelse loop. I am, however, suspecting that it's not due to the is.na statement but more likely due to the fact that I am using two ifelse conditions that call elements from two different data frames.

UPDATE: Prem's solution to add rowwise() to the pipe fixed the issue for the simplified example given above but unfortunately not for the more complicated example. The more complicated example uses lapply to apply the function to a list of data frames (a,b,c and d). As in the simplified example above it uses a second data frame as a look up table for the first ifelse statement. Here is the code:

a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))

List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)

List2 <- lapply(seq_along(List), function(i) {
  a <- filter(LookUp, bar == names(List[i]))
temp <- List[[i]] %>%
  rowwise() %>%
  mutate(foo1 = ifelse(is.na(LookUp$foo[1]), NA,
                       ifelse(List[[i]]$foo == "a", "a", "f"))) %>%
  data.frame()
} )

Now for all data frames all values in the new column foo1 are assigned the value "a". What I want is foo1 = c("a","f","f","f") for all list elements except list element 2, which should give me foo1 = c(NA, NA, NA, NA) given the first ifelse statement.

Also, some of the data frames in my list are very large. Rowwise() substantially slows down the function. Is there a better/faster way to code my function?

UPDATE 2: My apologies for further complicating this issue. Prem's second solution using Map() worked a charm for the example I had given. Unfortunately, I made a mistake in my more complex example. I specified to use is.na(LookUp$foo[1]) in the first ifelse statement instead of is.na(a$foo[1]) as intended. a is the subset lookup table storing information about the variable names for each element of my list. If I change my code to is.na(a$foo[1]), however, the Map() solution no longer works because the function does not specify how to cycle through i. I want the code to subset the lookup table differently for each function run. The updated value of b$bar should therefore be c(NA,NA,NA,NA)
Code below is the updated one.

a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))

List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)

List2 <- lapply(seq_along(List), function(i) {
  LookUp2 <- filter(LookUp, bar == names(List[i]))
temp <- List[[i]] %>%
  rowwise() %>%
  mutate(foo1 = ifelse(is.na(LookUp2$bar[1]), NA,
                       ifelse(List[[i]]$foo == "a", "a", "f"))) %>%
  data.frame()
} )

I tried to add name as a second vector that allows me to dynamically change i in my function following what has been suggested in this post How do I extract the index or name of the list item within FUN of lapply? but without success. It continues to give me identical row values within and between list elements.
Thanks for your help and patience.

a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","a","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","a","a","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","a","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))
List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)
List_new <- Map(function(x, name) {
  i = which(LookUp$bar == name)
  Lookup2 <- filter(LookUp, bar == names(List[i]))
  x %>%
    rowwise() %>%
    mutate(foo1=ifelse(is.na(Lookup2$bar[1]), NA,
                       ifelse(foo == "a", "a", "f")))
}, List, names(List))
List_new

Any help would be very much appreciated.

Body:
Hope this helps!

#sample data
a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c(1,NA,2,3), bar=c(1,2,3,4))

library(dplyr)
a %>%
  rowwise() %>%
  mutate(foo1 = ifelse(is.na(b$foo[1]), NA,
                             ifelse(foo == "a", "a", "f"))) %>%
  data.frame()

Output is:

  foo bar foo1
1   a   e    a
2   b   f    f
3   c   g    f
4   d   h    f

UPDATE: solution to the added requirement

#sample data
a <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
b <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
c <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
d <- data.frame(foo=c("a","b","c","d"), bar=c("e","f","g","h"))
LookUp <- data.frame(foo=c(1,NA,2,3), bar=c("a","b","c","d"))
List <- list(a,b,c,d)
names(List) <- c("a","b","c","d")

library(dplyr)
List_new <- Map(function(x) {
  x %>%
    rowwise() %>%
    mutate(foo1=ifelse(is.na(LookUp$foo[1]), NA,
                     ifelse(foo == "a", "a", "f")))
}, List)
List_new


问:
Angular - close modal window with event
I would like to fire an event when the close button is clicked within the modal window.
The button has the attribute data-dismiss="modal" and doesn't call the click event. Is it possible to have data-dismiss and click event or only click event and close modal from class?

```<code><div class="modal-dialog">
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>
    <h4 class="modal-title">{{modalHeader}}</h4>
  </div>
 </div>
</div>

close() {
    //Can I close modal window manually?
    this.onClose.emit();
  }
</code>```

Method close dont call because button has data-dismiss attribute.

Thank you

答:
In your close function add this

```<code>close() {
    $("#myModal").modal("hide");
}
</code>```

Title: Angular - close modal window with event

Body:
I would like to fire an event when the close button is clicked within the modal window.
The button has the attribute data-dismiss="modal" and doesn't call the click event. Is it possible to have data-dismiss and click event or only click event and close modal from class?

    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>

{{modalHeader}}

close() {
    //Can I close modal window manually?
    this.onClose.emit();
  }

Method close dont call because button has data-dismiss attribute.

Thank you

Body:
In your close function add this

close() {
    $("#myModal").modal("hide");
}


问:
Value types in object stored in heap as well?
I can imagine this question has been asked thousands of times, but I didn't have much luck in finding the answer, plus this is more out of curiosity than need.

Digging into the nuts and bolts of C#, I was wondering since objects are stored in the heap, are the value types within the objects stored in the heap as well or are they placed in the stack?

答: Those are stored on the heap, with the objects themselves.  A good way to think about this is that when an object (that has value types as part of its state) is allocated on the heap, it's value types must live there as well, otherwise those value types would disappear as soon as the stack unwound for the code that created the object.</p>


答:
I Don't think you need a pivot here, Instead you can try this using a combination of Case and Group By. try the Below

```<code>WITH CTE
AS
(
    SELECT
    ID,
    N_WorkD = CASE WHEN Flag = 'N' THEN WorkD ELSE 0 END ,
    N_holiD = CASE WHEN Flag = 'N' THEN holiD ELSE 0 END,
    D_WorkD = CASE WHEN Flag = 'D' THEN WorkD ELSE 0 END ,
    D_holiD = CASE WHEN Flag = 'D' THEN holiD ELSE 0 END
    FROM T1
)
SELECT
  ID,
  N_WorkD = SUM(N_WorkD),
  N_holiD = SUM(N_holiD),
  D_WorkD = SUM(D_WorkD),
  D_holiD = SUM(D_holiD)
  FROM CTE
    GROUP BY ID
</code>```

Sample Result is as below

Check the SQLFiddle Here

Title: How to pivot on SQL-Server multiple columns?

Body:
I am trying to create a SQL Statement to pivot a variable number of rows into a single row. A small subset of the data looks like this:

+--------------+--------+-------+-------+
|      ID      | Flag   | workD | holiD |
+--------------+--------+-------+-------+
| 11155        | N      | 1     | 0     |
| 11155        | D      | 1     | 1     |
| 5675         | N      | 1     | 1     |
| 98761        | N      | 0     | 1     |
| 98761        | D      | 1     | 1     |
+--------------+--------+-------+-------+

and I would like to pivot the data to look like the following:

+--------------+---------+---------+---------+---------+
|      ID      | N_wordD | N_holiD | D_wordD | D_holiD |
+--------------+---------+---------+---------+---------+
| 11155        | 1       | 0       | 1       | 1       |
| 5675         | 1       | 1       | NULL    | NULL    |
| 98761        | 0       | 1       | 1       | 1       |
+--------------+---------+---------+---------+---------+

I am a bit lost when it comes to pivoting, particularly when I want to pivot both the Style and the Quantity into my columns.

Any suggestions, pointers, etc would be greatly appreciated.

Body:
I Don't think you need a pivot here, Instead you can try this using a combination of Case and Group By. try the Below

WITH CTE
AS
(
    SELECT
    ID,
    N_WorkD = CASE WHEN Flag = 'N' THEN WorkD ELSE 0 END ,
    N_holiD = CASE WHEN Flag = 'N' THEN holiD ELSE 0 END,
    D_WorkD = CASE WHEN Flag = 'D' THEN WorkD ELSE 0 END ,
    D_holiD = CASE WHEN Flag = 'D' THEN holiD ELSE 0 END
    FROM T1
)
SELECT
  ID,
  N_WorkD = SUM(N_WorkD),
  N_holiD = SUM(N_holiD),
  D_WorkD = SUM(D_WorkD),
  D_holiD = SUM(D_holiD)
  FROM CTE
    GROUP BY ID

Sample Result is as below

Check the SQLFiddle Here


问:
Checking if an instance in Firebase already exists
I'm attempting to check to see if a string input by a user already exists in my database before I write it in.

Here's what I currently have:

Firebase:

```<code>players
      id:
      playerContent: Firstname Lastname
</code>```

```<code>class PlayerForm extends Component {
  constructor(props) {
    super(props);
    this.state= {
        newPlayerContent: '',
        exists: null
    };

    this.writePlayer = this.writePlayer.bind(this);
    this.checkIfUserExists = this.checkIfUserExists.bind(this);
}

checkIfUserExists(newPlayerContent) {
var playersRef = firebase.database().ref().child('players');

playersRef.once('value', function(snapshot) {
    if (snapshot.hasChild(newPlayerContent)) {
        this.setState({ exists });
    }
  })
 }

writePlayer(){
    if(this.exists !== null){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
    console.log("This player already exists.")
    }
}
</code>```

It keeps allowing it in, regardless. I'm a tad unsure of the checkIfUserExists function, specifically if I'm accessing my data right in firebase. I'm outputting the content of newPlayerContent to the console and it is in fact what I input, but I'm not sure if the check is doing its job. Does anything stand out here?

Thanks in advance.

答:
I used duplicate instead of exists .. but this code seems to do exactly as I wish. It won't let you add another person to the database if it already sees that player name in the name field (playerContent).

```<code>var playersRef = firebase.database().ref();
playersRef.child('players').orderByChild("playerContent").equalTo(newPlayerContent).once("value",snapshot => {
    const userData = snapshot.val();
    if (userData){
      console.log("exists!");

      this.state.duplicate = true;

      console.log(this.state.duplicate)
    }
    else{
      console.log("does not exist.")
      this.state.duplicate = false;
      console.log(this.state.duplicate)
    }
});
</code>```

In the writePlayer function:

```<code>if(this.state.duplicate !== true){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
    console.log("This player already exists.")
    }
</code>```

Thought, this does throw a warning —

Do not mutate state directly. Use setState()
  react/no-direct-mutation-state

Body:
I'm attempting to check to see if a string input by a user already exists in my database before I write it in.

Here's what I currently have:

Firebase:

players
      id:
      playerContent: Firstname Lastname

class PlayerForm extends Component {
  constructor(props) {
    super(props);
    this.state= {
        newPlayerContent: '',
        exists: null
    };

    this.writePlayer = this.writePlayer.bind(this);
    this.checkIfUserExists = this.checkIfUserExists.bind(this);
}

checkIfUserExists(newPlayerContent) {
var playersRef = firebase.database().ref().child('players');

playersRef.once('value', function(snapshot) {
    if (snapshot.hasChild(newPlayerContent)) {
        this.setState({ exists });
    }
  })
 }

writePlayer(){
    if(this.exists !== null){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
    console.log("This player already exists.")
    }
}

It keeps allowing it in, regardless. I'm a tad unsure of the checkIfUserExists function, specifically if I'm accessing my data right in firebase. I'm outputting the content of newPlayerContent to the console and it is in fact what I input, but I'm not sure if the check is doing its job. Does anything stand out here?

Thanks in advance.

Body:
I used duplicate instead of exists .. but this code seems to do exactly as I wish. It won't let you add another person to the database if it already sees that player name in the name field (playerContent).

var playersRef = firebase.database().ref();
playersRef.child('players').orderByChild("playerContent").equalTo(newPlayerContent).once("value",snapshot => {
    const userData = snapshot.val();
    if (userData){
      console.log("exists!");

      this.state.duplicate = true;

      console.log(this.state.duplicate)
    }
    else{
      console.log("does not exist.")
      this.state.duplicate = false;
      console.log(this.state.duplicate)
    }
});

In the writePlayer function:

if(this.state.duplicate !== true){
    this.props.addPlayer(this.state.newPlayerContent);
    this.setState({
        newPlayerContent: '',
        })
    }
    else{
    console.log("This player already exists.")
    }

Thought, this does throw a warning —

Do not mutate state directly. Use setState()
  react/no-direct-mutation-state


问:
Class admin does not exist
Having problem with Laravel 5.5. Simple website is working fine. But when I access admin panel I get this error after logging in.

ReflectionException thrown with message "Class admin does not exist"

app\Http\Middleware\Admin.php

```<code><?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\Auth;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check() && Auth::user()->isAdmin()){

            return $next($request);
        }
        return redirect('home');
    }
}
</code>```

web.php

```<code>Auth::routes();
Route::group(['prefix'=>'admin','middleware'=>['auth','admin']], function(){

    Route::post('toggledeliver/{orderId}','OrderController@toggledeliver')->name('toggle.deliver');

    Route::post('toggledeliver/{productId}','ProductsController@toggledeliver')->name('product.deliver');

    Route::get('/',function(){
        return view('admin.index');
    })->name('admin.index');
});
</code>```

答:
After creating middleware you need to register it in app/http/Kernel.php file in protected $routeMiddleware array! Then you can use this middleware in your routes(web.php/api.php)

Like this:

```<code>protected $routeMiddleware = [
    'admin' => 'App\Http\Middleware\Admin',
];
</code>```

Hope this helps you!

Title: Class admin does not exist

Body:
Having problem with Laravel 5.5. Simple website is working fine. But when I access admin panel I get this error after logging in.

ReflectionException thrown with message "Class admin does not exist"

app\Http\Middleware\Admin.php

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Support\Facades\Auth;

class Admin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check() && Auth::user()->isAdmin()){

            return $next($request);
        }
        return redirect('home');
    }
}

web.php

Auth::routes();
Route::group(['prefix'=>'admin','middleware'=>['auth','admin']], function(){

    Route::post('toggledeliver/{orderId}','OrderController@toggledeliver')->name('toggle.deliver');

    Route::post('toggledeliver/{productId}','ProductsController@toggledeliver')->name('product.deliver');

    Route::get('/',function(){
        return view('admin.index');
    })->name('admin.index');
});

Body:
After creating middleware you need to register it in app/http/Kernel.php file in protected $routeMiddleware array! Then you can use this middleware in your routes(web.php/api.php)

Like this:

protected $routeMiddleware = [
    'admin' => 'App\Http\Middleware\Admin',
];

Hope this helps you!


问:
Difference between returning a value and returning Promise.resolve() from a function
I have problem in understanding that what happens when we simply return a value or when we return Promise.resolve() from a function. Specifically: I am trying to understand how promises chaining works. I am chaining methods and verifying whether the value reaches in the method which is last call to then. I just want to understand the difference between returning promises to then, returning Promise.resolve() to then, and returning just a value to then.

答:
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future. MDN

The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; if the value was a promise, that object becomes the result of the call to Promise.resolve; otherwise the returned promise will be fulfilled with the value. MDN Promise.reslove

Returning a value from a function is synchronous unlike Promise.resolve()


问:
ExecuteScalar throws NullReferenceException when calling a stored proc that returns 1
I've done some research before posting this question and I'm aware of the fact that when there's no data returned, ExecuteScalar will throw  a System.NullReferenceException. That is why I modified my stored proc to "return 1" so there's guaranteed a return value. However, I'm still getting the NULL reference exception.

So I tried to use the SqlCommand to query a table that has data:

```<code>        SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)
</code>```

When I ran execute scalar I was able to pick up a value so I know I have permission to query the database. I'm suspecting that this is some specific storeed proc permission setting that I missed?

I'd really appreciate any comment/suggestions as I've been stuck on this for a day now. :(

My code looks like this:

```<code>        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand("GetSomeValue", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                //sqlCommand.Parameters.Add(new SqlParameter("@Id", this.ID));
                //sqlCommand.Parameters.Add(new SqlParameter("@State", 1 /* active */));

                byte retValue = (byte)sqlCommand.ExecuteScalar();
                return retValue;
            }
        }
</code>```

THANKS!

答:
Random guess

You are using RETURN so there is no dataset to read column 1, row 1 for ExecuteScalar

Use SELECT or OUTPUT parameters

Edit: Actually, not so random

RETURN 1 is not a result set: it's a "special" parameter

```<code>sqlCmd.Parameters.Add(New SqlParameter("RETURN_VALUE", SqlDbType.Int)).Direction = ParameterDirection.ReturnValue
</code>```

Body:
I've done some research before posting this question and I'm aware of the fact that when there's no data returned, ExecuteScalar will throw  a System.NullReferenceException. That is why I modified my stored proc to "return 1" so there's guaranteed a return value. However, I'm still getting the NULL reference exception.

So I tried to use the SqlCommand to query a table that has data:

        SqlCommand sqlCommand = new SqlCommand("SELECT * FROM ATableThatHasValues", conn)

When I ran execute scalar I was able to pick up a value so I know I have permission to query the database. I'm suspecting that this is some specific storeed proc permission setting that I missed?

I'd really appreciate any comment/suggestions as I've been stuck on this for a day now. :(

My code looks like this:

        using (SqlConnection sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();
            using (SqlCommand sqlCommand = new SqlCommand("GetSomeValue", sqlConnection))
            {
                sqlCommand.CommandType = CommandType.StoredProcedure;
                //sqlCommand.Parameters.Add(new SqlParameter("@Id", this.ID));
                //sqlCommand.Parameters.Add(new SqlParameter("@State", 1 /* active */));

                byte retValue = (byte)sqlCommand.ExecuteScalar();
                return retValue;
            }
        }

THANKS!

Body:
Random guess

You are using RETURN so there is no dataset to read column 1, row 1 for ExecuteScalar

Use SELECT or OUTPUT parameters

Edit: Actually, not so random

RETURN 1 is not a result set: it's a "special" parameter

sqlCmd.Parameters.Add(New SqlParameter("RETURN_VALUE", SqlDbType.Int)).Direction = ParameterDirection.ReturnValue


问:
iOS 11 FileProvider NSFileProviderRootContainerItemIdentifier
I'm trying to developing a FileProvider Extension for iOS 11.But I run into a weird problem.

```<code>- (nullable NSFileProviderItem)itemForIdentifier:(NSFileProviderItemIdentifier)identifier error:(NSError * _Nullable *)error
</code>```

In this method,the identifier always is NSFileProviderRootContainerItemIdentifier.According to Apple's Document,this identifier supposes to be unique.

how should I implement this method?

Thanks a lot!

答:
Return a new NSFileProviderItem For NSFileProviderRootContainerItemIdentifier.

don't return nil,that will cause a problem when try to use Filprovider extension in other app.

Body:
I'm trying to developing a FileProvider Extension for iOS 11.But I run into a weird problem.

- (nullable NSFileProviderItem)itemForIdentifier:(NSFileProviderItemIdentifier)identifier error:(NSError * _Nullable *)error

In this method,the identifier always is NSFileProviderRootContainerItemIdentifier.According to Apple's Document,this identifier supposes to be unique.

how should I implement this method?

Thanks a lot!


问:
Syntax highlighting Markdown via Assemble.io - incomplete
Am I missing something? I have a rendering pipeline set up with assemble.io via an express server and everything is rendering as expected. However, when I add in bracket fences for Markdown there seems to be an issue with the syntax highlighting. It does drop the code into  and ``` tags as expected and when I add in the language identifier after the top fence it does add in the class="language-[LANG] like you would think it would, however, it does nothing to the code within it (e.g. wrapping the tag elements, attributes, important names, etc. in span tags).

Is there a helper I need to add to the pipeline and pass the file through? So far I've tried adding prismjs, but that flattened the entire page into code (not ideal).

Result:
this is the link

Expected:
<a href="">this is the link

答:
Looking at the markdown documentation directly or at the assemble.io documentation does no good.

It's clearly listed on the helper-markdown github/npm sites respectivly.

Body:
Am I missing something? I have a rendering pipeline set up with assemble.io via an express server and everything is rendering as expected. However, when I add in bracket fences for Markdown there seems to be an issue with the syntax highlighting. It does drop the code into  and
 tags as expected and when I add in the language identifier after the top fence it does add in the class="language-[LANG] like you would think it would, however, it does nothing to the code within it (e.g. wrapping the tag elements, attributes, important names, etc. in span tags).

Is there a helper I need to add to the pipeline and pass the file through? So far I've tried adding prismjs, but that flattened the entire page into code (not ideal).

Result:
this is the link

Expected:
<a href="">this is the link


问:
Trouble in scraping specific element from a page using beautifulsoup python
I am new to python and looking into scraping HTML using python beautifulsoup library.

I need to fetch date field value as Day and date and precip field value as well as measuring unit .

Python code

    dates=[]
Precip=[]
for row in right_table.findAll("tr"):
    cells = row.findAll('td')
    th_cells=row.findAll('th') #To store second column data
    if len(cells)==5:
        Precip.append(cells[1].find(text=True))
        dates.append(th_cells[0].find(text=True))
print(dates)
print(Precip)```
</div>
</div>
</p>

<p><strong>Code Output</strong></p>

```['Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ']
['0 ', '0 ', '0 ', '1 ', '3 ', '3 ', '13 ', '0 ', '0 ', '0 ', '0 ', '0 ', '\xa0', '1 ', '3 ', '0 ', '1 ', '4 ', '2 ', '9 ', '2 ', '0 ', '1 ', '0 ', '0 ', '0 ', '0 ', '0 ', '1 ', '2 ']
```

<p><strong>Required Output</strong></p>

```['Wed 11/1','Thur 11/2'.......]

['0mm','0mm'....]
```

<p>Below is the HTML which i am trying to parse</p>

<p><strong>HTML</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><class 'list'>: ['\n', <thead>
<tr>
<th>Date</th>
<th>Hi/Lo</th>
<th>Precip</th>
<th>Snow</th>
<th>Forecast</th>
<th>Avg. HI / LO</th>
</tr>
</thead>, '\n', <tbody>
<tr class="pre">
<th scope="row">Wed <time>11/1</time></th>
<td>25°/20°</td>
<td>0 <span class="small">mm</span></td>
<td>0 <span class="small">CM</span></td>
<td> </td>
<td>28°/18°</td>
</tr>
<tr class="pre">
<th scope="row">Thu <time>11/2</time></th>
<td>28°/19°</td>
<td>0 <span class="small">mm</span></td>
<td>0 <span class="small">CM</span></td>
<td> </td>
<td>27°/18°</td>
</tr></code>```

答:
I'd use .text instead of .find(text=true).  What's currently happening is you're not fetching the content of the subtags, like <time>.

```<code>from bs4 import BeautifulSoup
import requests

html = requests.get("https://www.accuweather.com/en/in/bengaluru/204108/month/204108?view=table").text
soup = BeautifulSoup(html, 'html.parser')

right_table = soup.find("tbody")
dates=[]
Precip=[]
for row in right_table.findAll("tr"):
    cells = row.findAll('td')
    th_cells=row.findAll('th') #To store second column data
    if len(cells)==5:
        Precip.append(cells[1].text)
        dates.append(th_cells[0].text)
print(dates)
print(Precip)
</code>```

This gets the correct outputted result:

```<code>['Wed 11/1', 'Thu 11/2', 'Fri 11/3', 'Sat 11/4', 'Sun 11/5', 'Mon 11/6', 'Tue 11/7', 'Wed 11/8', 'Thu 11/9', 'Fri 11/10', 'Sat 11/11', 'Sun 11/12', 'Mon 11/13', 'Tue 11/14', 'Wed 11/15', 'Thu 11/16', 'Fri 11/17', 'Sat 11/18', 'Sun 11/19', 'Mon 11/20', 'Tue 11/21', 'Wed 11/22', 'Thu 11/23', 'Fri 11/24', 'Sat 11/25', 'Sun 11/26', 'Mon 11/27', 'Tue 11/28', 'Wed 11/29', 'Thu 11/30']
['0 mm', '0 mm', '0 mm', '1 mm', '3 mm', '3 mm', '13 mm', '0 mm', '0 mm', '0 mm', '0 mm', '0 mm', '\xa0', '1 mm', '3 mm', '0 mm', '1 mm', '4 mm', '2 mm', '9 mm', '2 mm', '0 mm', '1 mm', '0 mm', '0 mm', '0 mm', '0 mm', '0 mm', '1 mm', '2 mm']
</code>```

Body:
I am new to python and looking into scraping HTML using python beautifulsoup library.

I need to fetch date field value as Day and date and precip field value as well as measuring unit .

Python code

    dates=[]
Precip=[]
for row in right_table.findAll("tr"):
    cells = row.findAll('td')
    th_cells=row.findAll('th') #To store second column data
    if len(cells)==5:
        Precip.append(cells[1].find(text=True))
        dates.append(th_cells[0].find(text=True))
print(dates)
print(Precip)

Code Output

['Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Mon ', 'Tue ', 'Wed ', 'Thu ']
['0 ', '0 ', '0 ', '1 ', '3 ', '3 ', '13 ', '0 ', '0 ', '0 ', '0 ', '0 ', '\xa0', '1 ', '3 ', '0 ', '1 ', '4 ', '2 ', '9 ', '2 ', '0 ', '1 ', '0 ', '0 ', '0 ', '0 ', '0 ', '1 ', '2 ']

Required Output

['Wed 11/1','Thur 11/2'.......]

['0mm','0mm'....]

Below is the HTML which i am trying to parse

HTML

<class 'list'>: ['\n',

Date
Hi/Lo
Precip
Snow
Forecast
Avg. HI / LO

, '\n',

Wed <time>11/1</time>
25°/20°
0 mm
0 CM

28°/18°

Thu <time>11/2</time>
28°/19°
0 mm
0 CM

27°/18°

Body:
I'd use .text instead of .find(text=true).  What's currently happening is you're not fetching the content of the subtags, like <time>.

from bs4 import BeautifulSoup
import requests

html = requests.get("https://www.accuweather.com/en/in/bengaluru/204108/month/204108?view=table").text
soup = BeautifulSoup(html, 'html.parser')

right_table = soup.find("tbody")
dates=[]
Precip=[]
for row in right_table.findAll("tr"):
    cells = row.findAll('td')
    th_cells=row.findAll('th') #To store second column data
    if len(cells)==5:
        Precip.append(cells[1].text)
        dates.append(th_cells[0].text)
print(dates)
print(Precip)

This gets the correct outputted result:

['Wed 11/1', 'Thu 11/2', 'Fri 11/3', 'Sat 11/4', 'Sun 11/5', 'Mon 11/6', 'Tue 11/7', 'Wed 11/8', 'Thu 11/9', 'Fri 11/10', 'Sat 11/11', 'Sun 11/12', 'Mon 11/13', 'Tue 11/14', 'Wed 11/15', 'Thu 11/16', 'Fri 11/17', 'Sat 11/18', 'Sun 11/19', 'Mon 11/20', 'Tue 11/21', 'Wed 11/22', 'Thu 11/23', 'Fri 11/24', 'Sat 11/25', 'Sun 11/26', 'Mon 11/27', 'Tue 11/28', 'Wed 11/29', 'Thu 11/30']
['0 mm', '0 mm', '0 mm', '1 mm', '3 mm', '3 mm', '13 mm', '0 mm', '0 mm', '0 mm', '0 mm', '0 mm', '\xa0', '1 mm', '3 mm', '0 mm', '1 mm', '4 mm', '2 mm', '9 mm', '2 mm', '0 mm', '1 mm', '0 mm', '0 mm', '0 mm', '0 mm', '0 mm', '1 mm', '2 mm']


问:
How to access the ajax submitted data in PHP from javascript FormData
I have the following code to upload a file along with a user_id and a token via ajax post:

HTML Form:

```<code><?php foreach($model['all_documents'] as $doc=>$val){ ?>
<form enctype="multipart/form-data" class="form">
  <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
  <input type="hidden" name="user_id" value="<?=$model['user_id']?>" />
  <button type="button" class="col-md-7 btn btn-default documentUpload form-control">
    <i class="fa fa-file-image-o"></i> انتخاب اسکن
  </button>
  <input type="file" name="<?=$doc?>" class="documentUpload" style="display: none;" />
  <button class="col-md-4 btn btn-primary form-control submit pull-left">
    <i class="fa fa-upload"></i> آپلود
  </button>
</form>
<?php } ?>
</code>```

Javascript:

```<code>$(".form").submit(function(){
  var formData = new FormData(this);
  console.info(formData); // Shows FormData(), but can't find my stuff in it

  $.ajax({
    url: '<?=Yii::$app->homeUrl?>courier/upload-document',
    type: 'POST',
    data: formData,
    async: false,
    processData: false,
    // beforeSend: function(){
    // },
    success: function(data){
      console.log(data);
    }
  });
  return false;
});
</code>```

I tried to access the user_id and file like:

```<code>// $user_id = $_POST['user_id']; // Nothing
// $docs = $_FILES['image_url']; // Nothing
print_r($_POST);exit;
</code>```

What I get in my chrome's network response is as follows:

```<code>Array
(
    [------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition:_form-data;_name] => "_csrf"

dy5nWlJFb1U6dwg.FwshCjZ5NANmd1tkFFcdFh8sLgcnQQQxZzwoOA==
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="user_id"

456
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="image_url"; filename="avatar3.png"
Content-Type: image/png

�PNG

IHDR����4�PLTE�ɦ!!!�e<"""���r=-�Y<����cB   �����`@��^?����G2�ȥ�R8u>-�K4�aA�[=�D0����Z<�\=�W;�Ƥ�S9�P6�N6����ma�ġ��������Ÿ_>���UF<�Y<��������U:����ͭޏh纥�y@.|B/���ի��I3�~V�jA��ϻ�������Ѵ�m[����oG�L5Ɵ����쩅.,
</code>```

答:
Use

```<code>var formData = $(this).serializeArray();
</code>```

or

```<code>var formData = $(".form").serializeArray();
</code>```

or

```<code>var formData = $(".form").serialize();
</code>```

So that your code would look like this:

```<code>$(".form").submit(function(){
  var formData = $(this).serializeArray();
  console.log(formData);

  $.ajax({
    url: '<?=Yii::$app->homeUrl?>courier/upload-document',
    type: 'POST',
    data: formData,
    async: false,
    processData: false,
    // beforeSend: function(){
    // },
    success: function(data){
      console.log(data);
    }
  });
  return false;
});
</code>```

Next in your PHP code try checking whether these things work as you did.

```<code>$user_id = $_POST['user_id'];
$docs = $_FILES['image_url'];
print_r($_POST);
exit;
</code>```

UPDATED:

The serialize() method does not send files.
If you need to upload files with the serialize(), you could either get the base64 value and send it as a string. The serialize() method is supported in even old browsers which does not recognize the formData() API. That is the only advantage of this method.

If you want to use the formData() API in order to upload files, then you may refer this guide.

Body:
I have the following code to upload a file along with a user_id and a token via ajax post:

HTML Form:

<?php foreach($model['all_documents'] as $doc=>$val){ ?>
<form enctype="multipart/form-data" class="form">
  <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
  <input type="hidden" name="user_id" value="<?=$model['user_id']?>" />
  <button type="button" class="col-md-7 btn btn-default documentUpload form-control">
     انتخاب اسکن
  </button>
  <input type="file" name="<?=$doc?>" class="documentUpload" style="display: none;" />
  <button class="col-md-4 btn btn-primary form-control submit pull-left">
     آپلود
  </button>
</form>
<?php } ?>

Javascript:

$(".form").submit(function(){
  var formData = new FormData(this);
  console.info(formData); // Shows FormData(), but can't find my stuff in it

  $.ajax({
    url: '<?=Yii::$app->homeUrl?>courier/upload-document',
    type: 'POST',
    data: formData,
    async: false,
    processData: false,
    // beforeSend: function(){
    // },
    success: function(data){
      console.log(data);
    }
  });
  return false;
});

I tried to access the user_id and file like:

// $user_id = $_POST['user_id']; // Nothing
// $docs = $_FILES['image_url']; // Nothing
print_r($_POST);exit;

What I get in my chrome's network response is as follows:

Array
(
    [------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition:_form-data;_name] => "_csrf"

dy5nWlJFb1U6dwg.FwshCjZ5NANmd1tkFFcdFh8sLgcnQQQxZzwoOA==
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="user_id"

456
------WebKitFormBoundaryk0378isAjf4Png8L
Content-Disposition: form-data; name="image_url"; filename="avatar3.png"
Content-Type: image/png

�PNG

IHDR����4�PLTE�ɦ!!!�e<"""���r=-�Y<����cB   �����`@��^?����G2�ȥ�R8u>-�K4�aA�[=�D0����Z<�\=�W;�Ƥ�S9�P6�N6����ma�ġ��������Ÿ_>���UF<�Y<��������U:����ͭޏh纥�y@.|B/���ի��I3�~V�jA��ϻ�������Ѵ�m[����oG�L5Ɵ����쩅.,

Body:
Use

var formData = $(this).serializeArray();

or

var formData = $(".form").serializeArray();

or

var formData = $(".form").serialize();

So that your code would look like this:

$(".form").submit(function(){
  var formData = $(this).serializeArray();
  console.log(formData);

  $.ajax({
    url: '<?=Yii::$app->homeUrl?>courier/upload-document',
    type: 'POST',
    data: formData,
    async: false,
    processData: false,
    // beforeSend: function(){
    // },
    success: function(data){
      console.log(data);
    }
  });
  return false;
});

Next in your PHP code try checking whether these things work as you did.

$user_id = $_POST['user_id'];
$docs = $_FILES['image_url'];
print_r($_POST);
exit;

UPDATED:

The serialize() method does not send files.
If you need to upload files with the serialize(), you could either get the base64 value and send it as a string. The serialize() method is supported in even old browsers which does not recognize the formData() API. That is the only advantage of this method.

If you want to use the formData() API in order to upload files, then you may refer this guide.