问:
Issue sending mail message from ASP.NET MVC application hosted on GoDaddy
I have a form on a MVC Web Application that is hosted over at GoDaddy that users can fill out and send to our office. I am currently testing it using both a Gmail account and a GoDaddy email account (linked to my hosting space).  With the Gmail code in place, the email will send fine from my localhost, but when I publish it to the web I get the following error:

Request for the permission of type 'System.Net.Mail.SmtpPermission,
  System, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' failed.

Here is the code (borrowed from this post) I am using, credentials have been changed and password removed:

```<code>var fromAddress = new MailAddress("iihs.eval@gmail.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt Home Services");
const string fromPassword = "<removed>";
var subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName);
var body = MailBody(results);

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}
</code>```

I then tried to use my GoDaddy email that I set up for this particular form, and again locally it sends. However, when this one is uploaded it just times out rather than give me any sort of useful information. Here is that code:

```<code>var fromAddress = new MailAddress("fea@goimproveit.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt! Home Services");
const string fromPassword = "<removed>";
var client = new SmtpClient
{
    Host = "relay-hosting.secureserver.net",
    Port = 25,
    EnableSsl = false,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Timeout = 20000,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};

using (var msg = new MailMessage(fromAddress, toAddress)
{
    Subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName),
    IsBodyHtml = false,
    Body = MailBody(results)
})
{
    client.Send(msg);
}
</code>```

Originally I had smtpout.secureserver.net for my GoDaddy Host, but I found out from this article that I needed to change it to relay-hosting.secureserver.net. With the updated host information, the script runs but the mail message does not make it to the destination email inbox (or spam box).

Edit

Using Maxim's code, it seems I have gotten a "functioning" version in place. The email does not immediately appear in the destination inbox, but does so after about 15 minutes. Too bad it seems that GoDaddy is a giant PITA when it comes to programmatic emailing.

Here is what I got:

```<code>var emailmessage = new System.Web.Mail.MailMessage()
{
    Subject = subject,
    Body = body,
    From = fromAddress.Address,
    To = toAddress.Address,
    BodyFormat = MailFormat.Text,
    Priority = System.Web.Mail.MailPriority.High
};

SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);
</code>```

Thanks again for the assistance, I hope that I can figure out how to get GoDaddy to cooperate better. If I can, I will post back with updates.

答:
I have some ASP.NET MVC applications hosted on GoDaddy, too, that send out email. Unfortunately, the GoDaddy email policy is somewhat bad:

First of all, you must use relay-hosting.secureserver.net - you cannot use external SMTP servers, like Gmail.

Secondly, relay-hosting is usually very very slow. In my experience, some emails take around 90 minutes to be sent out, while others simply aren't delivered at all.

I've emailed back and forth with GoDaddy support many times about this issue but they have yet to fix the huge wait times/problems or allow external SMTP servers.

As for why your messages aren't delivering, you should try running the script multiple times to make sure that no anomalies are occuring. If it still doesn't work, here's my mail code:

```<code>var emailmessage = new System.Web.Mail.MailMessage()
                                   {
                                       Subject = "Subject",
                                       Body = "Body",
                                       From = "myFromAddress@domain.com",
                                       To = "myToAddress@someotherdomain.com",
                                       BodyFormat = MailFormat.Text,
                                       Priority = MailPriority.High
                                   };

SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);
</code>```

The only thing that is different (as far as I have noticed) is that you are trying to supply credentials to the SMTP server. Actually, relay-hosting.secureserver.net does not require any credentials whatsoever, but it will only send email if it detects that the message is being sent from a GoDaddy server. This might fix your problem!

Body:
I have a form on a MVC Web Application that is hosted over at GoDaddy that users can fill out and send to our office. I am currently testing it using both a Gmail account and a GoDaddy email account (linked to my hosting space).  With the Gmail code in place, the email will send fine from my localhost, but when I publish it to the web I get the following error:

Request for the permission of type 'System.Net.Mail.SmtpPermission,
  System, Version=2.0.0.0, Culture=neutral,
  PublicKeyToken=b77a5c561934e089' failed.

Here is the code (borrowed from this post) I am using, credentials have been changed and password removed:

var fromAddress = new MailAddress("iihs.eval@gmail.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt Home Services");
const string fromPassword = "<removed>";
var subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName);
var body = MailBody(results);

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

I then tried to use my GoDaddy email that I set up for this particular form, and again locally it sends. However, when this one is uploaded it just times out rather than give me any sort of useful information. Here is that code:

var fromAddress = new MailAddress("fea@goimproveit.com", "FEA Drone");
var toAddress = new MailAddress("improveithomeservices@gmail.com", "ImproveIt! Home Services");
const string fromPassword = "<removed>";
var client = new SmtpClient
{
    Host = "relay-hosting.secureserver.net",
    Port = 25,
    EnableSsl = false,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Timeout = 20000,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};

using (var msg = new MailMessage(fromAddress, toAddress)
{
    Subject = string.Format("Energy Evaluation Request for {0} {1}", model.FirstName, model.LastName),
    IsBodyHtml = false,
    Body = MailBody(results)
})
{
    client.Send(msg);
}

Originally I had smtpout.secureserver.net for my GoDaddy Host, but I found out from this article that I needed to change it to relay-hosting.secureserver.net. With the updated host information, the script runs but the mail message does not make it to the destination email inbox (or spam box).

Edit

Using Maxim's code, it seems I have gotten a "functioning" version in place. The email does not immediately appear in the destination inbox, but does so after about 15 minutes. Too bad it seems that GoDaddy is a giant PITA when it comes to programmatic emailing.

Here is what I got:

var emailmessage = new System.Web.Mail.MailMessage()
{
    Subject = subject,
    Body = body,
    From = fromAddress.Address,
    To = toAddress.Address,
    BodyFormat = MailFormat.Text,
    Priority = System.Web.Mail.MailPriority.High
};

SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);

Thanks again for the assistance, I hope that I can figure out how to get GoDaddy to cooperate better. If I can, I will post back with updates.

Body:
I have some ASP.NET MVC applications hosted on GoDaddy, too, that send out email. Unfortunately, the GoDaddy email policy is somewhat bad:

First of all, you must use relay-hosting.secureserver.net - you cannot use external SMTP servers, like Gmail.

Secondly, relay-hosting is usually very very slow. In my experience, some emails take around 90 minutes to be sent out, while others simply aren't delivered at all.

I've emailed back and forth with GoDaddy support many times about this issue but they have yet to fix the huge wait times/problems or allow external SMTP servers.

As for why your messages aren't delivering, you should try running the script multiple times to make sure that no anomalies are occuring. If it still doesn't work, here's my mail code:

var emailmessage = new System.Web.Mail.MailMessage()
                                   {
                                       Subject = "Subject",
                                       Body = "Body",
                                       From = "myFromAddress@domain.com",
                                       To = "myToAddress@someotherdomain.com",
                                       BodyFormat = MailFormat.Text,
                                       Priority = MailPriority.High
                                   };

SmtpMail.SmtpServer = "relay-hosting.secureserver.net";
SmtpMail.Send(emailmessage);

The only thing that is different (as far as I have noticed) is that you are trying to supply credentials to the SMTP server. Actually, relay-hosting.secureserver.net does not require any credentials whatsoever, but it will only send email if it detects that the message is being sent from a GoDaddy server. This might fix your problem!


来源: stackexchange

问:
how to pass variable from a function to render function in react
I am new in react. following a tutorial, where they are introducing state to find out wheather checkbox is checked or not. But i wanted to do that in this style:

```<code><script type="text/babel">
  var Checkbox = React.createClass({
    change: function(){
      var msg;
      var val= document.getElementById('check').checked;
      if(val==true){
        msg = 'checked';
      }else{
        msg = 'Not checked';
      }
    },
    render: function(){
      return(<div>
          <input onChange={this.change} id="check" type="Checkbox" />
          <p>Checkbox is {this.msg}.</p>
        </div>);
    }
  });
  ReactDOM.render(<Checkbox/>, document.getElementById('container'));
</script>
</code>```

so, the problem is i cant pass the variable "msg" into render function.

答:
If you want to render the message in UI, then msg should be set in state using setState function, so that re-render can happen.

For any other case where re-render is not required, variable can be created as class variable inside constructor and use in any function.

