问:
Getting empty array in PHP while using $.ajax
I have this jQuery $.ajax script:

```<code>var data = JSON.stringify( selected_products );

$.ajax({ type: "POST",
    url: "addtocart.php",
    data: data,
    dataType: 'application/json'
});
</code>```

And I am posting this to a really simple PHP script:

```<code>$selected_products = json_decode($_POST['data'], true);
print_r($selected_products);
</code>```

This is an example of what I'm sending; this is outgoing data in Chrome DevTools:

```<code>data:[{"id":"RECOLOURBALM","option":"Black","quantity":1},{"id":"TOWELS","quantity":1}]
</code>```

However this is the console readout for the response:

```<code>Array
(
)
</code>```

I think the request is succeeding and data is being passed, but the responses are all empty.

What am I doing wrong?

答:
```<code>$selected_products = json_decode($_POST['data'], true);
echo $selected_products[0]['id'];
echo '<br>';
echo $_POST;
echo '<br>';
var_dump($_POST);
</code>```

add data to your post

You are now getting null that's because of the stringify given there. Please change the code like this.It will surely work.

```<code>var data=[{"id":"RECOLOURBALM","option":"Bordeaux","quantity":1},{"id":"TOWELS","quantity":1}];
//data = JSON.stringify(data);
$.ajax({
    type: "POST",
    url: "addtocart.php",
    data: {'data':data},
    success:function(returndata){
        console.log(returndata);
    }
});
</code>```

Remove the stringify.

Body:
I have this jQuery $.ajax script:

var data = JSON.stringify( selected_products );

$.ajax({ type: "POST",
    url: "addtocart.php",
    data: data,
    dataType: 'application/json'
});

And I am posting this to a really simple PHP script:

$selected_products = json_decode($_POST['data'], true);
print_r($selected_products);

This is an example of what I'm sending; this is outgoing data in Chrome DevTools:

data:[{"id":"RECOLOURBALM","option":"Black","quantity":1},{"id":"TOWELS","quantity":1}]

However this is the console readout for the response:

Array
(
)

I think the request is succeeding and data is being passed, but the responses are all empty.

What am I doing wrong?

Body:
$selected_products = json_decode($_POST['data'], true);
echo $selected_products[0]['id'];
echo '<br>';
echo $_POST;
echo '<br>';
var_dump($_POST);

add data to your post

You are now getting null that's because of the stringify given there. Please change the code like this.It will surely work.

var data=[{"id":"RECOLOURBALM","option":"Bordeaux","quantity":1},{"id":"TOWELS","quantity":1}];
//data = JSON.stringify(data);
$.ajax({
    type: "POST",
    url: "addtocart.php",
    data: {'data':data},
    success:function(returndata){
        console.log(returndata);
    }
});

Remove the stringify.


来源: stackexchange

问:
Javascript Date.now to readable format
```<code>Date.now();
</code>```

I want to convert the timestamp to readable format

e.g "Fri Nov 17 2017 19:15:15 GMT+0800 (Malay Peninsula Standard Time)"

答:
Just new Date();

document.getElementById("demo").innerHTML = Date();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p></code>```

ContentLicense: CC BY-SA 3.0

Title: Javascript Date.now to readable format

Body:
Date.now();

I want to convert the timestamp to readable format

e.g "Fri Nov 17 2017 19:15:15 GMT+0800 (Malay Peninsula Standard Time)"

Body:
Just new Date();

document.getElementById("demo").innerHTML = Date();

<p id="demo"></p>


问:
Csv Helper. First Value is shifting to the right
I have been trying to create a simple csv file using the csv helper. However, the result, I am getting is not what I expected.
For some reason which I cannot find it, the first value is shifting towards the right and appear as the header.

Could someone point me what I am doing wrong here?

```<code>public class Record
{
    public string Vrm { get; set; }
    public string Version { get; set; }
    public DateTime Started { get; set; }
    public DateTime? Completed { get; set; }
    public string Status { get; set; }
    public string Comments { get; set; }
}