```<code>constructor(props){
super(props);
this.myVariable='';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new in react. following a tutorial, where they are introducing state to find out wheather checkbox is checked or not. But i wanted to do that in this style:

so, the problem is i cant pass the variable "msg" into render function.

Body:
If you want to render the message in UI, then msg should be set in state using setState function, so that re-render can happen.

For any other case where re-render is not required, variable can be created as class variable inside constructor and use in any function.

constructor(props){
super(props);
this.myVariable='';
}


问:
Converting pandas date column into seconds elapsed
I have a pandas dataframe of multiple columns with a column of datetime64[ns] data. Time is in HH:MM:SS format. How can I convert this column of dates into a column of seconds elapsed? Like if the time said 10:00:00 in seconds that would be 36000. The seconds should be in a float64 type format.

Example data column

答:
it would work:

```<code>df['time'].dt.total_seconds()
</code>```

regards

Body:
it would work:

df['time'].dt.total_seconds()

regards


问:
Mailgun emails not going out
I'm creating a verification email, however the mail isn't going out and I don't receive any errors.

My call to send the email:

```<code>public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    Mail::to($user->email)
        ->queue(new VerifyEmail($user));

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}
</code>```

here's my email build function:

```<code>public function build()
{
    return $this->view('emails.account.verify_email')
                ->with([
                    'id' => $this->user->id,
                    'firstname' => $this->user->firstname,
                    'token' => $this->user->email_verification_token,
                ]);
}
</code>```

I installed guzzlehttp/guzzle

and changed my files:

ENV (not sure of the port setting)

```<code>MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=postmaster@sandbox...655.mailgun.org
MAIL_PASSWORD=Default mailgun sandbox Password
MAIL_ENCRYPTION=tls
</code>```

config/services

```<code>'mailgun' => [
    'domain' => env('sandbox...655.mailgun.org'),
    'secret' => env('key-...'),
],
</code>```

config/mail

```<code><?php

return [

    'driver' => env('MAIL_DRIVER', 'mailgun'),

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    'port' => env('MAIL_PORT', 587),

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    'sendmail' => '/usr/sbin/sendmail -bs',

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];
</code>```

I don't receive any errors, however there are no outgoing mails when I check the mailgun dashboard

答:
Your services config file is wrong:

```<code>'mailgun' => [
    'domain' => env('sandbox...655.mailgun.org'),
    'secret' => env('key-...'),
],
</code>```

You're trying to look up the values from the .env file here. Should reference the keys, not the values. For instance:

```<code>'mailgun' => [
    'domain' => env('MAIL_DOMAIN'),
    'secret' => env('MAIL_SECRET'),
],
</code>```

And then add them to your .env file:

```<code>MAIL_DOMAIN=sandbox...655.mailgun.org
MAIL_KEY=key-...
</code>```

I'm assuming the rest is correct but I don't know for certain. :)

Title: Mailgun emails not going out

Body:
I'm creating a verification email, however the mail isn't going out and I don't receive any errors.

My call to send the email:

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    Mail::to($user->email)
        ->queue(new VerifyEmail($user));

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

here's my email build function:

public function build()
{
    return $this->view('emails.account.verify_email')
                ->with([
                    'id' => $this->user->id,
                    'firstname' => $this->user->firstname,
                    'token' => $this->user->email_verification_token,
                ]);
}

I installed guzzlehttp/guzzle

and changed my files:

ENV (not sure of the port setting)

MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=postmaster@sandbox...655.mailgun.org
MAIL_PASSWORD=Default mailgun sandbox Password
MAIL_ENCRYPTION=tls

config/services

'mailgun' => [
    'domain' => env('sandbox...655.mailgun.org'),
    'secret' => env('key-...'),
],

config/mail

<?php

return [

    'driver' => env('MAIL_DRIVER', 'mailgun'),

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    'port' => env('MAIL_PORT', 587),

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    'sendmail' => '/usr/sbin/sendmail -bs',

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

I don't receive any errors, however there are no outgoing mails when I check the mailgun dashboard

Body:
Your services config file is wrong:

'mailgun' => [
    'domain' => env('sandbox...655.mailgun.org'),
    'secret' => env('key-...'),
],

You're trying to look up the values from the .env file here. Should reference the keys, not the values. For instance:

'mailgun' => [
    'domain' => env('MAIL_DOMAIN'),
    'secret' => env('MAIL_SECRET'),
],

And then add them to your .env file:

MAIL_DOMAIN=sandbox...655.mailgun.org
MAIL_KEY=key-...

I'm assuming the rest is correct but I don't know for certain. :)


问:
Getting values from an api ordered by a common parameter
How would one go about listing all the values in this api in a html table ordered by their "position24" value?

I know how to call each individual value, but I'm not sure of how to automatically load them in that order.

http://www.coincap.io/front

答:
You can call your API, decode the JSON, sort it by this key and return it in a table. The following lines are a base for your solution.

```<code>function compare($a, $b) {
    return intval($a->position24) - intval($b->position24);
}

$json = file_get_contents('http://www.coincap.io/front');
$data = json_decode($json);
usort($data, 'compare');
// display $data in a table
</code>```

If you use classes and the compare function (compare) is in the same class as the usort-function-call you should use:

```<code>usort($data, array($this, 'compare'));
</code>```

UPDATE:

You can echo out your table by calling the attribute like this:

```<code>foreach ($data as $row) {
    echo $row->long;
    echo $row->position24;
}
</code>```

Because there are so many values, I let it up to, which one you want to display. If you need help how to build a table you find more information here.

Body:
You can call your API, decode the JSON, sort it by this key and return it in a table. The following lines are a base for your solution.

function compare($a, $b) {
    return intval($a->position24) - intval($b->position24);
}

$json = file_get_contents('http://www.coincap.io/front');
$data = json_decode($json);
usort($data, 'compare');
// display $data in a table

If you use classes and the compare function (compare) is in the same class as the usort-function-call you should use:

usort($data, array($this, 'compare'));

UPDATE:

You can echo out your table by calling the attribute like this:

foreach ($data as $row) {
    echo $row->long;
    echo $row->position24;
}

Because there are so many values, I let it up to, which one you want to display. If you need help how to build a table you find more information here.


问:
A web app with logins in a kiosk situation
We are looking at setting up an internal web application (ASP.NET MVC) as a kiosk for the employees that don't have a dedicated computer. We currently do not have this kiosk setup. Each employee will have their own login to look at some basic payroll information and request leaves of absence. This same web application will be used by the office workers with a dedicated PC at their desk.

I am going to go out on a limb and say that no matter how many times we tell the employees, the employees will not click log off when they walk away from the kiosk. What would you do to help prevent this from happening?

答:
lets try to fix the users instead of the code :) , i guess that your log out button is like the one here on stackoverflow. its a little text link "logout" some where in the upper right corner. thats perfect for people who use webapps day by day and are aware of the fact that they need to logout before someone comes along a does havoc to thier facebook profile, but less tech savy users wont think of that and walk away.

you need to the get the attention of your users to this logout-button and teach them that logging-out is a good thing.

try the following

give the logout button more visual weight then usally make it bigger, make it a real button instead of a textlink and even change its color to something more alerting (red, orange, ... whatever fits your ci)

if they dont loggout, use the session timeout and some javascript the refresh the page after any amount of inactivity, but also set a flag that this user has not logged out after his last visit. that way you can greet him on his next login with a nice confirmation dialog, and tell him once again why logging out is so important and where your logout-button is located.

ContentLicense: CC BY-SA 2.5


问:
Kendo Grid DateTime Column Shows Incorrect Date
I have a Kendo Grid which have a datetime columns, while fetching the date from database we are getting correct date but during display Date gets changed. For ex:
DB date is 07/06/2017 but while display on website it gets changed into 06/06/2017, considering MM/DD/YYYY. Could anyone please help me on this. Our DB and Website both located in new york region.</p>

答:
The Kendo UI DataSource uses JavaScript Date objects for dates. These objects are always in the client's time zone, which may lead to changes in the date. A possible option is to use UTC dates:

http://docs.telerik.com/aspnet-mvc/helpers/grid/how-to/editing/utc-time-on-both-server-and-client

Edit, just copy the content of the link to here, because SO does not like the link the only answer

Use a ViewModel with a setter and a getter that explicitly set the DateTime Kind to UTC.

```<code>private DateTime birthDate;
public DateTime BirthDate
{
    get { return this.birthDate; }
    set {
        this.birthDate = new DateTime(value.Ticks, DateTimeKind.Utc);
    }
}
</code>```

Use the requestEnd event of the DataSource to intercept and replace the incoming Date field with the time difference.

```<code>@(Html.Kendo().Grid<KendoUIMVC5.Models.Person>().Name("persons")
    .DataSource(dataSource => dataSource
        .Ajax()
        .Events(ev=>ev.RequestEnd("onRequestEnd"))
    )
    // ...
)

<script>
    var onRequestEnd = function(e) {
        if (e.response.Data && e.response.Data.length) {
            var data = e.response.Data;
            if (this.group().length && e.type == "read") {
                handleGroups(data);
            } else {
                loopRecords(data);
            }
        }
    }

    function handleGroups(groups) {
        for (var i = 0; i < groups.length; i++) {
            var gr = groups[i];
            offsetDateFields(gr); //handle the Key variable as well
            if (gr.HasSubgroups) {
                handleGroups(gr.Items)
            } else {
                loopRecords(gr.Items);
            }
        }
    }

    function loopRecords(persons) {
        for (var i = 0; i < persons.length; i++) {
            var person = persons[i];
            offsetDateFields(person);
        }
    }

    function offsetDateFields(obj) {
        for (var name in obj) {
            var prop = obj[name];
            if (typeof (prop) === "string" && prop.indexOf("/Date(") == 0) {
                obj[name] = prop.replace(/\d+/, function (n) {
                    var offsetMiliseconds = new Date(parseInt(n)).getTimezoneOffset() * 60000;
                    return parseInt(n) + offsetMiliseconds
                });
            }
        }
    }