static void Main(string[] args)
    {
        var source = new List<Record> {
            new Record {

                Status = "Success",
                Version = "enhance",
                Started = DateTime.Parse("2017-11-15 13:27:56.9933333"),
                Completed = DateTime.Parse("2017-11-15 13:27:57.7300000"),
                Vrm = "16aux",
                Comments = "Completed Successfully"
            }
        };

        var month = DateTime.UtcNow.Month;
        var year = DateTime.UtcNow.Year;
        var fileName = $"TestFile_{month}{year}.csv";

        using (var sw = new StreamWriter(fileName))
        {
            var writer = new CsvWriter(sw);

            try
            {
                writer.WriteHeader<Record>();
                foreach (var record in source)
                {
                    writer.WriteField(record.Vrm);
                    writer.WriteField(record.Version);
                    writer.WriteField(record.Started);
                    writer.WriteField(record.Completed);
                    writer.WriteField(record.Status);
                    writer.WriteField(record.Comments);
                    writer.NextRecord();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var i = sw;
        }
    }
</code>```

The result is something like this:

答:
Read up on http://joshclose.github.io/CsvHelper/writing#writing-all-records

You need to advance the writer one line by calling writer.NextRecord(); after writer.WriteHeader<Record>();.

You could also simply write all data at once, using csv.WriteRecords( records ); instead of foreaching over them

Body:
I have been trying to create a simple csv file using the csv helper. However, the result, I am getting is not what I expected.
For some reason which I cannot find it, the first value is shifting towards the right and appear as the header.

Could someone point me what I am doing wrong here?

public class Record
{
    public string Vrm { get; set; }
    public string Version { get; set; }
    public DateTime Started { get; set; }
    public DateTime? Completed { get; set; }
    public string Status { get; set; }
    public string Comments { get; set; }
}

static void Main(string[] args)
    {
        var source = new List<Record> {
            new Record {

                Status = "Success",
                Version = "enhance",
                Started = DateTime.Parse("2017-11-15 13:27:56.9933333"),
                Completed = DateTime.Parse("2017-11-15 13:27:57.7300000"),
                Vrm = "16aux",
                Comments = "Completed Successfully"
            }
        };

        var month = DateTime.UtcNow.Month;
        var year = DateTime.UtcNow.Year;
        var fileName = $"TestFile_{month}{year}.csv";

        using (var sw = new StreamWriter(fileName))
        {
            var writer = new CsvWriter(sw);

            try
            {
                writer.WriteHeader<Record>();
                foreach (var record in source)
                {
                    writer.WriteField(record.Vrm);
                    writer.WriteField(record.Version);
                    writer.WriteField(record.Started);
                    writer.WriteField(record.Completed);
                    writer.WriteField(record.Status);
                    writer.WriteField(record.Comments);
                    writer.NextRecord();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            var i = sw;
        }
    }

The result is something like this:


问:
Windows Server 2012 - MSMQ - Journaling keeps disabling itself
I'm trying to enabling journaling on my 2012 server - I have x2 queues on the host. One, I was able to enable this function and it has since stayed enabled. The other queue, I enable journaling on and it seems to be enabled, but after a few refreshes I go back into properties and it's turned itself off again.

The queue is used by a few applications - An IIS app and a custom service. Haven't tried to disable these as they are in constant use. Could this be the cause.

With the limit on the queue, what's the easiest way to check what the current storage quota is at?

Cheers all.

答: Setting journaling will make changes to the corresponding text file in the C:\Windows\System32\msmq\storage\lqs folder. Find the weirdly named text file that matches your private queue. It will contain "Journal=01" if journaling enabled and "JournalQuota=12345" for the journal storage limit. If journaling is disabled after you switch it on, check the date/time stamp on the file to see if it has been updated. If no change in date then MSMQ isn't writing the changes to the file for some reason. If the date is changed but the journal settings are off then there must be some other process telling MSMQ to disable journaling (but that would mean a process monitoring journaling to ensure it isn't switched on). Try manually editing the file yourself in a text editor and see what happens; would need to restart the service to make MSMQ pick up the change.</p>


问:
How to Set & Get in angular2-localstorage?
From this repo, I've successfully configured this:

```<code>import {Component} from "angular2/core";
import {LocalStorageService} from "angular2-localstorage/LocalStorageEmitter";

@Component({
    provider: [LocalStorageService]
})
export class AppRoot{
    constructor(private storageService: LocalStorageService){}
...
}
</code>```

How can I use storageService to set or get in local storage? I can't find example anywhere even in the doc.

Updated

After some testing, I've managed it to get it working with Decorator through WebStorage:

```<code>import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class LoginComponent implements OnInit {
   @LocalStorage() public username:string = 'hello world';
     ngOnInit() {
         console.log('username', this.username);
         // it prints username hello world
     }
}
</code>```

However, when I used Chrome Dev to see my localstorage, I see nothing there:

And In another component,

```<code>import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class DashboardComponent implements OnInit {
   @LocalStorage() public username:string;
     ngOnInit() {
         console.log(this.username);
         // it prints null
     }
}
</code>```

答:
I would prefer to create a separate Injectable service </p>

```<code>import { Injectable } from '@angular/core';
@Injectable()
export class LocalStorageService {

    constructor() {
        //
    }

    public setData(key:string, data:any) {
        localStorage.setItem(key, JSON.stringify(data));
    }
    public getData(key:string) {
        return JSON.parse(localStorage.getItem(key));
    }

    public removeData(key:string) {
        localStorage.removeItem(key);
    }
}
</code>```

<p>And in your component </p>

```<code>import { LocalStorageService } from './../../services/localStorageService';
@Component({
    selector: 'member-claims-modal',
    templateUrl: './view.html'
})

export class UserComponent {
constructor(private localStorageService:LocalStorageService) {
        super();
    }
    public SampleMethod() {
    let cloneData = {
            'claims': 'hello'
        };
    this.localStorageService.setData('claims', cloneData);
    let item=this.localStorageService.getData('claims');
    consoloe.log(item);
    this.localStorageService.removeData('claims');
    }
}
</code>```

Body:
From this repo, I've successfully configured this:

import {Component} from "angular2/core";
import {LocalStorageService} from "angular2-localstorage/LocalStorageEmitter";

@Component({
    provider: [LocalStorageService]
})
export class AppRoot{
    constructor(private storageService: LocalStorageService){}
...
}

How can I use storageService to set or get in local storage? I can't find example anywhere even in the doc.

Updated

After some testing, I've managed it to get it working with Decorator through WebStorage:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class LoginComponent implements OnInit {
   @LocalStorage() public username:string = 'hello world';
     ngOnInit() {
         console.log('username', this.username);
         // it prints username hello world
     }
}

However, when I used Chrome Dev to see my localstorage, I see nothing there:

And In another component,

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class DashboardComponent implements OnInit {
   @LocalStorage() public username:string;
     ngOnInit() {
         console.log(this.username);
         // it prints null
     }
}

Body:
I would prefer to create a separate Injectable service

import { Injectable } from '@angular/core';
@Injectable()
export class LocalStorageService {

    constructor() {
        //
    }

    public setData(key:string, data:any) {
        localStorage.setItem(key, JSON.stringify(data));
    }
    public getData(key:string) {
        return JSON.parse(localStorage.getItem(key));
    }

    public removeData(key:string) {
        localStorage.removeItem(key);
    }
}

And in your component

import { LocalStorageService } from './../../services/localStorageService';
@Component({
    selector: 'member-claims-modal',
    templateUrl: './view.html'
})

export class UserComponent {
constructor(private localStorageService:LocalStorageService) {
        super();
    }
    public SampleMethod() {
    let cloneData = {
            'claims': 'hello'
        };
    this.localStorageService.setData('claims', cloneData);
    let item=this.localStorageService.getData('claims');
    consoloe.log(item);
    this.localStorageService.removeData('claims');
    }
}


问:
Problems with connecting cassandra to elasticsearch node
I just start using Elassandra, as it accomplishes the requirements for my project. I am following the documentation and trying to indexing
 the database as it shows:

http://elassandra.readthedocs.io/en/latest/operations.html#indexing

The problem is that the host ID name is different than the master_node

I have to change the configuration of cassandra.yaml to make sure that the cluster name is the same cluster_name: 'elasticsearch'

答:
The problem that I had it was a non capital letter in the datacenter naming of a command proposed for the tutorial.

cqlsh>CREATE KEYSPACE IF NOT EXISTS twitter WITH replication={ 'class':'NetworkTopologyStrategy', 'dc1':'1' };

```<code>Datacenter: DC1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns    Host ID                               Rack
UN  127.0.0.1  416.17 KiB  256          ?       6a41ebba-c2da-43df-80fa-996accb4546a  rack1
</code>```

so the problem was solved changing 'dc1':'1' for 'DC1':'1'

ContentLicense: CC BY-SA 4.0

Body:
The problem that I had it was a non capital letter in the datacenter naming of a command proposed for the tutorial.

cqlsh>CREATE KEYSPACE IF NOT EXISTS twitter WITH replication={ 'class':'NetworkTopologyStrategy', 'dc1':'1' };

Datacenter: DC1
=======================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address    Load       Tokens       Owns    Host ID                               Rack
UN  127.0.0.1  416.17 KiB  256          ?       6a41ebba-c2da-43df-80fa-996accb4546a  rack1

so the problem was solved changing 'dc1':'1' for 'DC1':'1'


答:
var date = new Date();
console.log(date.toLocaleDateString());
console.log(date.toDateString());
console.log(date.toGMTString());```

Choose your method from here:
https://www.w3schools.com/js/js_date_methods.asp

Title: Javascript Date.now to readable format

Body:
var date = new Date();
console.log(date.toLocaleDateString());
console.log(date.toDateString());
console.log(date.toGMTString());

Choose your method from here:
https://www.w3schools.com/js/js_date_methods.asp


问:
Why are Xcode breakpoints expanded automatically?
I'm facing with a Xcode problem.
I have some breakpoints, and when I run my project, all the breakpoints are automatically expanded.

See this pic:

How can I tell Xcode to NOT expand them ?

答:
Looks like you have selected "Show only enabled breakpoint" button under breakpoint. Unselect the button to collapse the breakpoint.

See the image below.


问:
"Unable to read data from the transport connection: net_io_connectionclosed." - Windows Vista Business and SMTP
Unable to test sending email from .NET code in Windows Vista Business.

I am writing code which I will migrate to an SSIS Package once it its proven. The code is to send an error message via email to a list of recipients.

The code is below, however I am getting an exception when I execute the code.

I created a simple class to do the mailing... the design could be better, I am testing functionality before implementing more robust functionality, methods, etc.

```<code>namespace LabDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            Mailer m = new Mailer();
            m.test();
        }
    }
}

namespace LabDemos
{
    class MyMailer
    {
        List<string> _to = new List<string>();
        List<string> _cc = new List<string>();
        List<string> _bcc = new List<string>();
        String _msgFrom = "";
        String _msgSubject = "";
        String _msgBody = "";

        public void test(){
        //create the mail message
        MailMessage mail = new MailMessage();

        //set the addresses
        mail.From = new MailAddress("me@domain.com");

        //set the content
        mail.Subject = "This is an email";
        mail.Body = "this is a sample body";
        mail.IsBodyHtml = false;

        //send the message
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "emailservername";
        smtp.Port = 25;
        smtp.UseDefaultCredentials = true;
        smtp.Send(mail);
    }
}
</code>```

Exception Message

```<code>Inner Exception
{"Unable to read data from the transport connection: net_io_connectionclosed."}

Stack Trace
"   at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)\r\n   at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)\r\n   at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)\r\n   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)\r\n   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)\r\n   at System.Net.Mail.SmtpClient.GetConnection()\r\n   at System.Net.Mail.SmtpClient.Send(MailMessage message)"

Outer Exception
  System.Net.Mail.SmtpException was unhandled
  Message="Failure sending mail."
  Source="System"
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at LabDemos.Mailer.test() in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Mailer.cs:line 40
       at LabDemos.Program.Main(String[] args) in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Program.cs:line 48
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.IOException
       Message="Unable to read data from the transport connection: net_io_connectionclosed."
       Source="System"
       StackTrace:
            at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
            at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
            at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
            at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
            at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException:
</code>```

答:
Is your code incompleted.Dash is correct in identifying it.Other then that check smtp component is installed or not
check link text</p>

ContentLicense: CC BY-SA 2.5

Body:
Unable to test sending email from .NET code in Windows Vista Business.

I am writing code which I will migrate to an SSIS Package once it its proven. The code is to send an error message via email to a list of recipients.

The code is below, however I am getting an exception when I execute the code.

I created a simple class to do the mailing... the design could be better, I am testing functionality before implementing more robust functionality, methods, etc.

namespace LabDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            Mailer m = new Mailer();
            m.test();
        }
    }
}

namespace LabDemos
{
    class MyMailer
    {
        List<string> _to = new List<string>();
        List<string> _cc = new List<string>();
        List<string> _bcc = new List<string>();
        String _msgFrom = "";
        String _msgSubject = "";
        String _msgBody = "";