</script>
</code>```

Body:
The Kendo UI DataSource uses JavaScript Date objects for dates. These objects are always in the client's time zone, which may lead to changes in the date. A possible option is to use UTC dates:

http://docs.telerik.com/aspnet-mvc/helpers/grid/how-to/editing/utc-time-on-both-server-and-client

Edit, just copy the content of the link to here, because SO does not like the link the only answer

Use a ViewModel with a setter and a getter that explicitly set the DateTime Kind to UTC.

private DateTime birthDate;
public DateTime BirthDate
{
    get { return this.birthDate; }
    set {
        this.birthDate = new DateTime(value.Ticks, DateTimeKind.Utc);
    }
}

Use the requestEnd event of the DataSource to intercept and replace the incoming Date field with the time difference.

@(Html.Kendo().Grid<KendoUIMVC5.Models.Person>().Name("persons")
    .DataSource(dataSource => dataSource
        .Ajax()
        .Events(ev=>ev.RequestEnd("onRequestEnd"))
    )
    // ...
)

<script>
    var onRequestEnd = function(e) {
        if (e.response.Data && e.response.Data.length) {
            var data = e.response.Data;
            if (this.group().length && e.type == "read") {
                handleGroups(data);
            } else {
                loopRecords(data);
            }
        }
    }

    function handleGroups(groups) {
        for (var i = 0; i < groups.length; i++) {
            var gr = groups[i];
            offsetDateFields(gr); //handle the Key variable as well
            if (gr.HasSubgroups) {
                handleGroups(gr.Items)
            } else {
                loopRecords(gr.Items);
            }
        }
    }

    function loopRecords(persons) {
        for (var i = 0; i < persons.length; i++) {
            var person = persons[i];
            offsetDateFields(person);
        }
    }

    function offsetDateFields(obj) {
        for (var name in obj) {
            var prop = obj[name];
            if (typeof (prop) === "string" && prop.indexOf("/Date(") == 0) {
                obj[name] = prop.replace(/\d+/, function (n) {
                    var offsetMiliseconds = new Date(parseInt(n)).getTimezoneOffset() * 60000;
                    return parseInt(n) + offsetMiliseconds
                });
            }
        }
    }
</script>

ContentLicense: CC BY-SA 4.0


问:
Historical Google Static Map Images
It is possible to download recent earth images from http://staticmapmaker.com/google/.

Question: Is there some way to download historical earth images?

I guess google must have these somewhere, since previously it was possible to download images from 2015 from the very same webpage mentioned above.

I am aware historical images are available in Google Earth, but I have no clue how to download these in a similar way (same zoom level and size) as is possible from Google Static Maps API.

Thanks a lot!

答:
Currently there is no way to get historical imagery via Google Static Maps API.

You can see the corresponding feature request in the issue tracker:

https://issuetracker.google.com/issues/35826354

Feel free to star the feature request to add your vote and subscribe to further notifications from Google.

Title: Historical Google Static Map Images


问:
How can I select all posts which have specific tags?
Here is my table structure:

```<code>// posts
+----+-----------+---------------------+-------------+
| id |   title   |        body         |   keywords  |
+----+-----------+---------------------+-------------+
| 1  | title1    | Something here      | php,oop     |
| 2  | title2    | Something else      | html,css,js |
+----+-----------+---------------------+-------------+

// tags
+----+----------+
| id |   name   |
+----+----------+
| 1  | php      |
| 2  | oop      |
| 3  | html     |
| 4  | css      |
| 5  | js       |
+----+----------+

// pivot
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1       | 1      |
| 1       | 2      |
| 2       | 3      |
| 2       | 4      |
| 2       | 5      |
+---------+--------+
</code>```

Ok well, I have two tags (php and html) and I need to select all posts tagged with them. How can I do that?

Currently I use REGEXP and simply select what I want like this:

```<code>SELECT * FROM posts WHERE keywords REGEXP 'php|html';
</code>```

See? I don't use even 1 join. These days my dataset is grown up and my query takes a while to be executed. I guess I have to use a relational feature like join.  However I'm not sure it would be better than my current query.

Anyway, does anybody know, how can I get the expected result faster?

答:
You already have a normalized design with a many to many relationship. There is no need to have the keywords column in the posts table, as the pivot already establishes the same.

You just need to do the join properly. Try this:

```<code>SELECT posts.id
  FROM posts
LEFT OUTER JOIN pivot
  ON posts.id = pivot.post_id
LEFT OUTER JOIN tags
  ON pivot.tag_id = tags.id
WHERE tags.name = "php" or tags.name = "html"
GROUP BY posts.id;
</code>```

This will give you all the id's of the posts with the tags.

Body:
Here is my table structure:

// posts
+----+-----------+---------------------+-------------+
| id |   title   |        body         |   keywords  |
+----+-----------+---------------------+-------------+
| 1  | title1    | Something here      | php,oop     |
| 2  | title2    | Something else      | html,css,js |
+----+-----------+---------------------+-------------+

// tags
+----+----------+
| id |   name   |
+----+----------+
| 1  | php      |
| 2  | oop      |
| 3  | html     |
| 4  | css      |
| 5  | js       |
+----+----------+

// pivot
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1       | 1      |
| 1       | 2      |
| 2       | 3      |
| 2       | 4      |
| 2       | 5      |
+---------+--------+

Ok well, I have two tags (php and html) and I need to select all posts tagged with them. How can I do that?

Currently I use REGEXP and simply select what I want like this:

SELECT * FROM posts WHERE keywords REGEXP 'php|html';

See? I don't use even 1 join. These days my dataset is grown up and my query takes a while to be executed. I guess I have to use a relational feature like join.  However I'm not sure it would be better than my current query.

Anyway, does anybody know, how can I get the expected result faster?

Body:
You already have a normalized design with a many to many relationship. There is no need to have the keywords column in the posts table, as the pivot already establishes the same.

You just need to do the join properly. Try this:

SELECT posts.id
  FROM posts
LEFT OUTER JOIN pivot
  ON posts.id = pivot.post_id
LEFT OUTER JOIN tags
  ON pivot.tag_id = tags.id
WHERE tags.name = "php" or tags.name = "html"
GROUP BY posts.id;

This will give you all the id's of the posts with the tags.


问:
What's the quickest way to assign a variables based on an array?
What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

```<code>var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...
</code>```

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.

答:
try it:    </p>

```<code>var abbrev = '';
    if(state.indexOf(' ') == -1){
    abbrev = state.substring(0,2).toUpperCase();
    }else{
    var firstLetter = state.substring(0,1).toUpperCase();
    var secoundLetter = state.substring(state.indexOf(' '),1).toUpperCase();
    abbrev = firstLetter  + secoundLetter;
    }
    alert(abbrev);
</code>```

Body:
What's the quickest way, from a readability/typing standpoint, to assign a value to a specific variable based on a related variable?

var abbrev;

if(state=='Pennsylvania'){
    abbrev='PA';
}else if(state=='New Jersey'){
    abbrev='NJ';
}else if(state=='Delaware'){
    abbrev='DE';
}
//and so on...

I'm trying to avoid making one array for the state name and a another array for the abbreviation because the relationship is lost with separate declarations.

Body:
try it:

var abbrev = '';
    if(state.indexOf(' ') == -1){
    abbrev = state.substring(0,2).toUpperCase();
    }else{
    var firstLetter = state.substring(0,1).toUpperCase();
    var secoundLetter = state.substring(state.indexOf(' '),1).toUpperCase();
    abbrev = firstLetter  + secoundLetter;
    }
    alert(abbrev);


问:
Lubuntu. /bin/sh: 2: xtensa-lx106-elf-gcc: not found
I'm am a very beginner at this area and I have a problem compiling an example from ESP8266_NONOS_SDK-master.

I've been following steps described in ESP8266 SDK Getting Started Guide form the documentation.

That means that I downloaded virtual box esp8266 image (ESP8266_lubuntu_20141021.ova) where all tools as I understood must be set up.
But while compiling the example I am getting:

```<code>/bin/sh: 2: xtensa-lx106-elf-gcc: not found
</code>```

error.

echo $PATH returns: /opt/xtensa-lx106-elf/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

and xtensa-lx106-elf-gcc -v returns Configured with ...gcc version 4.8.2 (crosstool-NG 1.20.0)

The compilation happens under esp8266/Share folder.

Can someone tell me what am I missing and how to get SDK to 'see' xtensa-lx106-elf-gcc?

Lubuntu directory tree image:

答:
Xtensa crosstool-NG was missing. To install it used this method. (Do not forget to chown $username /opt/espressif/ in order to avoid   'Permission denied' error while compilation.
 Also to upgrade OS (if this is chosen) and build crosstool-NG in /opt/espressif, enlarge VM disc size, as it might run out of free space.)

Body:
I'm am a very beginner at this area and I have a problem compiling an example from ESP8266_NONOS_SDK-master.

I've been following steps described in ESP8266 SDK Getting Started Guide form the documentation.

That means that I downloaded virtual box esp8266 image (ESP8266_lubuntu_20141021.ova) where all tools as I understood must be set up.
But while compiling the example I am getting:

/bin/sh: 2: xtensa-lx106-elf-gcc: not found

error.

echo $PATH returns: /opt/xtensa-lx106-elf/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

and xtensa-lx106-elf-gcc -v returns Configured with ...gcc version 4.8.2 (crosstool-NG 1.20.0)

The compilation happens under esp8266/Share folder.

Can someone tell me what am I missing and how to get SDK to 'see' xtensa-lx106-elf-gcc?

Lubuntu directory tree image:


问:
center image while keeping footer
I've been working on trying to get an image to center (was able to do that) while still having a footer that would stick at the bottom of the page.

I can't seem to figure out how to position the footer at the bottom, because of the way I'm positioning the image.

This is what I have:

```<code>body {
    margin:0;
    padding:0;
    text-align:center;
    background-color:black;
    color: #463D38;
}

#Content {
    clear:both;
    width:500px;
    margin:0px auto;
    text-align:center;
    padding:15px;
    height:240px;
    position:absolute;
    top: 50%;
    left: 50%;
}

#inner {
    position: relative;
    top: -50%;
    left: -50%;
}

#text-center{
    text-align:center;
    font-family:Tahoma, Geneva, sans-serif
}

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}
</code>```

Here is the HTML code of the page:

```<code><head>
<title>Title</title>
</head>

<body>
<div id="Content">
<div id="inner">
<img src="logo332.png" width="500" height="163">
</div>

<div class="footer">test</div>
</body>
</html>
</code>```

Any pointers or suggestions on how I can have these two playing nicely with each other?

Much appreciated.

答: If you want to stick the footer, then you need to make it position:fixed; </p>

Title: center image while keeping footer

Body:
I've been working on trying to get an image to center (was able to do that) while still having a footer that would stick at the bottom of the page.

I can't seem to figure out how to position the footer at the bottom, because of the way I'm positioning the image.

This is what I have:

body {
    margin:0;
    padding:0;
    text-align:center;
    background-color:black;
    color: #463D38;
}

#Content {
    clear:both;
    width:500px;
    margin:0px auto;
    text-align:center;
    padding:15px;
    height:240px;
    position:absolute;
    top: 50%;
    left: 50%;
}

#inner {
    position: relative;
    top: -50%;
    left: -50%;
}

#text-center{
    text-align:center;
    font-family:Tahoma, Geneva, sans-serif
}

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  background-color: #efefef;
  text-align: center;
}

Here is the HTML code of the page:

<title>Title</title>

test

Any pointers or suggestions on how I can have these two playing nicely with each other?

Much appreciated.


问:
Split a string into a String[] of a specific size
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

```<code>String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]
</code>```

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

答:
Simply getting the position of the delimiter and using substrings gets you there pretty easily:  </p>

```<code>public static String[] split(String str, int limit){

           String[] arr = new String[limit];

           for(int i = 0; i < limit-1; i++){
               int position = str.indexOf(',');
               int length = str.length();

               if(position == -1){
                   arr[i]= str.substring(0,length);
                   str = str.substring(length, length);
               }
               else{
                   arr[i] = str.substring(0, position);
                   str = str.substring(position+1, length);
               }
            }

            arr[limit-1] = str;

            return arr;
       }
</code>```

Body:
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

Body:
Simply getting the position of the delimiter and using substrings gets you there pretty easily:

public static String[] split(String str, int limit){

           String[] arr = new String[limit];

           for(int i = 0; i < limit-1; i++){
               int position = str.indexOf(',');
               int length = str.length();

               if(position == -1){
                   arr[i]= str.substring(0,length);
                   str = str.substring(length, length);
               }
               else{
                   arr[i] = str.substring(0, position);
                   str = str.substring(position+1, length);
               }
            }

            arr[limit-1] = str;

            return arr;
       }


问:
Angular 2 how do I test a component that uses router
I am trying to write some tests for a component that calls router.navigate() and I'm stuck on errors with declaring the routes. I've read a lot of things and tried all of them but they all lead to some error or another. I am using Angular 4.0.0.

Component:

```<code>@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  constructor(
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    private formBuilder: FormBuilder,
    private jwtService: JwtService,
    private router: Router,
    private storageService: StorageService
  ) { ... }

  ngOnInit() {
  }

  private login(formData: any): void {
    const credentials: any = {
      email: formData.controls.email.value,
      password: formData.controls.password.value
    };
    this.authService.login(credentials).subscribe(res => {
      this.activatedRoute.params.subscribe(params => {
        if (params.returnUrl) {
          this.router.navigate([params.returnUrl]);
        } else {
          this.router.navigate(['/dashboard']);
        }
      });
    }, error => { ... });
  }
}
</code>```

Test:

```<code>describe('LoginComponent', () => {
  let component: any;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [
        SharedModule,
        RouterTestingModule
      ],
      providers: [{
        provide: AuthService,
        useClass: MockAuthService
      }, {
        provide: JwtService,
        useClass: MockJwtService
      }, {
        provide: StorageService,
        useClass: MockStorageService
      }],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  describe('login', () => {
    it('should call router.navigate with the dashboard route if the login is successful', () => {
      spyOn(component.router, 'navigate');
      component.authService.login.and.returnValue(Observable.of({ access_token: 'fake_token' }));
      component.login(component.loginForm);
      expect(component.router.navigate).toHaveBeenCalledWith(['/dashboard']);
    });
  });
});
</code>```

This all gives me the following error:

zone.js:569 Unhandled Promise rejection: Cannot match any routes. URL Segment: 'dashboard'

So from there I looked into adding the route with withRoutes. I don't like that I need to include the DashboardComponent since it seems like there should be some mocked/blank component available for this especially since I don't want to actually navigate and load another route but I couldn't find anything like that:

```<code>TestBed.configureTestingModule({
  declarations: [ LoginComponent ],
  imports: [
    SharedModule,
    RouterTestingModule.withRoutes([{
      path: 'dashboard',
      component: DashboardComponent
    }])
  ],
  ...
})
.compileComponents();
</code>```

However that just give me a new error:

Component DashboardComponent is not part of any NgModule or the module has not been imported into your module.

So I thought that maybe I needed to declare the DashboardComponent, so I added it to the declarations array:

```<code>TestBed.configureTestingModule({
  declarations: [ LoginComponent, DashboardComponent ],
  ..
})
.compileComponents();
</code>```

However that just lead to yet another error:

Unhandled Promise rejection: Cannot find primary outlet to load 'DashboardComponent'

At this point it seems like there must be a simpler way to do this as it's a very common scenario but I've tried everything others say they used and everything just leads further down this rabbit hole.

答:
I found a slightly different solution then @efarley, which takes his answer and changes what the injector is provided.  Thought I'd add this in as well in case it helps anyone.  I used the Angular CLI so the spec is setup with the default blueprint for a test, and I've removed bits for brevity.</p>

```<code>// NOTE: Other required test imports removed for brevity so this snippet
// only represents the minimum viable code required to test a route
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let de: DebugElement;
  let el: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        LoginComponent
      ],
      providers: []
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    fixture.detectChanges();
  });

  it('form submission login and navigating to the dashboard', () => {
    el = de.nativeElement.querySelector('button[type="submit"]');

    // **ONLY** difference between the solutions is what is passed to the injector
    spyOn(de.injector.get(Router), 'navigate');
    el.click();

    expect(de.injector.get(Router).navigate)
      .toHaveBeenCalledWith(['dashboard']);
  });