        public void test(){
        //create the mail message
        MailMessage mail = new MailMessage();

        //set the addresses
        mail.From = new MailAddress("me@domain.com");

        //set the content
        mail.Subject = "This is an email";
        mail.Body = "this is a sample body";
        mail.IsBodyHtml = false;

        //send the message
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "emailservername";
        smtp.Port = 25;
        smtp.UseDefaultCredentials = true;
        smtp.Send(mail);
    }
}

Exception Message

Inner Exception
{"Unable to read data from the transport connection: net_io_connectionclosed."}

Stack Trace
"   at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)\r\n   at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)\r\n   at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)\r\n   at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)\r\n   at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)\r\n   at System.Net.Mail.SmtpClient.GetConnection()\r\n   at System.Net.Mail.SmtpClient.Send(MailMessage message)"

Outer Exception
  System.Net.Mail.SmtpException was unhandled
  Message="Failure sending mail."
  Source="System"
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at LabDemos.Mailer.test() in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Mailer.cs:line 40
       at LabDemos.Program.Main(String[] args) in C:\Users\username\Documents\Visual Studio 2008\Projects\LabDemos\LabDemos\Program.cs:line 48
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.IO.IOException
       Message="Unable to read data from the transport connection: net_io_connectionclosed."
       Source="System"
       StackTrace:
            at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
            at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
            at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
            at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
            at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
            at System.Net.Mail.SmtpClient.GetConnection()
            at System.Net.Mail.SmtpClient.Send(MailMessage message)
       InnerException:


问:
Use Git in SSH to pull specific directories
Total newbie question but what is the best practice when it comes to using SSH with Git? I'm working on a WordPress project. In the root I have gulp and other dev files/folders like SASS and Scripts that I don't need on the server and in the same project I have my WordPress folder that contains a theme and a few custom plugins. As you can imagine when the theme or any of the plugins are ready to be deployed I don't want to pull everything in my repository on the server. So far as a newbie I've always just pull and pushed the entire repository and used FTP to upload what I need to the server, so how is this done with SSH and Git and is there a better way to have my setup?

EDIT: To make my question a little bit more clear let me give you an example of what I think my issue is. In my main project folder, I have a SASS folder next to my WordPress folder. All I really need to deploy to the server is the WordPress folder. My build process that happens on my dev machine combines all of the SASS files into a single CSS that is then placed into the WordPress folder. I need the SASS folder to be tracked by Git so that any other developer can pull them and continue developing so I can't have git ignore it. However none of those SASS files need to be on the server for WordPress to work either. I just simply need to deploy the WordPress folder and everything that's in it.

I understand the idea of creating a bare repository on the server and using post-receive hook to point the git folder sitting outside your web root to point to where the web root is. But that's basically how GIT and SSH work and that's not answering my concern.

答:
Not with Git

Git is not designed to pull specific files or directories only.  It's a directed acyclic graph with binary blobs as objects and sometimes multiple objects get compacted into a single larger object.

Due to Git design, your specific request is not possible.

Alternatives

post-receive hook

If your website only contains simple static files then it's okay to push to a git repository over SSH.  In reality, it's unlikely your repository will be large as long as you don't have non-text files.

Take for example the following setup.

/var/lib/www - apache web dir which is the cloned copy of www.git

/var/lib/www.git - a bare git repository.

/var/lib/www.git/hooks/post-recieve - A server side git hook.  It can be a shell script that pulls the www repository when this repository is updated.

Sample post-recieve hook script:

```<code>#!/bin/bash
cd /home/sam/sandbox/git-hooks/www
unset GIT_DIR
git fetch origin master
git reset --hard origin/master
</code>```

Zip up build in a tar.gz

At the end of your build you can zip up your files in a tar.gz.  This file should be hosted somewhere (perhaps GitHub releases if you're using GitHub).  Some enterprises use on premise artifact hosting like Nexus or Artifactory.

The idea being: you have a tested artifact that has a specific sha256sum.  The artifact you test is the exact same artifact which eventually goes to production.

Diving into more detail such as continuous integration, continuous delivery, and the software development life cycle might be out of scope for your question.

Body:
Not with Git

Git is not designed to pull specific files or directories only.  It's a directed acyclic graph with binary blobs as objects and sometimes multiple objects get compacted into a single larger object.

Due to Git design, your specific request is not possible.

Alternatives

post-receive hook

If your website only contains simple static files then it's okay to push to a git repository over SSH.  In reality, it's unlikely your repository will be large as long as you don't have non-text files.

Take for example the following setup.

/var/lib/www - apache web dir which is the cloned copy of www.git

/var/lib/www.git - a bare git repository.

/var/lib/www.git/hooks/post-recieve - A server side git hook.  It can be a shell script that pulls the www repository when this repository is updated.

Sample post-recieve hook script:

#!/bin/bash
cd /home/sam/sandbox/git-hooks/www
unset GIT_DIR
git fetch origin master
git reset --hard origin/master

Zip up build in a tar.gz

At the end of your build you can zip up your files in a tar.gz.  This file should be hosted somewhere (perhaps GitHub releases if you're using GitHub).  Some enterprises use on premise artifact hosting like Nexus or Artifactory.

The idea being: you have a tested artifact that has a specific sha256sum.  The artifact you test is the exact same artifact which eventually goes to production.

Diving into more detail such as continuous integration, continuous delivery, and the software development life cycle might be out of scope for your question.


问:
Vertical total by group Pivot SQL
I have a Pivot query which counts employees by group per month on how many times they have logged in, I want to get a grand total per group, per month shown horizontally under the list of employees in the group.

Currently I can only get the totals to show as the overall total per group as an extra column

The SQL I am using is:

```<code>   SELECT
   Code,
   Full_Name,
   [1] AS Jan,
   [2] AS Feb,
   [3] AS Mar,
   [4] AS Apr,
   [5] AS May,
   [6] AS Jun,
   [7] AS Jul,
   [8] AS Aug,
   [9] AS Sep,
   [10] AS Oct,
   [11] AS Nov,
   [12] AS Dec,
   Total
   FROM
   (SELECT Norgren_Group.Code
   , Full_Name
   , lh.Employee_Id
   , MONTH(lh.RN_Create_Date) [Month]
   , COUNT(lh.Employee_Id) OVER (PARTITION BY Norgren_Group_Id) as Total
   FROM Employee_Login_History lh
   JOIN Employee ON Employee.Employee_Id = lh.Employee_Id
   JOIN Norgren_Group ON Norgren_Group.Norgren_Group_Id = Employee.Default_Norgren_Group_Id
   WHERE Reporting_Region='Europe'
   AND YEAR(lh.RN_Create_Date) = YEAR(GETDATE())
   ) pvt
   PIVOT
   (
      COUNT(Employee_Id)
      FOR [Month]
      IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
   ) AS pvttble
   ORDER BY Code, Full_Name
</code>```

A snippet of the result i get is:

```<code> Code   Full_Name            Jan    Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
   A    Alexander Wipplinger 20     11  23  7   14  10  15  10  13  23  6   0   2894
   A    Andreas Grünanger    13     12  12  10  17  14  11  15  13  20  11  0   2894
   ALPE Albert Unger         16     18  28  9   13  17  18  19  17  22  18  0   16899
   ALPE Andreas Barz         1      0   0   0   0   0   0   0   0   0   0   0   16899
</code>```

What I want to see is:

```<code> Code   Full_Name            Jan    Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
   A    Alexander Wipplinger 20     11  23  7   14  10  15  10  13  23  6   0
   A    Andreas Grünanger    13     12  12  10  17  14  11  15  13  20  11  0
        Total                33     23  35  17  31  24  26  25  26  43  17  0
   ALPE Albert Unger         16     18  28  9   13  17  18  19  17  22  18  0
   ALPE Andreas Barz         1      0   0   0   0   0   0   0   0   0   0   0
        Total                17     18  28  9   13  17  18  19  17  22  18  0
</code>```

答:
One method is to switch to conditional aggregation and use GROUPING SETS:

```<code>SELECT ng.Code, Full_Name,
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 1 THEN 1 ELSE 0 END) as Jan,
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 2 THEN 1 ELSE 0 END) as Feb,
       . . .
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 12 THEN 1 ELSE 0 END) as Dec
FROM Employee_Login_History lh JOIN
     Employee e
     ON e.Employee_Id = lh.Employee_Id JOIN
     Norgren_Group ng
     ON ng.Norgren_Group_Id = e.Default_Norgren_Group_Id
WHERE Reporting_Region = 'Europe'AND
      YEAR(lh.RN_Create_Date) = YEAR(GETDATE())
GROUP BY GROUPING SETS ( (ng.Code, Full_Name), () );
</code>```

Title: Vertical total by group Pivot SQL

Body:
I have a Pivot query which counts employees by group per month on how many times they have logged in, I want to get a grand total per group, per month shown horizontally under the list of employees in the group.

Currently I can only get the totals to show as the overall total per group as an extra column

The SQL I am using is:

   SELECT
   Code,
   Full_Name,
   [1] AS Jan,
   [2] AS Feb,
   [3] AS Mar,
   [4] AS Apr,
   [5] AS May,
   [6] AS Jun,
   [7] AS Jul,
   [8] AS Aug,
   [9] AS Sep,
   [10] AS Oct,
   [11] AS Nov,
   [12] AS Dec,
   Total
   FROM
   (SELECT Norgren_Group.Code
   , Full_Name
   , lh.Employee_Id
   , MONTH(lh.RN_Create_Date) [Month]
   , COUNT(lh.Employee_Id) OVER (PARTITION BY Norgren_Group_Id) as Total
   FROM Employee_Login_History lh
   JOIN Employee ON Employee.Employee_Id = lh.Employee_Id
   JOIN Norgren_Group ON Norgren_Group.Norgren_Group_Id = Employee.Default_Norgren_Group_Id
   WHERE Reporting_Region='Europe'
   AND YEAR(lh.RN_Create_Date) = YEAR(GETDATE())
   ) pvt
   PIVOT
   (
      COUNT(Employee_Id)
      FOR [Month]
      IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12])
   ) AS pvttble
   ORDER BY Code, Full_Name

A snippet of the result i get is:

 Code   Full_Name            Jan    Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Total
   A    Alexander Wipplinger 20     11  23  7   14  10  15  10  13  23  6   0   2894
   A    Andreas Grünanger    13     12  12  10  17  14  11  15  13  20  11  0   2894
   ALPE Albert Unger         16     18  28  9   13  17  18  19  17  22  18  0   16899
   ALPE Andreas Barz         1      0   0   0   0   0   0   0   0   0   0   0   16899

What I want to see is:

 Code   Full_Name            Jan    Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
   A    Alexander Wipplinger 20     11  23  7   14  10  15  10  13  23  6   0
   A    Andreas Grünanger    13     12  12  10  17  14  11  15  13  20  11  0
        Total                33     23  35  17  31  24  26  25  26  43  17  0
   ALPE Albert Unger         16     18  28  9   13  17  18  19  17  22  18  0
   ALPE Andreas Barz         1      0   0   0   0   0   0   0   0   0   0   0
        Total                17     18  28  9   13  17  18  19  17  22  18  0

Body:
One method is to switch to conditional aggregation and use GROUPING SETS:

SELECT ng.Code, Full_Name,
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 1 THEN 1 ELSE 0 END) as Jan,
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 2 THEN 1 ELSE 0 END) as Feb,
       . . .
       SUM(CASE WHEN MONTH(lh.RN_Create_Date) = 12 THEN 1 ELSE 0 END) as Dec
FROM Employee_Login_History lh JOIN
     Employee e
     ON e.Employee_Id = lh.Employee_Id JOIN
     Norgren_Group ng
     ON ng.Norgren_Group_Id = e.Default_Norgren_Group_Id
WHERE Reporting_Region = 'Europe'AND
      YEAR(lh.RN_Create_Date) = YEAR(GETDATE())
GROUP BY GROUPING SETS ( (ng.Code, Full_Name), () );


答:
You could do these following statements</p>
```<code>let newDate = new Date();
console.log(`${newDate.toDateString()} ${newDate.toTimeString()}`);
</code>```

Title: Javascript Date.now to readable format

Body:
You could do these following statements

let newDate = new Date();
console.log(`${newDate.toDateString()} ${newDate.toTimeString()}`);


问:
dropdown Arrow unicode icon static position css small devices
I'm trying to implement an accordion for FAQ. I have problems with the arrow icons in small screens, so each time I press the down arrow it should be switched for the up arrow icon and also located on the same place. But once I click the down arrow the up arrow appears slightly more on the top (on smartphone view). I tried with margin but not success. I would like to know how to keep both icons at the same place each time I switch from one to the other by clicking on it.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.accordion {

  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  font-size: 18px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

button.accordion.active, button.accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease-out;
}

button.accordion:after {

  font-family: 'Arial Unicode MS', 'Consolas';
  content: "\2304";

  font-size: 60px !important;
  color: #777;
  float: left;
  margin-left: 5px;
  margin-top: -3vh ;
}

button.accordion.active:after {
  content: "\2303";
  max-height: 1vh;

}</code>```

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

```

答:
 var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
        acc[i].onclick = function(){
            /* Toggle between adding and removing the "active" class,
            to highlight the button that controls the panel */
            this.classList.toggle("active");

            /* Toggle between hiding and showing the active panel */
            var panel = this.nextElementSibling;
            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.accordion {

        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        text-align: center;
        border: none;
        outline: none;
        transition: 0.4s;
        font-size: 18px;
        position: relative;
    }
    .panel p{
      margin: 0;
      padding:10px;
    }

    /* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

    button.accordion.active, button.accordion:hover {
        background-color: #ccc;
    }

    /* Style the accordion panel. Note: hidden by default */

    div.panel {
        padding: 0 18px;
        background-color: white;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.4s ease-out;
    }

    button.accordion:after {

        font-family: 'Arial Unicode MS', 'Consolas';
        content: "\2304";

        font-size: 60px !important;
        color: #777;
        position: absolute;
        left: 3%;
        top: -30%;
    }

    button.accordion.active:after {
        content: "\2303";
        max-height: 1vh;

    }</code>```

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

```

Body:
I'm trying to implement an accordion for FAQ. I have problems with the arrow icons in small screens, so each time I press the down arrow it should be switched for the up arrow icon and also located on the same place. But once I click the down arrow the up arrow appears slightly more on the top (on smartphone view). I tried with margin but not success. I would like to know how to keep both icons at the same place each time I switch from one to the other by clicking on it.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        /* Toggle between adding and removing the "active" class,
        to highlight the button that controls the panel */
        this.classList.toggle("active");

        /* Toggle between hiding and showing the active panel */
        var panel = this.nextElementSibling;
        if (panel.style.maxHeight) {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    }
}

button.accordion {

  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: center;
  border: none;
  outline: none;
  transition: 0.4s;
  font-size: 18px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

button.accordion.active, button.accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */

div.panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.4s ease-out;
}

button.accordion:after {

  font-family: 'Arial Unicode MS', 'Consolas';
  content: "\2304";

  font-size: 60px !important;
  color: #777;
  float: left;
  margin-left: 5px;
  margin-top: -3vh ;
}

button.accordion.active:after {
  content: "\2303";
  max-height: 1vh;

}

    <button type="button" class="accordion">First Question</button>

Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto.

    <button type="button" class="accordion">Second Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Third Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fourth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Fifth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

    <button type="button" class="accordion">Sixth Question</button>

This is the answer to question #1. Pellentesque habitant morbi....

Body:
 var acc = document.getElementsByClassName("accordion");
    var i;

    for (i = 0; i < acc.length; i++) {
        acc[i].onclick = function(){
            /* Toggle between adding and removing the "active" class,
            to highlight the button that controls the panel */
            this.classList.toggle("active");

            /* Toggle between hiding and showing the active panel */
            var panel = this.nextElementSibling;
            if (panel.style.maxHeight) {
                panel.style.maxHeight = null;
            } else {
                panel.style.maxHeight = panel.scrollHeight + "px";
            }
        }
    }

button.accordion {

        background-color: #eee;
        color: #444;
        cursor: pointer;
        padding: 18px;
        width: 100%;
        text-align: center;
        border: none;
        outline: none;
        transition: 0.4s;
        font-size: 18px;
        position: relative;
    }
    .panel p{
      margin: 0;
      padding:10px;
    }

    /* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */

    button.accordion.active, button.accordion:hover {
        background-color: #ccc;
    }

    /* Style the accordion panel. Note: hidden by default */

    div.panel {
        padding: 0 18px;
        background-color: white;
        max-height: 0;
        overflow: hidden;
        transition: max-height 0.4s ease-out;
    }

    button.accordion:after {

        font-family: 'Arial Unicode MS', 'Consolas';
        content: "\2304";

        font-size: 60px !important;
        color: #777;
        position: absolute;
        left: 3%;
        top: -30%;
    }

    button.accordion.active:after {
        content: "\2303";
        max-height: 1vh;

    }

<div class="container">
    <button type="button" class="accordion">First Question</button>
    <div class="panel">
        <p>Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. </p>
    </div>

    <button type="button" class="accordion">Second Question</button>
    <div class="panel">
        <p>This is the answer to question #1. Pellentesque habitant morbi....</p>
    </div>

    <button type="button" class="accordion">Third Question</button>
    <div class="panel">
        <p>This is the answer to question #1. Pellentesque habitant morbi....</p>
    </div>

    <button type="button" class="accordion">Fourth Question</button>
    <div class="panel">
        <p>This is the answer to question #1. Pellentesque habitant morbi....</p>
    </div>

    <button type="button" class="accordion">Fifth Question</button>
    <div class="panel">
        <p>This is the answer to question #1. Pellentesque habitant morbi....</p>
    </div>

    <button type="button" class="accordion">Sixth Question</button>
    <div class="panel">
        <p>This is the answer to question #1. Pellentesque habitant morbi....</p>
    </div>
</div>


问:
Keepiing only 3 FY tables in the database at a time, rest all tables needs to Drop
I want to keep only 3 financial year tables in my database rest I need to drop the table

Means I have a table something like

```<code>KT201705, KT201502 , KT201412 , KT201605 , KT201709 , KT201506
</code>```

Current financial year is    2017-2018
Last Financial year          2016-2017
Last to Last financial year  2015-2016

I want to Keep tables like

```<code>KT201705,
KT201605,
KT201709,
KT201506
</code>```

I want to drop all the tables created in financial year before that which means tables like

```<code>KT201412,
KT201502
</code>```

What I tried:

```<code>select 'DROP TABLE ' + NAME from sys.tables
WHERE NAME LIKE 'KT2%'
</code>```

But I cannot figured out the financial year part.

I also checked this query:

```<code>SELECT CASE WHEN DatePart(Month, convert(varchar(10),GETDATE(),112)) >= 4
        THEN DatePart(Year, convert(varchar(10),GETDATE(),112)) + 1
        ELSE DatePart(Year,convert(varchar(10),GETDATE(),112))
   END AS Fiscal_Year
</code>```

But it is giving only the current financial year.

Can anyone have any idea how to proceed further??

答:
Will this work

```<code>;WITH cteNum
AS(
    SELECT N = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
    FROM master.dbo.spt_values V
)
SELECT 'DROP TABLE ' + NAME
FROM sys.tables
CROSS APPLY cteNum N
WHERE NAME LIKE 'KT'+ CONVERT(NVARCHAR(4),DATEADD(YEAR, -N.N, GETDATE()), 102) + '%'
AND N.N >= 2 AND  N.N <=10
</code>```

The same query slightly amended returns this list of dates

```<code>;WITH cteNum
AS(
    SELECT N = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
    FROM master.dbo.spt_values V
)
SELECT yyyyDate = CONVERT(NVARCHAR(4),DATEADD(YEAR, -N.N, GETDATE()), 102)
FROM cteNum N
WHERE N.N >= 2 AND  N.N <=10
</code>```

Body:
I want to keep only 3 financial year tables in my database rest I need to drop the table

Means I have a table something like

KT201705, KT201502 , KT201412 , KT201605 , KT201709 , KT201506

Current financial year is    2017-2018
Last Financial year          2016-2017
Last to Last financial year  2015-2016

I want to Keep tables like

KT201705,
KT201605,
KT201709,
KT201506

I want to drop all the tables created in financial year before that which means tables like

KT201412,
KT201502

What I tried:

select 'DROP TABLE ' + NAME from sys.tables
WHERE NAME LIKE 'KT2%'

But I cannot figured out the financial year part.

I also checked this query:

SELECT CASE WHEN DatePart(Month, convert(varchar(10),GETDATE(),112)) >= 4
        THEN DatePart(Year, convert(varchar(10),GETDATE(),112)) + 1
        ELSE DatePart(Year,convert(varchar(10),GETDATE(),112))
   END AS Fiscal_Year

But it is giving only the current financial year.

Can anyone have any idea how to proceed further??

Body:
Will this work

;WITH cteNum
AS(
    SELECT N = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
    FROM master.dbo.spt_values V
)
SELECT 'DROP TABLE ' + NAME
FROM sys.tables
CROSS APPLY cteNum N
WHERE NAME LIKE 'KT'+ CONVERT(NVARCHAR(4),DATEADD(YEAR, -N.N, GETDATE()), 102) + '%'
AND N.N >= 2 AND  N.N <=10

The same query slightly amended returns this list of dates

;WITH cteNum
AS(
    SELECT N = ROW_NUMBER()OVER(ORDER BY (SELECT NULL))
    FROM master.dbo.spt_values V
)
SELECT yyyyDate = CONVERT(NVARCHAR(4),DATEADD(YEAR, -N.N, GETDATE()), 102)
FROM cteNum N
WHERE N.N >= 2 AND  N.N <=10


问:
why value types are declared (instantiated) without 'new' keyword in (vb or C#).net
why  value  types are declared (instantiated) without 'new' keyword in (vb or C#).net</p>

答:
Value types are not necessarily constructed without the use of the new keyword, but there's support in the language for primitive types, like integers, strings, etc.

In other words you typically write this:

```<code>int i = 10;
string s = "test";
</code>```

However, if you define your own value types, to declare variables with initial values, you need to use new:

```<code>Point p = new Point(10, 20);
</code>```

I think you need to clarify what you're asking.

Body:
Value types are not necessarily constructed without the use of the new keyword, but there's support in the language for primitive types, like integers, strings, etc.

In other words you typically write this:

int i = 10;
string s = "test";

However, if you define your own value types, to declare variables with initial values, you need to use new:

Point p = new Point(10, 20);

I think you need to clarify what you're asking.


问:
PHP get the current month of a date
Hello everybody I would like to get the current month of a date.

This is what I tried:

```<code><?php

   $transdate = date('m-d-Y', time());

   echo $transdate;

   $month = date('m', strtotime($transdate));

   if ($month == "12") {
       echo "<br />December is the month :)";
   } else {
       echo "<br /> The month is probably not December";
   }

?>
</code>```

But the result is wrong, it should display December is the month :0

Any ideas? thanks.

答:
Why not simply </p>

```<code>echo date('F, Y');
</code>```

<p>? This prints November, 2017.</p>

Title: PHP get the current month of a date

Body:
Hello everybody I would like to get the current month of a date.

This is what I tried:

<?php

   $transdate = date('m-d-Y', time());

   echo $transdate;

   $month = date('m', strtotime($transdate));

   if ($month == "12") {
       echo "
December is the month :)";
   } else {
       echo "
 The month is probably not December";
   }

?>

But the result is wrong, it should display December is the month :0

Any ideas? thanks.

Body:
Why not simply

echo date('F, Y');

? This prints November, 2017.


问:
Why both Jenkins and GitLab are not opening in browser when they are in the same server?
On my Linux server, Jenkins was already installed, and I tried to install GitLab on same server, with following commands:

```<code>sudo yum install -y curl policycoreutils-python openssh-server cronie
sudo lokkit -s http -s ssh
curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh | sudo bash
sudo EXTERNAL_URL="http://gitlab.fabcd.com" yum -y install gitlab-ee
</code>```

It says that GitLab is now installed, but when i open the URL in browser, its not opening and also my Jenkins URL isn't working.

Please help me rollback this GitLab installation as I don't want to mess with my Jenkins.

答:
Both servers exposed in port 8080.

You should change one of it to be different port.

To set the GitLab port, edit the file /etc/gitlab/gitlab.rb

```<code>external_port "8888"
</code>```

Then run reconfigure:

```<code>gitlab-ctl reconfigure
</code>```

Body:
On my Linux server, Jenkins was already installed, and I tried to install GitLab on same server, with following commands:

sudo yum install -y curl policycoreutils-python openssh-server cronie
sudo lokkit -s http -s ssh
curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ee/script.rpm.sh | sudo bash
sudo EXTERNAL_URL="http://gitlab.fabcd.com" yum -y install gitlab-ee

It says that GitLab is now installed, but when i open the URL in browser, its not opening and also my Jenkins URL isn't working.

Please help me rollback this GitLab installation as I don't want to mess with my Jenkins.

Body:
Both servers exposed in port 8080.

You should change one of it to be different port.

To set the GitLab port, edit the file /etc/gitlab/gitlab.rb

external_port "8888"

Then run reconfigure:

gitlab-ctl reconfigure


问:
.Net Core Angular 4 - Duplicate app component on bundle rebuilding
My project is using the Visual Studio .Net-Core AngularJS Template (i.e with the app.module.shared.ts,app.module.browser.ts,app.module.server.ts files)

I was having a strange issue whereby whenever I made changes a new <app> element was being added to my DOM, and the old <app> element wasn't being removed.
If I refreshed the page it all went back to normal.

答:
After much searching it turned out it was due to having this in my app.module.browser.ts file

```<code>imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppModuleShared
],
</code>```

Once I remove the BrowserAnimationsModule line, the duplication issue stopped.

So the imports section becomes:

```<code>imports: [
    BrowserModule,
    AppModuleShared
],
</code>```

I have no idea if this is a webpack issue, an angular issue, or an issue with the MS way of having app.module split into multiple files... But that's what is causing it if you run into this issue!

It's easy to duplicate for those interested, just start a new template project and add that line.

Update: Adding BrowserAnimationsModule import to the app.module.shared.ts file also had the same issue, as does NoopAnimationsModule

Update 2:
I just found this GIT issue with a proper workaround to remove the old <app>
https://github.com/aspnet/JavaScriptServices/issues/1165

Body:
After much searching it turned out it was due to having this in my app.module.browser.ts file

imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AppModuleShared
],

Once I remove the BrowserAnimationsModule line, the duplication issue stopped.

So the imports section becomes:

imports: [
    BrowserModule,
    AppModuleShared
],

I have no idea if this is a webpack issue, an angular issue, or an issue with the MS way of having app.module split into multiple files... But that's what is causing it if you run into this issue!

It's easy to duplicate for those interested, just start a new template project and add that line.

Update: Adding BrowserAnimationsModule import to the app.module.shared.ts file also had the same issue, as does NoopAnimationsModule

Update 2:
I just found this GIT issue with a proper workaround to remove the old <app>
https://github.com/aspnet/JavaScriptServices/issues/1165


问:
How to use guzzle in Laravel Project
I'm planning to use Guzzle to communicate with my XML web service.
I am able to communicate with my XML web service using core PHP 5.6. I want to do this within my Laravel App using Guzzle to communicate with XML web service.

My xml config code is as follows:

```<code>        $requestXmlBody  ='';
        $requestXmlBody  = '<?xml version="1.0" encoding="UTF-8"?>';
        $requestXmlBody = $requestXmlBody.'<FAB_PkgAvailRQ Target="test" Version="2002A" xmlns="https://localhost.com/find">';
        $requestXmlBody = $requestXmlBody.'<SyndicatorInfo SyndicatorId="******" SyndicatorPassword="*****"/>';
        $requestXmlBody = $requestXmlBody.'<SessionInfo CreateNewSession="true"/>';
        $requestXmlBody = $requestXmlBody.'<HolidaySearchRequest ResponseTimeoutSecs="60" ExcludeNonBookableSuppliers="true">';
        $requestXmlBody = $requestXmlBody.'<SearchCriteria FlightOnly="true" OneWayOnly="'.$journey_type.'" NumberOfAdults="'.$adults.'" NumberOfChildren="'.$children.'" NumberOfInfants="'.$infants.'">';

        $requestXmlBody = $requestXmlBody.'<DepartureDateRange StartDate="'.$from.'" EndDate="'.$from.'"/>';
        $requestXmlBody = $requestXmlBody.'<DepartureAirports><Airport>'.$origin.'</Airport></DepartureAirports>';
        $requestXmlBody = $requestXmlBody.'<DestinationChoice><DestinationAirports><Airport>'.$destination.'</Airport></DestinationAirports></DestinationChoice>';
        $requestXmlBody = $requestXmlBody.'<FlightPreferences/>';

        $requestXmlBody = $requestXmlBody.'<HolidayDuration MinNumberOfNights="'.$ddays.'" MaxNumberOfNights="'.$ddays.'"/>';
        $requestXmlBody = $requestXmlBody.'</SearchCriteria>';
        // $requestXmlBody = $requestXmlBody.'<ResultSetPreferences MaxItems="'.$numberofsearch.'" SortCode="cost" SortAscending="true"/>';
        // $requestXmlBody = $requestXmlBody.'<InitialViewInfo Length="'.$numberofsearch.'" Offset="0"/>';
        $requestXmlBody = $requestXmlBody.'</HolidaySearchRequest>';
        $requestXmlBody = $requestXmlBody.'</FAB_PkgAvailRQ>';

       My curl code is as follows

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"http://localhost.com/23");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXmlBody);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);

        $result = curl_exec($ch);

        curl_close($ch);
        $result1 = simplexml_load_string($result);
        dd($result1);
</code>```