</code>```

Body:
I am trying to write some tests for a component that calls router.navigate() and I'm stuck on errors with declaring the routes. I've read a lot of things and tried all of them but they all lead to some error or another. I am using Angular 4.0.0.

Component:

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  constructor(
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    private formBuilder: FormBuilder,
    private jwtService: JwtService,
    private router: Router,
    private storageService: StorageService
  ) { ... }

  ngOnInit() {
  }

  private login(formData: any): void {
    const credentials: any = {
      email: formData.controls.email.value,
      password: formData.controls.password.value
    };
    this.authService.login(credentials).subscribe(res => {
      this.activatedRoute.params.subscribe(params => {
        if (params.returnUrl) {
          this.router.navigate([params.returnUrl]);
        } else {
          this.router.navigate(['/dashboard']);
        }
      });
    }, error => { ... });
  }
}

Test:

describe('LoginComponent', () => {
  let component: any;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [
        SharedModule,
        RouterTestingModule
      ],
      providers: [{
        provide: AuthService,
        useClass: MockAuthService
      }, {
        provide: JwtService,
        useClass: MockJwtService
      }, {
        provide: StorageService,
        useClass: MockStorageService
      }],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  describe('login', () => {
    it('should call router.navigate with the dashboard route if the login is successful', () => {
      spyOn(component.router, 'navigate');
      component.authService.login.and.returnValue(Observable.of({ access_token: 'fake_token' }));
      component.login(component.loginForm);
      expect(component.router.navigate).toHaveBeenCalledWith(['/dashboard']);
    });
  });
});

This all gives me the following error:

zone.js:569 Unhandled Promise rejection: Cannot match any routes. URL Segment: 'dashboard'

So from there I looked into adding the route with withRoutes. I don't like that I need to include the DashboardComponent since it seems like there should be some mocked/blank component available for this especially since I don't want to actually navigate and load another route but I couldn't find anything like that:

TestBed.configureTestingModule({
  declarations: [ LoginComponent ],
  imports: [
    SharedModule,
    RouterTestingModule.withRoutes([{
      path: 'dashboard',
      component: DashboardComponent
    }])
  ],
  ...
})
.compileComponents();

However that just give me a new error:

Component DashboardComponent is not part of any NgModule or the module has not been imported into your module.

So I thought that maybe I needed to declare the DashboardComponent, so I added it to the declarations array:

TestBed.configureTestingModule({
  declarations: [ LoginComponent, DashboardComponent ],
  ..
})
.compileComponents();

However that just lead to yet another error:

Unhandled Promise rejection: Cannot find primary outlet to load 'DashboardComponent'

At this point it seems like there must be a simpler way to do this as it's a very common scenario but I've tried everything others say they used and everything just leads further down this rabbit hole.

Body:
I found a slightly different solution then @efarley, which takes his answer and changes what the injector is provided.  Thought I'd add this in as well in case it helps anyone.  I used the Angular CLI so the spec is setup with the default blueprint for a test, and I've removed bits for brevity.

// NOTE: Other required test imports removed for brevity so this snippet
// only represents the minimum viable code required to test a route
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';

describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  let de: DebugElement;
  let el: HTMLElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        LoginComponent
      ],
      providers: []
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    fixture.detectChanges();
  });

  it('form submission login and navigating to the dashboard', () => {
    el = de.nativeElement.querySelector('button[type="submit"]');

    // **ONLY** difference between the solutions is what is passed to the injector
    spyOn(de.injector.get(Router), 'navigate');
    el.click();

    expect(de.injector.get(Router).navigate)
      .toHaveBeenCalledWith(['dashboard']);
  });


Title: How to add groupBy().count() to the source DataFrame?

Body:
I have the following dataframe:

+---------------+--------------+--------------+-----+
|        column0|       column1|       column2|label|
+---------------+--------------+--------------+-----+
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|
+---------------+--------------+--------------+-----+

I want to apply groupBy and count on it and make the following result:

+--------------+--------------+-----+
|       column1|       column2|count|
+--------------+--------------+-----+
|10.0.0.2.54880| 10.0.0.3.5001|   19|
| 10.0.0.3.5001|10.0.0.2.54880|   10|
+--------------+--------------+-----+

I know that I have to use this:

dataFrame_Train.groupBy("column1", "column2").count().show()

However the problem is that I need to add "count" column as a permanent column to my dataframe.
In the above case, if I use dataFrame_Train.show() after the groupBy, I see the first dataframe without "count" column. This code:

dataFrame_Train.groupBy("column1", "column2").count().show()
`dataFrame_Train.show()`

Can you help me to add groupBy("column1", "column2").count() to the dataframe? (Since I need to use "count" column for training the data in future) Thanks.

Body:
@eliasah's answer is fine, but might not be the most effective, code- and performance-wise.

Window Aggregate Functions (aka Window Aggregations)

Whenever you see a need for groupBy and join, esp. for such a simple use case like this, think of window aggregate functions.

The main difference between groupBy and window aggregations is that the former gives you at most the number of rows as in the source dataset while the latter (window aggregates) gives you exactly the number of rows as in the source dataset. That seems to match your requirements exactly, doesn't it?

With that, let's see the code.

import org.apache.spark.sql.expressions.Window
val columns1and2 = Window.partitionBy("column1", "column2") // <-- matches groupBy

import org.apache.spark.sql.functions._
// using count aggregate function over entire partition frame
val counts = ips.withColumn("count", count($"label") over columns1and2)
scala> counts.show
+---------------+--------------+--------------+-----+-----+
|        column0|       column1|       column2|label|count|
+---------------+--------------+--------------+-----+-----+
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604900|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604899|10.0.0.2.54880| 10.0.0.3.5001|    2|   13|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
|05:49:56.604908| 10.0.0.3.5001|10.0.0.2.54880|    2|    7|
+---------------+--------------+--------------+-----+-----+

Done! Clean and easy. That's my beloved window aggregate functions!

Performance Comparison

Now, comes the fun part. Is the difference between this and @eliasah's solutions just pure syntax? I don't think so (yet I'm still learning how to draw right conclusions). See the execution plans and judge yourself.

The following is the execution plan for window aggregation.

The following however is the execution plan for groupBy and join (I had to take two screenshots as the plan was too big to include in one).

Job-wise groupBy and join query beats window aggregation easily, 2 Spark jobs for the former while 5 for the latter.

Operator-wise, their number and most importantly Exchanges (which are Spark SQL's shuffles), window aggregation may have beaten groupBy with join.


问:
Laravel 5.4 Sessions and Auth::user() not available in controller's constructor
I would like to use a User class throught the application. So, I would like to create CustomUser and then inject it into controllers that need it (it would be most of them).

Now, I create an empty instance in serviceprovider. Next, I want to fill it with data that are already saved in Auth::user(). After long time I have not found where to do it.

Auth::user() is empty in middlewares, but is filled with the user data in controllers. I am missing the step where Laravel queries the database and fills Auth:user() with data. I want to avoid making the same query again.

Thanks for any help!

答:
Since Laravel 5.3, you do not have access to sessions in controller constructors. This is because the middleware has not been run yet. I know it's difficult to locate, but in the migration documentation from 5.2 > 5.3 (you're probably on 5.4), it shows that the proper way to resolve data from sessions (which auth() is just a wrapper around a session() call to get the user), is to use the following method:

```<code>class MyController extends Controller {
    protected $user;

    public function __construct() {
        $this->middleware(function ($request, $next) {
           $this->user= auth()->user();

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

Then $this->user will reference the auth user to any methods inside of this controller.

Hopefully his helps.

Body:
Since Laravel 5.3, you do not have access to sessions in controller constructors. This is because the middleware has not been run yet. I know it's difficult to locate, but in the migration documentation from 5.2 > 5.3 (you're probably on 5.4), it shows that the proper way to resolve data from sessions (which auth() is just a wrapper around a session() call to get the user), is to use the following method:

class MyController extends Controller {
    protected $user;

    public function __construct() {
        $this->middleware(function ($request, $next) {
           $this->user= auth()->user();

           return $next($request);
        });
    }
}

Then $this->user will reference the auth user to any methods inside of this controller.

Hopefully his helps.


问:
Is it necessary to initialize static class variables?
I started learning python few days ago and I am trying out different things.

I wrote code as follows:

```<code>class ConsumeState:
    token
</code>```

I got following error for this code

NameError: name 'token' is not defined
```

So I initialized token to "abc" and the error was gone.

My question is what if I don't want to define the static variable at this point what should I do for that? Is it always necessary to initialize static variable in python?

答:
Unlike C,Java,C# and so on, in python you don't to initialize a variable or even declare that it is a String or int or float.

You can declare like this:

```<code>u=set()
u.add("stack")
u.add("overflow")
</code>```

You can also do this:

```<code>u=set(["stack","overflow"])
</code>```

That is a one liner but creates a list first and then creates a set out of it.

This creates a list with the powers of all the numbers from 0-4. You don't need to declare that l is a list and then add stuff in it. You also dont need to declare that x is an int or even initialize it.

```<code>l = [x for x in range(5)]
</code>```

In python you can also do this:

```<code>s="stack"
s=[x for x in "overflow"]
</code>```

See there? i just changed the type of s from string to a list. I can also add different objects in the same list.

```<code>s.append(5)
</code>```

if i were to print s now i would get this:

```<code>['o', 'v', 'e', 'r', 'f', 'l', 'o', 'w', 5]
</code>```

5 is still an integer inside a list of what was only string objects.

I can also do operations with same integer that i cant with the other objects

```<code>print(s[-1:][0]/5)
</code>```

this for example prints 5/5. s[-1:] tells python to return a list of just the last object. On that list i pick [0]  , which is 5 and then i divide it with 5.

if i were to do a forloop, i would get error that i can't use divide operation with string types.

If you were to do something like this:

```<code>u=set()
def pwsdw():
    some code here..
    u.add(x)
</code>```

You would receive error that you didn't initialize the variable.

You can do this however:

```<code>u=set()
def pwsdw():
    global u
    some code
    u.add(x)
</code>```

All in all, python is an extremely flexible language. Have fun.

Body:
I started learning python few days ago and I am trying out different things.

I wrote code as follows:

class ConsumeState:
    token

I got following error for this code

NameError: name 'token' is not defined

So I initialized token to "abc" and the error was gone.

My question is what if I don't want to define the static variable at this point what should I do for that? Is it always necessary to initialize static variable in python?

Body:
Unlike C,Java,C# and so on, in python you don't to initialize a variable or even declare that it is a String or int or float.

You can declare like this:

u=set()
u.add("stack")
u.add("overflow")

You can also do this:

u=set(["stack","overflow"])

That is a one liner but creates a list first and then creates a set out of it.

This creates a list with the powers of all the numbers from 0-4. You don't need to declare that l is a list and then add stuff in it. You also dont need to declare that x is an int or even initialize it.

l = [x for x in range(5)]

In python you can also do this:

s="stack"
s=[x for x in "overflow"]

See there? i just changed the type of s from string to a list. I can also add different objects in the same list.

s.append(5)

if i were to print s now i would get this:

['o', 'v', 'e', 'r', 'f', 'l', 'o', 'w', 5]

5 is still an integer inside a list of what was only string objects.

I can also do operations with same integer that i cant with the other objects

print(s[-1:][0]/5)

this for example prints 5/5. s[-1:] tells python to return a list of just the last object. On that list i pick [0]  , which is 5 and then i divide it with 5.

if i were to do a forloop, i would get error that i can't use divide operation with string types.

If you were to do something like this:

u=set()
def pwsdw():
    some code here..
    u.add(x)

You would receive error that you didn't initialize the variable.

You can do this however:

u=set()
def pwsdw():
    global u
    some code
    u.add(x)

All in all, python is an extremely flexible language. Have fun.


问:
Pass additional object to 3rd-party callback
I am working on screenshot taking script. For taking screenshot I am using html2canvas lib. Thing is when screenshot is eventually taken and onrendered callback is called  I have to do some additional handling and for that purpose I need to be able to get some arguments, which I was using before.

```<code>function onMessageReceived(event){
        ...
    if (dataObj.screenshot)
    {
        takeScreenshot(dataObj);
    }
}
</code>```

Screenshot taking function:

```<code>function takeScreenshot(dataObj) {
    html2canvas($('body'),{
        onrendered: function (canvas) {
            var imgString = canvas.toDataURL("screenshot.png");
            window.open(imgString);
            //do some additional handling here using dataObj
        }
    });
}
</code>```

Is there some good straight-forward solution for it? I mean, without using global vars or saving this dataObj on the disk.

答:
Because of the way scopes in JS work, dataObj is already available in the scope for your takeScreenshot function because you passed it in from the other function. So all you need to do is use it in the callback. Here's how you would alert the value of the screenshot attribute on your dataObj.

```<code>function takeScreenshot(dataObj) {
    html2canvas($('body'),{
        onrendered: function (canvas) {
            var imgString = canvas.toDataURL("screenshot.png");
            window.open(imgString);
            alert(dataObj.screenshot);
        }
    });
}
</code>```

Body:
I am working on screenshot taking script. For taking screenshot I am using html2canvas lib. Thing is when screenshot is eventually taken and onrendered callback is called  I have to do some additional handling and for that purpose I need to be able to get some arguments, which I was using before.

function onMessageReceived(event){
        ...
    if (dataObj.screenshot)
    {
        takeScreenshot(dataObj);
    }
}

Screenshot taking function:

function takeScreenshot(dataObj) {
    html2canvas($('body'),{
        onrendered: function (canvas) {
            var imgString = canvas.toDataURL("screenshot.png");
            window.open(imgString);
            //do some additional handling here using dataObj
        }
    });
}

Is there some good straight-forward solution for it? I mean, without using global vars or saving this dataObj on the disk.

Body:
Because of the way scopes in JS work, dataObj is already available in the scope for your takeScreenshot function because you passed it in from the other function. So all you need to do is use it in the callback. Here's how you would alert the value of the screenshot attribute on your dataObj.

function takeScreenshot(dataObj) {
    html2canvas($('body'),{
        onrendered: function (canvas) {
            var imgString = canvas.toDataURL("screenshot.png");
            window.open(imgString);
            alert(dataObj.screenshot);
        }
    });
}


问:
Ruby on Rails: Many-to-Many Instance
New to rails. I'm creating a project with several database tables all in relation to each other. I would like to know how to add a foreign key reference to an instance after it has been created. Code below:

In schema:

```<code>    class Blog < ActiveRecord::Base
      has_many :posts
      has_many :owners
      has_many :users, through: :owners
    end

    class Owner < ActiveRecord::Base
      belongs_to :user
      belongs_to :blog
    end

    class User < ActiveRecord::Base
       has_many :messages
       has_many :posts
       has_many :owners
       has_many :blogs, through: :owners
    end
</code>```

Models:

```<code>class User < ActiveRecord::Base
   has_many :messages
   has_many :posts
   has_many :owners
   has_many :blogs, through: :owners
end

class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :owners
  has_many :users, through: :owners
end
</code>```

In rails console:

```<code>blog1 = Blog.first
user1 = User.first
blog1.users = user1
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8>
</code>```

答:
Since a Blog has many Users, .users will be a collection (Array or ActiveRecord_Relation).

Try: blog1.users << user1

<< (shovel operator) docs

Title: Ruby on Rails: Many-to-Many Instance

Body:
New to rails. I'm creating a project with several database tables all in relation to each other. I would like to know how to add a foreign key reference to an instance after it has been created. Code below:

In schema:

    class Blog < ActiveRecord::Base
      has_many :posts
      has_many :owners
      has_many :users, through: :owners
    end

    class Owner < ActiveRecord::Base
      belongs_to :user
      belongs_to :blog
    end

    class User < ActiveRecord::Base
       has_many :messages
       has_many :posts
       has_many :owners
       has_many :blogs, through: :owners
    end

Models:

class User < ActiveRecord::Base
   has_many :messages
   has_many :posts
   has_many :owners
   has_many :blogs, through: :owners
end

class Owner < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :owners
  has_many :users, through: :owners
end

In rails console:

blog1 = Blog.first
user1 = User.first
blog1.users = user1
NoMethodError: undefined method `each' for #<User:0x0000000487e9f8>


问:
Why does clicking a link rendered by WP PHP with target="_blank" open in new tab and current tab?
So I know this kind of question has been asked in here, but mine appears to be different from others.

The code below shows that if there is a URL populate it and open it in a new tab, however, for some strange reason the link opens in a new tab (YAY!!) AND opens in the current tab (BOO!!). Why is it opening in both the new tab and the current tab?

I just checked in an incognito window and it happens there also so it doesn't appear to be a cookie issue either.

```<code><div class="box span4">
    <?php if( $url1 != '' && $img1 != '' ): ?>
        <a href="<?php echo esc_url( $url1 ); ?>" target="_blank" class="box-link">
            <center><img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/></center>
        </a>
    <?php else: ?>
        <?php if( $img1 != '' ): ?>
            <a class="box-no-url">
                <center><img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/></center>
            </a>
        <?php endif; ?>
    <?php endif; ?>
    <p><?php echo wp_kses( $text1, array( 'br' => array(), 'em' => array(), 'strong' => array() ) ); ?></p>
</div>
</code>```

To see this code in action please visit http://www.tayloredhomeinspection.com/ and scroll down to the image with the InterNACHI seal in the middle gray box and click on it (or the text below it).

答:
Here is the weave job I did that seems to have it working.

```<code>jQuery(window).load(function(e) {
 if (jQuery(window).width() > 767) {
  setTimeout(function() {
   jQuery("#widget_boxes_container .box").css("height",
jQuery("#widget_boxes_container").height() - 20)
  }, 500)
 }
 jQuery(".boxes .box").each(function() {
  var e = jQuery(this).children(".box-link").attr("href");
  var target = jQuery(this).children(".box-link").attr("target");
  if (target == "_blank") {
      jQuery(this).off("click");
  }
  jQuery(this).hover(function() {
   if (e && e != "") jQuery(this).css("cursor", "pointer")
  }, function() {
   jQuery(this).css("cursor", "default")
  });
  jQuery(this).click(function(event) {
      if (e && e != "") {
          if (target == "_blank") {
              window.open( e, "_blank");
          }
          else {
              window.location = e;
          }
      }
    });
 jQuery(".carousel").carousel("cycle")
})
</code>```

It looks like I have to keep the target="_blank" in the .php file and this should work for any changes I make in the theme and I have the file saved in case of theme updates.

Body:
So I know this kind of question has been asked in here, but mine appears to be different from others.

The code below shows that if there is a URL populate it and open it in a new tab, however, for some strange reason the link opens in a new tab (YAY!!) AND opens in the current tab (BOO!!). Why is it opening in both the new tab and the current tab?

I just checked in an incognito window and it happens there also so it doesn't appear to be a cookie issue either.

    <?php if( $url1 != '' && $img1 != '' ): ?>
        <a href="<?php echo esc_url( $url1 ); ?>" target="_blank" class="box-link">
            <img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/>

    <?php else: ?>
        <?php if( $img1 != '' ): ?>

                <img class="box-image" src="<?php echo esc_url( $img1 ); ?>"/>

        <?php endif; ?>
    <?php endif; ?>

<?php echo wp_kses( $text1, array( 'br' => array(), 'em' => array(), 'strong' => array() ) ); ?>

To see this code in action please visit http://www.tayloredhomeinspection.com/ and scroll down to the image with the InterNACHI seal in the middle gray box and click on it (or the text below it).

Body:
Here is the weave job I did that seems to have it working.

jQuery(window).load(function(e) {
 if (jQuery(window).width() > 767) {
  setTimeout(function() {
   jQuery("#widget_boxes_container .box").css("height",
jQuery("#widget_boxes_container").height() - 20)
  }, 500)
 }
 jQuery(".boxes .box").each(function() {
  var e = jQuery(this).children(".box-link").attr("href");
  var target = jQuery(this).children(".box-link").attr("target");
  if (target == "_blank") {
      jQuery(this).off("click");
  }
  jQuery(this).hover(function() {
   if (e && e != "") jQuery(this).css("cursor", "pointer")
  }, function() {
   jQuery(this).css("cursor", "default")
  });
  jQuery(this).click(function(event) {
      if (e && e != "") {
          if (target == "_blank") {
              window.open( e, "_blank");
          }
          else {
              window.location = e;
          }
      }
    });
 jQuery(".carousel").carousel("cycle")
})

It looks like I have to keep the target="_blank" in the .php file and this should work for any changes I make in the theme and I have the file saved in case of theme updates.


问:
bash no parameters for $(function parameters)
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters

```<code>function promp() {
    echo $*
    read response
    echo $response
}
function confirm() {
    echo $*
    read -rp $'(y/N) : ' -ei $'N' key;
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE
</code>```

Expected:

```<code>SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text
</code>```

Obtained:

```<code>(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text
</code>```

I know the problem is the echo within the function is part of the variable data, but I want to get this printed.

How can I do this or which is the best way to do this

答:
Global variables are used more commonly in shell scripts than other languages; if your code is getting too complicated to easily manage global variables, it is probably time to switch to another language anyway.</p>

```<code># This is probably too trivial to even define as a function.
promp() {
    read -p "$1" "$2"
}

confirm() {
    printf '%s\n' "$1" >&2
    read -rp $'(y/N) : ' -ei N key
    case "$key" in
        [yY][eE][sS]|[yY])
            key=true
            ;;
        *)
            key=false
            ;;
    esac
    printf -v "$2" "$key"
}

# No expensive command substitutions needed;
# read and printf -v will both populate a global variable
# named by an argument.
confirm "SOME QUESTION" IS_RESPONSE
promp "WRITE SOMETHING" STRING_RESPONSE
echo "$IS_RESPONSE"
echo "$STRING_RESPONSE"
</code>```

Body:
I want to create a script that use basic (prompt and confirm) functions multiple times, when I try to set the return to any variable the function ignore the parameters

function promp() {
    echo $*
    read response
    echo $response
}
function confirm() {
    echo $*
    read -rp $'(y/N) : ' -ei $'N' key;
    case "$key" in
        [yY][eE][sS]|[yY])
            echo true
            ;;
        *)
            echo false
            ;;
    esac
}

IS_RESPONSE=$(confirm "SOME QUESTION")
STRING_RESPONSE=$(promp "WRITE SOMETHING")
echo $IS_RESPONSE
echo $STRING_RESPONSE

Expected:

SOME QUESTION
(y/N) : N
WRITE SOMETHING
#<< "some text"
false
some text

Obtained:

(y/N) : N
#<< "some text"
SOME QUESTION false
WRITE SOMETHING some text

I know the problem is the echo within the function is part of the variable data, but I want to get this printed.

How can I do this or which is the best way to do this

Body:
Global variables are used more commonly in shell scripts than other languages; if your code is getting too complicated to easily manage global variables, it is probably time to switch to another language anyway.

# This is probably too trivial to even define as a function.
promp() {
    read -p "$1" "$2"
}

confirm() {
    printf '%s\n' "$1" >&2
    read -rp $'(y/N) : ' -ei N key
    case "$key" in
        [yY][eE][sS]|[yY])
            key=true
            ;;
        *)
            key=false
            ;;
    esac
    printf -v "$2" "$key"
}

# No expensive command substitutions needed;
# read and printf -v will both populate a global variable
# named by an argument.
confirm "SOME QUESTION" IS_RESPONSE
promp "WRITE SOMETHING" STRING_RESPONSE
echo "$IS_RESPONSE"
echo "$STRING_RESPONSE"


问:
Malware detected after compiling with Inno Setup
I've created an installer by using Inno Setup.
Inside of this installer there are 2 executable files with my app (32 and 64 version).

When I try to upload the file to hosting server it says that contain a malware: Win.Adware.Eorezo-356

I scan this installer with VirusTotal.com and one of the antivirus says the same.

See the report: https://www.virustotal.com/en/file/601671b2466d0b46d5ab4fc598a5f5d864a81e49d9ae11b6ed8a3aef2d427d2c/analysis/1445309382/

I test on Virus Total separately both executable files and the sqlite database file that I add inside installer and all of them are fully clean.

Inno setup .iss script doesn't have something special inside, just normal things.

I compiled the installer on 2 computers and on both i get an installer with malware.

Remarks:
- I used the latest stable release version from Inno Setup
- I compiled the installer on a Win 7 and Win Xp

How can I get this malware off?

答: For this case, I just installed the previous version and it works. In this case the latest version was reported by ClamAV as virus, which was just a false positive. I reported this to ClamAV but no response.</p>


问:
Odd problem with jQuery .change() event
I have the following select element with an onchange event.

```<code><select name="ftest" onchange="alert('test');">
  <option value="0"></option>
  <option value="test">test</option>
</select>
</code>```

I later bind another event on all the select elements in the page using jQuery (1.4.4).

```<code>   $("SELECT").change(function(){
    _isDirty = true;
   });
</code>```

The result is my alert showing up twice when I change the value of my select list.

Anyone has an idea why this is happening or have a way to fix this?

Thanks

答: I believe, that jQuery adds handlers, not replaces them. So for the above, you'd get one for your onchange attribute in the SELECT element, and another for the addition that jQuery makes.</p>

Title: Odd problem with jQuery .change() event

Body:
I have the following select element with an onchange event.

<select name="ftest" onchange="alert('test');">
  <option value="0"></option>
  <option value="test">test</option>
</select>

I later bind another event on all the select elements in the page using jQuery (1.4.4).

   $("SELECT").change(function(){
    _isDirty = true;
   });

The result is my alert showing up twice when I change the value of my select list.

Anyone has an idea why this is happening or have a way to fix this?

Thanks


问:
SQL find partial duplicates in table
I have a table with partial duplicate values in one of the column and that is the primary key on the table. I tried to write a query to find those duplicates and couldn't figure it out.
Ex:

```<code>Taxi(Number, id) - Number is primary key on the table
Values(123, 253)
Values(123-, 253)
Values(1 23,253)
</code>```

These all are treated as duplicates according to the requirements.
This is the query I tried with no luck

```<code>select * from taxi t where exists(
select 1 from taxi t2
where t1.id = t2.id
and t2.number like t1.number||'%')
</code>```

This is giving me all the values back. Any help is appreciated

答:
Perhaps translate() will do what you want:

```<code>select translate(number, '0- ', '0') as fixed_number
</code>```

All the characters after 0 in the first string will be removed.

So, if you want the duplicates:

```<code>select t.*
from (select translate(number, '0- , '0') as fixed_number, t.*,
             count(*) over (partition by translate(number, '0- ', '0')) as cnt
      from t
     ) t
where cnt > 1
order by fixed_number;
</code>```

Title: SQL find partial duplicates in table

Body:
I have a table with partial duplicate values in one of the column and that is the primary key on the table. I tried to write a query to find those duplicates and couldn't figure it out.
Ex:

Taxi(Number, id) - Number is primary key on the table
Values(123, 253)
Values(123-, 253)
Values(1 23,253)

These all are treated as duplicates according to the requirements.
This is the query I tried with no luck

select * from taxi t where exists(
select 1 from taxi t2
where t1.id = t2.id
and t2.number like t1.number||'%')

This is giving me all the values back. Any help is appreciated

Body:
Perhaps translate() will do what you want:

select translate(number, '0- ', '0') as fixed_number

All the characters after 0 in the first string will be removed.

So, if you want the duplicates:

select t.*
from (select translate(number, '0- , '0') as fixed_number, t.*,
             count(*) over (partition by translate(number, '0- ', '0')) as cnt
      from t
     ) t
where cnt > 1
order by fixed_number;


问:
singelton object in sync adapter class
I need help regarding the explanation of

why do we use a singleton object in sync adapter service class

```<code>private static SyncAdapter sSyncAdapter = null;
private static final Object sSyncAdapterLock = new Object();

    @Override
    public void onCreate() {
        synchronized (sSyncAdapterLock) {
            if (sSyncAdapter == null) {
                sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
            }
        }
    }
</code>```

答:
Because the Framework is build in the way to work with only one SyncAdapter:

The sync adapter framework is designed to work with sync adapter components that are singleton instances.

You can have multiple component triggering the SyncAdapter to send some data. But you only want to create ONE SyncAdapter to manage all the calls. Therefore you create the SynAdapter with the singleton-pattern.

Title: singelton object in sync adapter class

Body:
I need help regarding the explanation of

why do we use a singleton object in sync adapter service class

private static SyncAdapter sSyncAdapter = null;
private static final Object sSyncAdapterLock = new Object();

    @Override
    public void onCreate() {
        synchronized (sSyncAdapterLock) {
            if (sSyncAdapter == null) {
                sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
            }
        }
    }


问:
Matching an NSString and a UILabel's text
I am comparing a word entered by the user to a secret word. My if statement testing whether the correct word is equal to the guessed word won't work.

```<code>@property (weak, nonatomic) IBOutlet UILabel *guesslet; //the guessed letter
@property (weak, nonatomic) IBOutlet UILabel *Word;  //the ongoing guessed word
@property (weak, nonatomic) NSString *wrand;  //the correct word
@property (weak, nonatomic) NSString *letterguess;
- (IBAction)GuessButton;   //the button to guess the word

- (IBAction)GuessButton
{
  letterguess = guesslet.text;
  bool match = NO;
  char charInput = [guesslet.text characterAtIndex: 0];
  for(NSInteger i = 0; i < wrand.length; i++)
  {
    char tempChar = [wrand characterAtIndex: i];
    if (charInput == tempChar)
    {
      match = YES;
      NSRange InputRange = NSMakeRange(i, 1); //location, length
     Word.text = [Word.text stringByReplacingCharactersInRange:
     InputRange withString: letterguess];
    }
    if(Word.text == randword)
    {
      UIAlertController *alert = [UIAlertController
      alertControllerWithTitle:@”Winner!!”
      message:@”Great Job! You won!”
      preferredStyle:UIAlertControllerStyleAlert];
      UIAlertAction *okAction = [UIAlertAction
      actionWithTitle:@”Ok”
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      UIAlertAction *cancelAction = [UIAlertAction
      actionWithTitle:@”Cancel”;
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      [alert addAction:okAction];
      [alert addAction:cancelAction];
      [self presentViewController:alert animated: YES completion:nil];

    }
}

if(match == NO)
</code>```

What am I doing wrong?

答:
Using == to compare will do a pointer (or reference) comparison, if you want to compare the actual NSString's you will want to use something like</p>

```<code>if([Word.text isEqualToString:randword]) {

}
</code>```

Body:
I am comparing a word entered by the user to a secret word. My if statement testing whether the correct word is equal to the guessed word won't work.

@property (weak, nonatomic) IBOutlet UILabel *guesslet; //the guessed letter
@property (weak, nonatomic) IBOutlet UILabel *Word;  //the ongoing guessed word
@property (weak, nonatomic) NSString *wrand;  //the correct word
@property (weak, nonatomic) NSString *letterguess;
- (IBAction)GuessButton;   //the button to guess the word

- (IBAction)GuessButton
{
  letterguess = guesslet.text;
  bool match = NO;
  char charInput = [guesslet.text characterAtIndex: 0];
  for(NSInteger i = 0; i < wrand.length; i++)
  {
    char tempChar = [wrand characterAtIndex: i];
    if (charInput == tempChar)
    {
      match = YES;
      NSRange InputRange = NSMakeRange(i, 1); //location, length
     Word.text = [Word.text stringByReplacingCharactersInRange:
     InputRange withString: letterguess];
    }
    if(Word.text == randword)
    {
      UIAlertController *alert = [UIAlertController
      alertControllerWithTitle:@”Winner!!”
      message:@”Great Job! You won!”
      preferredStyle:UIAlertControllerStyleAlert];
      UIAlertAction *okAction = [UIAlertAction
      actionWithTitle:@”Ok”
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      UIAlertAction *cancelAction = [UIAlertAction
      actionWithTitle:@”Cancel”;
      style: UIAlertActionStyleDefault
      handler:^(UIAlertAction * action){
      }];
      [alert addAction:okAction];
      [alert addAction:cancelAction];
      [self presentViewController:alert animated: YES completion:nil];

    }
}

if(match == NO)

What am I doing wrong?

Body:
Using == to compare will do a pointer (or reference) comparison, if you want to compare the actual NSString's you will want to use something like

if([Word.text isEqualToString:randword]) {

}


问:
Swift: How to get substring from start to last index of character
I want to learn the best/simplest way to turn a string into another string but with only a subset, starting at the beginning and going to the last index of a character.

For example, convert "www.stackoverflow.com" to "www.stackoverflow".  What code snippet would do that, and being the most swift-like? (I hope this doesn't bring a debate, but I can't find good lesson on how to handle substrings in Swift.

答:
Here is a simple way to get substring in Swift</p>

```<code>import UIKit

var str = "Hello, playground"
var res = NSString(string: str)
print(res.substring(from: 4))
print(res.substring(to: 10))
</code>```

Body:
Here is a simple way to get substring in Swift

import UIKit

var str = "Hello, playground"
var res = NSString(string: str)
print(res.substring(from: 4))
print(res.substring(to: 10))


问:
Missing characters in filled pdf using PDFTk with encoding UTF-8
I'm trying to fill pdf documents using PDFTk. Script working fine, it fills inputs in form but I don't get special characters [polish charset: UTF-8 or ISO-8859-2].

Script: https://github.com/mikehaertl/php-pdftk

The weird thing is that generated pdf actually has polish characters when I click on field.

Before click:

After click on field:

Default encoding is set to UTF-8. The problem is that PDFTk can't use chars outside the standard ASCII with FDF form fill. It doesn't allow multi-byte characters.

What I did:

Add fonts to pdf files (checked and files has font)

Create fields in pdf files with default font (Arial)

Change encoding in script (function fillForm) to ISO-8859-2

Change data values encoding (iconv or mb_convert_encoding)

Change functions encoding and data value encoding to ISO-8859-2

Flatten pdf after filling the form

Read all topics about this problem in stackoverflow, google

UPDATE (25.03.2016): Findout that pdf documents works fine on some computers. Some people have polish characters and other don't. All of
  us have right fonts (with polish charset). I used default Arial or
  Times New Roman. Fonts are also embed in that file.

Any ideas?

答:
you need to run pdftk with need_appearances as an argument.

kudos to the guys from this issue on github.


问:
Dynamic_cast compatibility?
I was reading about dynamic_cast and then I encountered the following statement (from cplusplus.com):

Compatibility note: This type of dynamic_cast requires Run-Time Type
  Information (RTTI) to keep track of dynamic types. Some compilers
  support this feature as an option which is disabled by default. This
  needs to be enabled for runtime type checking using dynamic_cast to
  work properly with these types.

After the example:

```<code>// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {} };
class Derived: public Base { int a; };

int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;

    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.\n";

    pd = dynamic_cast<Derived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast.\n";

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}
</code>```

What does the author mean by "this type of dynamic_cast"? Isn't dynamic_cast only used for polymorphic classes(almost)? And he mentions this RTTI as something that is needed for the dynamic cast to work, does that mean that you have to use dynamic_cast with caution because you do not know if it is supported fully by the compiler and therefore makes it riskier than the other casting operators which do not need this RTTI?

答:
rtti is expensive at runtime and some embedded systems compile with flags, disabling it. All it gives you are dynamic_cast and typeid.

Therefore, I interpret

because you do not know if it is supported fully by the compiler

as

because your code could have been compiled with rtti disabled.

Title: Dynamic_cast compatibility?

Body:
I was reading about dynamic_cast and then I encountered the following statement (from cplusplus.com):

Compatibility note: This type of dynamic_cast requires Run-Time Type
  Information (RTTI) to keep track of dynamic types. Some compilers
  support this feature as an option which is disabled by default. This
  needs to be enabled for runtime type checking using dynamic_cast to
  work properly with these types.

After the example:

// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;

class Base { virtual void dummy() {} };
class Derived: public Base { int a; };

int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;

    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.\n";

    pd = dynamic_cast<Derived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast.\n";

  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}

What does the author mean by "this type of dynamic_cast"? Isn't dynamic_cast only used for polymorphic classes(almost)? And he mentions this RTTI as something that is needed for the dynamic cast to work, does that mean that you have to use dynamic_cast with caution because you do not know if it is supported fully by the compiler and therefore makes it riskier than the other casting operators which do not need this RTTI?


问:
Calling external API from dropwizard
I'm pretty new to Dropwizard and learning it (and API development in general).

I'm looking at Dropwizard to build an API which should call another API at somepoint.

More precisely, I have a json/yaml file which I'll convert it another json file consumable by an external API.

The API I'm building includes the whole process

For now I'm focusing on the last part: calling external API (with a fixed json).so how can I hit an external API from within Dropwizard?

Here's the sudo code:

```<code>@Path("/my_api")
public class HelloResource {

@GET
@Produces(MediaType.APPLICATION_JSON)
public hit_external() {
    // call "my.external.api/ext_api"

}
}
</code>```

Any comments/suggestions/link to references is really appreciated.

答:
You can use the Dropwizard Client module, which relies on the Apache HttpClient (default) or the Jersey Client. Once the client is configured in the DW application just use that to make the external calls. For an higher-level abstraction Feign is a good option.

Be aware that when making synchronous calls to an external web service the application might run out of available threads if those are waiting on the other service. You should make this calls asynchronous if possible for example using a queue of external calls to be processed and having the clients of the API to check the status of that request.

Title: Calling external API from dropwizard

Body:
I'm pretty new to Dropwizard and learning it (and API development in general).

I'm looking at Dropwizard to build an API which should call another API at somepoint.

More precisely, I have a json/yaml file which I'll convert it another json file consumable by an external API.

The API I'm building includes the whole process

For now I'm focusing on the last part: calling external API (with a fixed json).so how can I hit an external API from within Dropwizard?

Here's the sudo code:

@Path("/my_api")
public class HelloResource {

@GET
@Produces(MediaType.APPLICATION_JSON)
public hit_external() {
    // call "my.external.api/ext_api"

}
}

Any comments/suggestions/link to references is really appreciated.