I want to send a POST request using Guzzle to above xml configuration to my xml web service such as paxport/multicom.
Any Idea How I can proceed?

答:
It's simple.</p>

```<code>use GuzzleHttp\Client;

$client = new Client();
$response = $client->post('http://localhost.com/23', ['body' => $requestXmlBody]);

$result = $response->getBody()->getContents();

$result1 = simplexml_load_string($result);
</code>```

Title: How to use guzzle in Laravel Project

Body:
I'm planning to use Guzzle to communicate with my XML web service.
I am able to communicate with my XML web service using core PHP 5.6. I want to do this within my Laravel App using Guzzle to communicate with XML web service.

My xml config code is as follows:

        $requestXmlBody  ='';
        $requestXmlBody  = '<?xml version="1.0" encoding="UTF-8"?>';
        $requestXmlBody = $requestXmlBody.'<FAB_PkgAvailRQ Target="test" Version="2002A" xmlns="https://localhost.com/find">';
        $requestXmlBody = $requestXmlBody.'<SyndicatorInfo SyndicatorId="******" SyndicatorPassword="*****"/>';
        $requestXmlBody = $requestXmlBody.'<SessionInfo CreateNewSession="true"/>';
        $requestXmlBody = $requestXmlBody.'<HolidaySearchRequest ResponseTimeoutSecs="60" ExcludeNonBookableSuppliers="true">';
        $requestXmlBody = $requestXmlBody.'<SearchCriteria FlightOnly="true" OneWayOnly="'.$journey_type.'" NumberOfAdults="'.$adults.'" NumberOfChildren="'.$children.'" NumberOfInfants="'.$infants.'">';

        $requestXmlBody = $requestXmlBody.'<DepartureDateRange StartDate="'.$from.'" EndDate="'.$from.'"/>';
        $requestXmlBody = $requestXmlBody.'<DepartureAirports><Airport>'.$origin.'</Airport></DepartureAirports>';
        $requestXmlBody = $requestXmlBody.'<DestinationChoice><DestinationAirports><Airport>'.$destination.'</Airport></DestinationAirports></DestinationChoice>';
        $requestXmlBody = $requestXmlBody.'<FlightPreferences/>';

        $requestXmlBody = $requestXmlBody.'<HolidayDuration MinNumberOfNights="'.$ddays.'" MaxNumberOfNights="'.$ddays.'"/>';
        $requestXmlBody = $requestXmlBody.'</SearchCriteria>';
        // $requestXmlBody = $requestXmlBody.'<ResultSetPreferences MaxItems="'.$numberofsearch.'" SortCode="cost" SortAscending="true"/>';
        // $requestXmlBody = $requestXmlBody.'<InitialViewInfo Length="'.$numberofsearch.'" Offset="0"/>';
        $requestXmlBody = $requestXmlBody.'</HolidaySearchRequest>';
        $requestXmlBody = $requestXmlBody.'</FAB_PkgAvailRQ>';

       My curl code is as follows

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"http://localhost.com/23");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXmlBody);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);

        $result = curl_exec($ch);

        curl_close($ch);
        $result1 = simplexml_load_string($result);
        dd($result1);

I want to send a POST request using Guzzle to above xml configuration to my xml web service such as paxport/multicom.
Any Idea How I can proceed?

Body:
It's simple.

use GuzzleHttp\Client;

$client = new Client();
$response = $client->post('http://localhost.com/23', ['body' => $requestXmlBody]);

$result = $response->getBody()->getContents();

$result1 = simplexml_load_string($result);


问:
ASP.NET Conditional Markup Rendering According to Web.config Key
I have a key in web.config as -

```<code><add key="IsDemo" value ="true"/>
</code>```

I want to show/hide markup based on above web.config entry for a non-server html tag without using code behind file (as there is no .cs file and there are no runat=server controls).
Something similar to following pseudo code:

```<code>IF ( IsDemo == "true" )
THEN
<tr>
    <td id="tdDemoSection" colspan="2" align="left" valign="top">
        <.....>
    </td>
</tr>
ENDIF
</code>```

Does anyone know that we can write such conditional logic in .aspx markup?
Please help!!!

EDIT:

Section I'm hiding or showing have some data like username and password. So, I do not want user to use Firebug or Web Developer Tools to see hidden markup. markup should not go to client side.

答:
The syntax for something like that would be

```<code><% if(System.Configuration.ConfigurationManager.AppSettings["IsDemo"] == "true") %>
<% { %>
<!-- Protected HTML goes here -->
<% } %>
</code>```

This assumes that the page is in C#.

You can firm this code up by being more defensive around the AppSettings retrieval e.g. what happens in the case where the value is null etc.

Body:
I have a key in web.config as -

<add key="IsDemo" value ="true"/>

I want to show/hide markup based on above web.config entry for a non-server html tag without using code behind file (as there is no .cs file and there are no runat=server controls).
Something similar to following pseudo code:

IF ( IsDemo == "true" )
THEN

        <.....>

ENDIF

Does anyone know that we can write such conditional logic in .aspx markup?
Please help!!!

EDIT:

Section I'm hiding or showing have some data like username and password. So, I do not want user to use Firebug or Web Developer Tools to see hidden markup. markup should not go to client side.

Body:
The syntax for something like that would be

<% if(System.Configuration.ConfigurationManager.AppSettings["IsDemo"] == "true") %>
<% { %>
<!-- Protected HTML goes here -->
<% } %>

This assumes that the page is in C#.

You can firm this code up by being more defensive around the AppSettings retrieval e.g. what happens in the case where the value is null etc.


问:
Threadsafe vs Synchronized
I'm new to java.
I'm little bit confused between Threadsafe and synchronized.
Thread safe means that a method or class instance can be used by multiple threads at the same time without any problems occurring.
Where as Synchronized means only one thread can operate at single time.

So how they are related to each other?

答:
Synchronized: only one thread can operate at same time.
Threadsafe: a method or class instance can be used by multiple threads at the same time without any problems occurring.
If you relate this question as, Why synchronized methods are thread safe? than you can get better idea.

As per the definition this appears to be confusive. But not,if you understand it analytically.

Synchronized means: sequentially one by one in an order,Not concurrently [Not at the same time].
synchronized method not allows to act another thread on it, While a thread is already working on it.This avoids concurrency.
example of synchronization: If you want to buy a movie ticket,and stand in a queue. you will get the ticket only after the person in front of you get the ticket.

Thread safe means: method becomes safe to be accessed by multiple threads without any problem at the same time.synchronized keyword is one of the way to achieve 'thread safe'. But Remember:Actually while multiple threads tries to access synchronized method they follow the order so becomes safe to access. Actually, Even they act at the same time, but cannot access the same  resource(method/block) at the same time, because of synchronized behavior of the resource.

Because If a method becomes synchronized, so this is becomes safe to allow multiple threads to act on it, without any problem. Remember:: multiple threads "not act on it at the same time" hence we call synchronized methods thread safe.

Hope this helps to understand.

Title: Threadsafe vs Synchronized


问:
change field datatype in Cosmos DB
I have a field in Cosmos DB which is mapped as an number, but it should be a string. I'd like to alter the schema in-place without reloading the data, is this possible with a query in the same way it can be achieved in SQL?

```<code>ALTER TABLE EVENTS
MODIFY COLUMN eventAmount varchar;
</code>```

Have consulted the docs but they only reference simple SQL commands.

答:
DocumentDB is schemaless. There is no structure defined outside documents themselves so each document has their own schema. If you want to enforce some documents follow a certain structure, then that must be enforced by yourself in your application logic.

So, this means you can not "alter schema" for collection to change data types.

What you can and should do, is to fix documents which you consider having wrong schema by updating them. Query docs where eventAmount is stored as JS number and save the document with the value stored as a corresponding javascript string instead.

Title: change field datatype in Cosmos DB

Body:
I have a field in Cosmos DB which is mapped as an number, but it should be a string. I'd like to alter the schema in-place without reloading the data, is this possible with a query in the same way it can be achieved in SQL?

ALTER TABLE EVENTS
MODIFY COLUMN eventAmount varchar;

Have consulted the docs but they only reference simple SQL commands.


问:
Why accesing DataFrame from UDF results in NullPointerException?
I have a problem executing a Spark application.

Source code:

```<code>// Read table From HDFS
val productInformation = spark.table("temp.temp_table1")
val dict = spark.table("temp.temp_table2")

// Custom UDF
val countPositiveSimilarity = udf[Long, Seq[String], Seq[String]]((a, b) =>
    dict.filter(
        (($"first".isin(a: _*) && $"second".isin(b: _*)) || ($"first".isin(b: _*) && $"second".isin(a: _*))) && $"similarity" > 0.7
    ).count
)

val result = productInformation.withColumn("positive_count", countPositiveSimilarity($"title", $"internal_category"))

// Error occurs!
result.show
</code>```

Error message:

```<code>org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 54.0 failed 4 times, most recent failure: Lost task 0.3 in stage 54.0 (TID 5887, ip-10-211-220-33.ap-northeast-2.compute.internal, executor 150): org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at $anonfun$1.apply(<console>:45)
    at $anonfun$1.apply(<console>:43)
    ... 16 more

Driver stacktrace:
  at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
  at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
  at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
  at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at scala.Option.foreach(Option.scala:257)
  at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
  at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
  at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
  at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:333)
  at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
  at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2371)
  at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
  at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
  at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2370)
  at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2377)
  at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2113)
  at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2112)
  at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2795)
  at org.apache.spark.sql.Dataset.head(Dataset.scala:2112)
  at org.apache.spark.sql.Dataset.take(Dataset.scala:2327)
  at org.apache.spark.sql.Dataset.showString(Dataset.scala:248)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:636)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:595)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:604)
  ... 48 elided
Caused by: org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)
  at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
  at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
  at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
  at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
  at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
  at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
  at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
  at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
  at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
  at org.apache.spark.scheduler.Task.run(Task.scala:99)
  at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
  ... 3 more
Caused by: java.lang.NullPointerException
  at $anonfun$1.apply(<console>:45)
  at $anonfun$1.apply(<console>:43)
  ... 16 more
</code>```

I have checked whether productInformation and dict have null value in Columns. But there are no null values.

Can anyone help me?
I attached example code to let you know more details:

```<code>case class Target(wordListOne: Seq[String], WordListTwo: Seq[String])
val targetData = Seq(Target(Seq("Spark", "Wrong", "Something"), Seq("Java", "Grape", "Banana")),
                     Target(Seq("Java", "Scala"), Seq("Scala", "Banana")),
                     Target(Seq(""), Seq("Grape", "Banana")),
                     Target(Seq(""), Seq("")))
val targets = spark.createDataset(targetData)

case class WordSimilarity(first: String, second: String, similarity: Double)
val similarityData = Seq(WordSimilarity("Spark", "Java", 0.8),
                     WordSimilarity("Scala", "Spark", 0.9),
                     WordSimilarity("Java", "Scala", 0.9),
                     WordSimilarity("Apple", "Grape", 0.66),
                     WordSimilarity("Scala", "Apple", -0.1),
                     WordSimilarity("Gine", "Spark", 0.1))
val dict = spark.createDataset(similarityData)

val countPositiveSimilarity = udf[Long, Seq[String], Seq[String]]((a, b) =>
    dict.filter(
        (($"first".isin(a: _*) && $"second".isin(b: _*)) || ($"first".isin(b: _*) && $"second".isin(a: _*))) && $"similarity" > 0.7
    ).count
)

val countDF = targets.withColumn("positive_count", countPositiveSimilarity($"wordListOne", $"wordListTwo"))
</code>```

This is an example code and is similar to my original code.
Example code operates well. Which point should I check in original code and data?

答:
Very interesting question. I have to do some search, and here is my though. Hope this will help you a little bit.

When you create Dataset via createDataset, spark will assign this dataset with LocalRelation logical query plan.

```<code>def createDataset[T : Encoder](data: Seq[T]): Dataset[T] = {
    val enc = encoderFor[T]
    val attributes = enc.schema.toAttributes
    val encoded = data.map(d => enc.toRow(d).copy())
    val plan = new LocalRelation(attributes, encoded)
    Dataset[T](self, plan)
  }
</code>```

Follow this link:
LocalRelation is a leaf logical plan that allow functions like collect or take to be executed locally, i.e. without using Spark executors.

And, it's true as isLocal method point out

```<code> /**
   * Returns true if the `collect` and `take` methods can be run locally
   * (without any Spark executors).
   *
   * @group basic
   * @since 1.6.0
   */
  def isLocal: Boolean = logicalPlan.isInstanceOf[LocalRelation]
</code>```

Obviously, You can check out your 2 datasets is local.

And, the show method actually call take internally.

```<code>private[sql] def showString(_numRows: Int, truncate: Int = 20): String = {
    val numRows = _numRows.max(0)
    val takeResult = toDF().take(numRows + 1)
    val hasMoreData = takeResult.length > numRows
    val data = takeResult.take(numRows)
</code>```

So, with those envidences, I think the call countDF.show is executed, it will behave simliar as when you call count on dict dataset from driver, number of call times is number of records of targets. And, the dict dataset of course doesn't need to be local for the show on countDF work.

You can try to save countDF, it will give you exception same as first case
org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)

Body:
I have a problem executing a Spark application.

Source code:

// Read table From HDFS
val productInformation = spark.table("temp.temp_table1")
val dict = spark.table("temp.temp_table2")

// Custom UDF
val countPositiveSimilarity = udf[Long, Seq[String], Seq[String]]((a, b) =>
    dict.filter(
        (($"first".isin(a: _*) && $"second".isin(b: _*)) || ($"first".isin(b: _*) && $"second".isin(a: _*))) && $"similarity" > 0.7
    ).count
)

val result = productInformation.withColumn("positive_count", countPositiveSimilarity($"title", $"internal_category"))

// Error occurs!
result.show

Error message:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 54.0 failed 4 times, most recent failure: Lost task 0.3 in stage 54.0 (TID 5887, ip-10-211-220-33.ap-northeast-2.compute.internal, executor 150): org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at $anonfun$1.apply(<console>:45)
    at $anonfun$1.apply(<console>:43)
    ... 16 more

Driver stacktrace:
  at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
  at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
  at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
  at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
  at scala.Option.foreach(Option.scala:257)
  at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
  at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
  at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
  at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
  at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
  at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:333)
  at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
  at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2371)
  at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
  at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
  at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2370)
  at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2377)
  at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2113)
  at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2112)
  at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2795)
  at org.apache.spark.sql.Dataset.head(Dataset.scala:2112)
  at org.apache.spark.sql.Dataset.take(Dataset.scala:2327)
  at org.apache.spark.sql.Dataset.showString(Dataset.scala:248)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:636)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:595)
  at org.apache.spark.sql.Dataset.show(Dataset.scala:604)
  ... 48 elided
Caused by: org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)
  at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
  at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
  at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
  at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
  at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
  at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
  at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
  at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
  at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
  at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
  at org.apache.spark.scheduler.Task.run(Task.scala:99)
  at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
  ... 3 more
Caused by: java.lang.NullPointerException
  at $anonfun$1.apply(<console>:45)
  at $anonfun$1.apply(<console>:43)
  ... 16 more

I have checked whether productInformation and dict have null value in Columns. But there are no null values.

Can anyone help me?
I attached example code to let you know more details:

case class Target(wordListOne: Seq[String], WordListTwo: Seq[String])
val targetData = Seq(Target(Seq("Spark", "Wrong", "Something"), Seq("Java", "Grape", "Banana")),
                     Target(Seq("Java", "Scala"), Seq("Scala", "Banana")),
                     Target(Seq(""), Seq("Grape", "Banana")),
                     Target(Seq(""), Seq("")))
val targets = spark.createDataset(targetData)

case class WordSimilarity(first: String, second: String, similarity: Double)
val similarityData = Seq(WordSimilarity("Spark", "Java", 0.8),
                     WordSimilarity("Scala", "Spark", 0.9),
                     WordSimilarity("Java", "Scala", 0.9),
                     WordSimilarity("Apple", "Grape", 0.66),
                     WordSimilarity("Scala", "Apple", -0.1),
                     WordSimilarity("Gine", "Spark", 0.1))
val dict = spark.createDataset(similarityData)

val countPositiveSimilarity = udf[Long, Seq[String], Seq[String]]((a, b) =>
    dict.filter(
        (($"first".isin(a: _*) && $"second".isin(b: _*)) || ($"first".isin(b: _*) && $"second".isin(a: _*))) && $"similarity" > 0.7
    ).count
)

val countDF = targets.withColumn("positive_count", countPositiveSimilarity($"wordListOne", $"wordListTwo"))

This is an example code and is similar to my original code.
Example code operates well. Which point should I check in original code and data?

Body:
Very interesting question. I have to do some search, and here is my though. Hope this will help you a little bit.

When you create Dataset via createDataset, spark will assign this dataset with LocalRelation logical query plan.

def createDataset[T : Encoder](data: Seq[T]): Dataset[T] = {
    val enc = encoderFor[T]
    val attributes = enc.schema.toAttributes
    val encoded = data.map(d => enc.toRow(d).copy())
    val plan = new LocalRelation(attributes, encoded)
    Dataset[T](self, plan)
  }

Follow this link:
LocalRelation is a leaf logical plan that allow functions like collect or take to be executed locally, i.e. without using Spark executors.

And, it's true as isLocal method point out

 /**
   * Returns true if the `collect` and `take` methods can be run locally
   * (without any Spark executors).
   *
   * @group basic
   * @since 1.6.0
   */
  def isLocal: Boolean = logicalPlan.isInstanceOf[LocalRelation]

Obviously, You can check out your 2 datasets is local.

And, the show method actually call take internally.

private[sql] def showString(_numRows: Int, truncate: Int = 20): String = {
    val numRows = _numRows.max(0)
    val takeResult = toDF().take(numRows + 1)
    val hasMoreData = takeResult.length > numRows
    val data = takeResult.take(numRows)

So, with those envidences, I think the call countDF.show is executed, it will behave simliar as when you call count on dict dataset from driver, number of call times is number of records of targets. And, the dict dataset of course doesn't need to be local for the show on countDF work.

You can try to save countDF, it will give you exception same as first case
org.apache.spark.SparkException: Failed to execute user defined function($anonfun$1: (array<string>, array<string>) => bigint)


问:
singleton with throwable initializer
I have a singleton:

```<code>public class Manager {
  static let shared = Manager()
  private init() {
    ...
  }
}
</code>```

Other class can access it by:

```<code>Manager.shared
</code>```

No problem here. Now, I start thinking, what if the private initializer is throwable?

```<code>public class Manager {
   // Compiler error: Call can throw, but erros cannot be thrown out of global variable initializer
   static let shared = Manager()

   // throwable initialier
   private init() throws {
     ...
   }
}
</code>```

How to resolve above error if I still want Manager to be singleton?

答:
THe error you are seeing is very clear. If you don't understand it, I suggest you to read the docs for throwing functions here.

There are several ways to fix this issue, the thing is - why the heck would you mark initialiser for singleton object throwing... One thing you could do is to wrap up the initialiser into setupManager function like this:

```<code>public class Manager {

    static let shared = setupManager()

    // throwable initialier
    private init() throws {

    }

    static func setupManager() -> Manager {

        do {

            return try Manager()
        } catch let error {

            fatalError("error:\(error)")
        }
    }
}
</code>```

In shorter declaration without the setup method:

```<code>public class Manager {

    static var shared: Manager {

        do {

            return try Manager()
        } catch let error {
            // Immediatly stops program execution...
            fatalError("An error occured: \(error)")
        }
    }

    // throwable initialier
    private init() throws {

    }
}
</code>```

The other way to solve this problem would be to use try? and make the shared instance optional (found in the documentation I posted above):

```<code>public class Manager {

    static let shared: Manager? = try? Manager()

    // throwable initialier
    private init() throws {

    }
}
</code>```

Other way around this could be to force unwrap it, but that's not what you want to do since it's really bad approach to problems...

Please keep in mind that always when you code something, fix the core of the problem, not the symptoms, it can always get worse. I don't see any reason for making singleton initialiser throwing in any case, so if you are dependent on some code in the app which should be handed to it, rethink your architecture. Questions are welcome. Wish happy coding!

Title: singleton with throwable initializer

Body:
I have a singleton:

public class Manager {
  static let shared = Manager()
  private init() {
    ...
  }
}

Other class can access it by:

Manager.shared

No problem here. Now, I start thinking, what if the private initializer is throwable?

public class Manager {
   // Compiler error: Call can throw, but erros cannot be thrown out of global variable initializer
   static let shared = Manager()

   // throwable initialier
   private init() throws {
     ...
   }
}

How to resolve above error if I still want Manager to be singleton?

Body:
THe error you are seeing is very clear. If you don't understand it, I suggest you to read the docs for throwing functions here.

There are several ways to fix this issue, the thing is - why the heck would you mark initialiser for singleton object throwing... One thing you could do is to wrap up the initialiser into setupManager function like this:

public class Manager {

    static let shared = setupManager()

    // throwable initialier
    private init() throws {

    }

    static func setupManager() -> Manager {

        do {

            return try Manager()
        } catch let error {

            fatalError("error:\(error)")
        }
    }
}

In shorter declaration without the setup method:

public class Manager {

    static var shared: Manager {

        do {

            return try Manager()
        } catch let error {
            // Immediatly stops program execution...
            fatalError("An error occured: \(error)")
        }
    }

    // throwable initialier
    private init() throws {

    }
}

The other way to solve this problem would be to use try? and make the shared instance optional (found in the documentation I posted above):

public class Manager {

    static let shared: Manager? = try? Manager()

    // throwable initialier
    private init() throws {

    }
}

Other way around this could be to force unwrap it, but that's not what you want to do since it's really bad approach to problems...

Please keep in mind that always when you code something, fix the core of the problem, not the symptoms, it can always get worse. I don't see any reason for making singleton initialiser throwing in any case, so if you are dependent on some code in the app which should be handed to it, rethink your architecture. Questions are welcome. Wish happy coding!


问:
Data Source instance in the list grid
I am using smart gwt 2.2 on windows system in mozilla browser.
I am using List Grid instance in my application.
In that list grid instance I am filling data using data source.
Method for set data:

// Entry point method

```<code>  public void init() {
   final ListGrid grid = new ListGrid();
   DataSource ds= new DataSource();
   ds.setClientOnly(true);
   setDataSourceField(ds);
   ds.setTestData(getGridData());
   grid.setFields(getGridFields());
   grid.setDataSource(ds);
   setGridProperty(grid);
   grid.addClickHandler(new ClickHandler(){
    @Override
    public void onClick(ClickEvent event) {
     DataSource ds= new DataSource();
     ds.setClientOnly(true);
     setDataSourceField(ds);
     ds.setTestData(getGridData());
     grid.setFields(getGridFields());
     grid.setDataSource(ds);
     grid.draw();
    }
   });
   myCanvas.addChild(grid);
  }
</code>```

//dummy data

```<code> private static ListGridRecord[] getGridData() {
   ListGridRecord record = new ListGridRecord();
   record.setAttribute("id", "1");
   record.setAttribute("name", "11");
   record.setAttribute("address", "111");
   ListGridRecord record1 = new ListGridRecord();
   record1.setAttribute("id", "2");
   record1.setAttribute("name", "222");
   record1.setAttribute("address", "222");

   return new ListGridRecord[] { record, record1 };
  }

//grid property
  private static void setGridProperty(ListGrid grid) {
   grid.setWidth("90%");
   grid.setHeight(125);
   grid.setAutoFetchData(true);
  }

//fields
  private static ListGridField[] getGridFields() {
   ListGridField field = new ListGridField("id");
   ListGridField field1 = new ListGridField("name");
   ListGridField field2 = new ListGridField("address");
   return new ListGridField[] { field, field1 ,field2};
  }

//data source field
  protected static void setDataSourceField(DataSource dataSource) {
   DataSourceField idField = new DataSourceField("id", FieldType.TEXT);
   idField.setPrimaryKey(true);
   DataSourceField nameField = new DataSourceField("name",
     FieldType.TEXT);
   DataSourceField addField = new DataSourceField("address", FieldType.TEXT);
   dataSource.setFields(nameField, idField, addField);
  }
</code>```

On click of the row of the grid I want to add a new data source instance to the grid, but it is not showing any data.
Please Help

答: Try grid.invalidateCache()

Title: Data Source instance in the list grid

Body:
I am using smart gwt 2.2 on windows system in mozilla browser.
I am using List Grid instance in my application.
In that list grid instance I am filling data using data source.
Method for set data:

// Entry point method

  public void init() {
   final ListGrid grid = new ListGrid();
   DataSource ds= new DataSource();
   ds.setClientOnly(true);
   setDataSourceField(ds);
   ds.setTestData(getGridData());
   grid.setFields(getGridFields());
   grid.setDataSource(ds);
   setGridProperty(grid);
   grid.addClickHandler(new ClickHandler(){
    @Override
    public void onClick(ClickEvent event) {
     DataSource ds= new DataSource();
     ds.setClientOnly(true);
     setDataSourceField(ds);
     ds.setTestData(getGridData());
     grid.setFields(getGridFields());
     grid.setDataSource(ds);
     grid.draw();
    }
   });
   myCanvas.addChild(grid);
  }

//dummy data

 private static ListGridRecord[] getGridData() {
   ListGridRecord record = new ListGridRecord();
   record.setAttribute("id", "1");
   record.setAttribute("name", "11");
   record.setAttribute("address", "111");
   ListGridRecord record1 = new ListGridRecord();
   record1.setAttribute("id", "2");
   record1.setAttribute("name", "222");
   record1.setAttribute("address", "222");

   return new ListGridRecord[] { record, record1 };
  }

//grid property
  private static void setGridProperty(ListGrid grid) {
   grid.setWidth("90%");
   grid.setHeight(125);
   grid.setAutoFetchData(true);
  }

//fields
  private static ListGridField[] getGridFields() {
   ListGridField field = new ListGridField("id");
   ListGridField field1 = new ListGridField("name");
   ListGridField field2 = new ListGridField("address");
   return new ListGridField[] { field, field1 ,field2};
  }

//data source field
  protected static void setDataSourceField(DataSource dataSource) {
   DataSourceField idField = new DataSourceField("id", FieldType.TEXT);
   idField.setPrimaryKey(true);
   DataSourceField nameField = new DataSourceField("name",
     FieldType.TEXT);
   DataSourceField addField = new DataSourceField("address", FieldType.TEXT);
   dataSource.setFields(nameField, idField, addField);
  }

On click of the row of the grid I want to add a new data source instance to the grid, but it is not showing any data.
Please Help

Body: Try grid.invalidateCache()