问:
String comparison with different COLLATION
MYSQL databases

Database1 - table - table1

id - int

title - utf8_general_ci

values -

1, Bienvenue Chez les Châ€™tis

2, ABC

3, XYZ

Database2 - table - table2

id - int

title - utf8_unicode_ci

values -

1, Bienvenue Chez les Ch’tis

2, ABC

3, QWE

I have list of titles in both the tables as above.I want to list titles which are not same.

I tries so many different things but no luck.

How can I compare these titles?

```<code>SELECT database1.table1.title as title1,database2.table2.title as title2
FROM database1.table1 JOIN database2.table2 ON (database1.table1.id =database2.table2)
WHERE database1.table1.title NOT LIKE database2.table2.title COLLATE utf8_general_ci
</code>```

result from above query:

Bienvenue Chez les Châ€™tis, Bienvenue Chez les Ch’tis

XYZ, QWE

But I just want below in result

XYZ, QWE

I want to exclude french one, I want to consider it as a identical titles.

答:
â€™ is Mojibake for ’.  The problem came when storing the same right-single-quote in two different ways.  Not a COLLATION issue.

First, check the two tables to see what got stored:

```<code>SELECT HEX(title) FROM database1.table1 WHERE id = 1
</code>```

Two likely cases of what you will find are these:

```<code>C  h          ...        t  i  s
43 68        E28099      74 69 73  -- correctly encoded with UTF-8
43 68 C3A2 E282AC E284A2 74 69 73  -- "double encoded"
</code>```

(I added spacing to the HEX for clarity.)

If one of the tables is "doubly encoded", then it got messed up during INSERTing.  The strings will not compare equal.

This Q&A discusses things further.  Then see this for fixing the doubly encoded text.  But be sure to apply it only to the broken data.

Body:
MYSQL databases

Database1 - table - table1

id - int

title - utf8_general_ci

values -

1, Bienvenue Chez les Châ€™tis

2, ABC

3, XYZ

Database2 - table - table2

id - int

title - utf8_unicode_ci

values -

1, Bienvenue Chez les Ch’tis

2, ABC

3, QWE

I have list of titles in both the tables as above.I want to list titles which are not same.

I tries so many different things but no luck.

How can I compare these titles?

SELECT database1.table1.title as title1,database2.table2.title as title2
FROM database1.table1 JOIN database2.table2 ON (database1.table1.id =database2.table2)
WHERE database1.table1.title NOT LIKE database2.table2.title COLLATE utf8_general_ci

result from above query:

Bienvenue Chez les Châ€™tis, Bienvenue Chez les Ch’tis

XYZ, QWE

But I just want below in result

XYZ, QWE

I want to exclude french one, I want to consider it as a identical titles.

Body:
â€™ is Mojibake for ’.  The problem came when storing the same right-single-quote in two different ways.  Not a COLLATION issue.

First, check the two tables to see what got stored:

SELECT HEX(title) FROM database1.table1 WHERE id = 1

Two likely cases of what you will find are these:

C  h          ...        t  i  s
43 68        E28099      74 69 73  -- correctly encoded with UTF-8
43 68 C3A2 E282AC E284A2 74 69 73  -- "double encoded"

(I added spacing to the HEX for clarity.)

If one of the tables is "doubly encoded", then it got messed up during INSERTing.  The strings will not compare equal.

This Q&A discusses things further.  Then see this for fixing the doubly encoded text.  But be sure to apply it only to the broken data.


来源: stackexchange

问:
Program throws 'Access-Control-Allow-Origin' header in JavaScript? Works in Postman, not through browser
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

```<code>alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `<tr id="Article-${Article.Id}"><td>${Article.Title}</td>
                <td>${Article.Authors}</td>
                <td>${Article.Genre}</td>
</code>```

Due to popular demand, this is the server-side code:

```<code>package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}
</code>```

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

```<code>  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List<Article> findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}
</code>```

THIS IS NOT SOLVED YET

答:
Basically what it says is that your service at
http://localhost:8080/articles/addArticle.
should add a header 'Access-Control-Allow-Origin' that the browser can read.

I ran to similar scenario when I was making a REST API, but instead of installing cors (which its version conflicts with our production server build), I just added that header when sending out responses to the request client.

response.AddHeader("Access-Control-Allow-Origin", "*");

If you are using asp.net, then you can either put that code in the Global.asax under:

```<code>protected void Application_BeginRequest(Object sender, EventArgs e) {
    var context = HttpContext.Current;
    var response = context.Response;
    response.AddHeader("Access-Control-Allow-Origin", "*");
}
</code>```

If you are using java/servlet/jsp then it's quite similar as you already have access to HttpServletResponse response so in your code body, just do:

```<code>public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");

    //other codes and stuff here...
}
</code>```

from your code on the other hand which uses spring, you could do something like:

```<code>@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Solved

I have been working on this program since 07:00. This has been driving me crazy. I have written multiple full stack web apps and have not had this problem.

Basically I have a form in html that allows a user to input data. Whenever the submit button is clicked, it sends that data to a collection in mongoDB. I have tested this in postman and it works. However, when I run the program through a webbrowser, I get this error:

XMLHttpRequest cannot load http://localhost:8080/articles/addArticle. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

I tried installing CORS and configuring the endpoint

I tried going into the javascript file and changing the

This is my JavaScript file

alert('JS is linked to page!');

function Article(id = 1, title = "", authors="", content = "", genre = "", date = 1497484623) {
    console.log("JavaScript file loaded successfully");
    var self = this;
    self.Id = id;
    self.Title = title;
    self.Authors = authors;
    self.Content = content;
    self.Genre = genre;
    self.Date = date;
    self.Save = function() {
        var settings = {
            url: 'http://localhost:8080/articles/addArticle',
            method: 'POST',
            dataType: "json",
              beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
        };
        var myData = {
            "Id" : self.Id,
            "Title": self.Title,
            "Authors": self.Authors,
            "Content": self.Content,
            "Genre": self.Genre,
            "Date": self.Date
        };
        settings.data = myData;

        $.ajax(settings).done(function(article) {
         var myArticle = new Article(article.Id, article.Title, article.Authors,
                article.Content, article.Genre, article.Date);
        });
    };
}

function addArticle(Article) {
    alert('addArticle Activated');
    var settings = {
        url: 'http://localhost:8080/articles/addArticle',
        method: 'POST',
        dataType: "json",
          beforeSend: function (xhr) {
                xhr.setRequestHeader("Accept", "application/json");
            }
    };
    var myData = {
        "Title": Article.Title,
        "Authors" : Article.Authors,
        "Content": Article.Content,
        "Genre" : Article.Genre,
        "Date": Article.Date
    };
    settings.data = myData;

    $.ajax(settings).done(function(Article) {
        var myArticle = new Article(article.Id, article.Title, article.Authors, article.Content,
            article.Genre, article.Date);
        console.log("Article Created");
    });
}

$(document).ready(function() {

    $(document).on("submit", "#add-article", function(e) {
        e.preventDefault();
            alert('submit Activated');
        var title, authors, genre, content;
        title = $("#Title").val();
        director = $("#Authors").val();
        rating = $("#Genre").val();
        notes = $("#Content").val();
        var myArticle = new Article(0, title, authors, genre, content, 1497484623);
        alert(myArticle.Title);
        addArticle(myArticle);
        $("#add-article")[0].reset();
        $("#title").focus();

    });

});

/*function CreateSuccessRow(Article) {
    var successDataRow = `
${Article.Title}
                ${Article.Authors}
                ${Article.Genre}

Due to popular demand, this is the server-side code:

package com.stereoscopics.app.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.stereoscopics.app.models.Article;
import com.stereoscopics.app.repo.ArticleRepo;

@RestController
@RequestMapping("/articles")
public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle) {
    articleRepo.save(newArticle);
    return newArticle;
}

}

I have no idea how to fix this. Please help.

UPDATE

This still isn't working. I've updated the code as per some suggestions and I'm either doing it wrong or it's incorrect. The changes are shown below:

  @RestController
  @RequestMapping("/articles")
  public class ArticleController {

private ArticleRepo articleRepo;

@Autowired
public ArticleController(ArticleRepo articleRepo) {
    this.articleRepo = articleRepo;
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
}

@RequestMapping(value = "/findall", method = RequestMethod.GET)
@ResponseBody
public List
 findall() {
    return articleRepo.findAll();
}

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final
HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
  }
}

THIS IS NOT SOLVED YET

Body:
Basically what it says is that your service at
http://localhost:8080/articles/addArticle.
should add a header 'Access-Control-Allow-Origin' that the browser can read.

I ran to similar scenario when I was making a REST API, but instead of installing cors (which its version conflicts with our production server build), I just added that header when sending out responses to the request client.

response.AddHeader("Access-Control-Allow-Origin", "*");

If you are using asp.net, then you can either put that code in the Global.asax under:

protected void Application_BeginRequest(Object sender, EventArgs e) {
    var context = HttpContext.Current;
    var response = context.Response;
    response.AddHeader("Access-Control-Allow-Origin", "*");
}

If you are using java/servlet/jsp then it's quite similar as you already have access to HttpServletResponse response so in your code body, just do:

public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");

    //other codes and stuff here...
}

from your code on the other hand which uses spring, you could do something like:

@RequestMapping(value = "/addArticle", method = RequestMethod.POST)
@ResponseBody
public Article addArticle(@RequestBody Article newArticle, final HttpServletResponse response) {
    response.addHeader("Access-Control-Allow-Origin", "*");
    articleRepo.save(newArticle);
    return newArticle;
}


问:
How to compare day of the week with actual date in moment js?
I'm relatively new to moment js. And I have a problem with the concept of time manipulation and comparison in moment JS. What I want to do is compare times of 2 events.

First event is an actual event, like work hours. This has a start and end time.

Second event is a re-occurring event, like overtime hours for a company. This also has a start time and end time, but the days may vary.

For example: from Monday 11:00PM to Tuesday 7:00AM is considered "overtime". But I worked from Monday 9:00PM to Tuesday 6:00AM.

How would i go about comparing these times? I need to compare them and separate the "overtime hours" from the "normal hours" and use these later.

答:
Moment offers getter and setter methods to access certain parameters for comparison. Here is a basic approach to check if overhours and events happen on the same day of the week:</p>

```<code>if (moment(overhourDate).weekday() === moment(eventDate).weekday()) {
    whatever();
}
</code>```

Body:
Moment offers getter and setter methods to access certain parameters for comparison. Here is a basic approach to check if overhours and events happen on the same day of the week:

if (moment(overhourDate).weekday() === moment(eventDate).weekday()) {
    whatever();
}


问:
Creation of PDF file using itextSharp
Hi
 I am creating an ASP.net website where some articles can be uploaded. I need that my users can get PDF version of it by clicking on a button. For this functionality I am using itextSharp.
    I am considering the following two options.
1. I will create the PDF file once(on first request) and reuse it always by checking for the existence of it.
2. I will create it on the fly and delete it as soon as the PDF file is delivered to the client.
The first approach will lead to faster PDF delivery where as the second approach will lead to saving space. Can anyone please tell me which of the options is better?

I am also wondering if this can be possible without saving the PDF on the server in the first place. So can anyone reply me as soon as possible.

Thanks
Dipa

答:
Actually its totally depends on application requirement.Like in my application I don't need to save pdf file on server so after pdf file delivered to client side i delete it from the server.
So in your case if particular user access particular pdf file multiple times then you have to save it on the server,it would save your pdf generation time.</p>

ContentLicense: CC BY-SA 2.5

Title: Creation of PDF file using itextSharp


问:
How can I select * WHERE & receive other results connected to the found primary keys?
So I've got the following tables setup:

thread:

id

created_at

thread_users:

id

thread_id -> FK thread

user_id -> FK users (the user who is in the thread)

joined_at

users:

id

name

etc...other relevant details for user

Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.

Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID

It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ] - This represents the thread_id 6)

```<code>const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');
</code>```

From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)

```<code>Object.keys(groupedThreads).forEach((key) => {
      const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
      console.log(thr, 'FOUND THREAD inside loop after filter');
      /**
       * @TODO add something here which will take into account pluralbot
       */
      if (thr.length === 2) {
        foundThread = thr[0];
      }
    });
</code>```

However, this bit of logic doesn't work:

```<code>if (thr.length === 2) {
   foundThread = thr[0];
}
</code>```

Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.

I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?

答:
Okay so what I ended up doing was adding a new field to the thread table named: thread_name. The thread name consists of the 2 user ids joined together, e.g: 445-123. The reason for this is so I can easily query for a thread between 2 users! I'm not sure if I will do this for group messages though (we will see when the time comes).

Example usage:

```<code>const name = [http_req_userId, otherUserId].sort().join('-'); // Returns something like 123-323
select * from threads where thread_name = name;
</code>```

Note that I'm sorting the 2 IDS before joining them together so I don't create duplicate threads between users.

I got the idea for this off this SO question (see comments of below answer): thread messaging system database schema design

EDIT

Do not use this approach - I will leave this here as a reference for what NOT to do.

Body:
So I've got the following tables setup:

thread:

id

created_at

thread_users:

id

thread_id -> FK thread

user_id -> FK users (the user who is in the thread)

joined_at

users:

id

name

etc...other relevant details for user

Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.

Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID

It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ] - This represents the thread_id 6)

const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');

From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)

Object.keys(groupedThreads).forEach((key) => {
      const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
      console.log(thr, 'FOUND THREAD inside loop after filter');
      /**
       * @TODO add something here which will take into account pluralbot
       */
      if (thr.length === 2) {
        foundThread = thr[0];
      }
    });

However, this bit of logic doesn't work:

if (thr.length === 2) {
   foundThread = thr[0];
}

Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.

I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?

Body:
Okay so what I ended up doing was adding a new field to the thread table named: thread_name. The thread name consists of the 2 user ids joined together, e.g: 445-123. The reason for this is so I can easily query for a thread between 2 users! I'm not sure if I will do this for group messages though (we will see when the time comes).

Example usage:

const name = [http_req_userId, otherUserId].sort().join('-'); // Returns something like 123-323
select * from threads where thread_name = name;

Note that I'm sorting the 2 IDS before joining them together so I don't create duplicate threads between users.

I got the idea for this off this SO question (see comments of below answer): thread messaging system database schema design

EDIT

Do not use this approach - I will leave this here as a reference for what NOT to do.


问:
jQuery addClass is not working now
So I'm trying to add a class with jquery.
Here is the code:

```<code>jQuery(document).ready(function($) {
    $('body').addClass('scrollbar-dynamic');
});
</code>```

I can confirm the script is loaded on frontend as it appears in source code.
Plus all other javascript "1400 lines" works fine.
The addClass jquery method is also used about 30 more times throughout the script.
I'm also using the latest version of wordpress
It's just this time it's not working.
Here is a working js fiddle

Stuff like this just drives me crazy.
Cheers for the help

答:
Ok - since console.log(jQuery) is returning what we'd expect, I think the issue is with how the library is being referenced. Here's your code:

```<code>jQuery(document).ready(function($) {
  $('body').addClass('scrollbar-dynamic');
});
</code>```

The script knows what jQuery is...but it doesn't seem to know what $ is, and it's not being bound to anything when it's called.

Try this - if it works, it's a binding issue.

```<code>jQuery(document).ready(function($) {
  jQuery('body').addClass('scrollbar-dynamic');
});
</code>```

Title: jQuery addClass is not working now

Body:
So I'm trying to add a class with jquery.
Here is the code:

jQuery(document).ready(function($) {
    $('body').addClass('scrollbar-dynamic');
});

I can confirm the script is loaded on frontend as it appears in source code.
Plus all other javascript "1400 lines" works fine.
The addClass jquery method is also used about 30 more times throughout the script.
I'm also using the latest version of wordpress
It's just this time it's not working.
Here is a working js fiddle

Stuff like this just drives me crazy.
Cheers for the help

Body:
Ok - since console.log(jQuery) is returning what we'd expect, I think the issue is with how the library is being referenced. Here's your code:

jQuery(document).ready(function($) {
  $('body').addClass('scrollbar-dynamic');
});

The script knows what jQuery is...but it doesn't seem to know what $ is, and it's not being bound to anything when it's called.

Try this - if it works, it's a binding issue.

jQuery(document).ready(function($) {
  jQuery('body').addClass('scrollbar-dynamic');
});


问:
Google Visually Similar Image API
I know there is this link to find visually similar images to an uploaded picture
https://www.google.com/searchbyimage?site=search&sa=X&image_url=YOUR_IMAGE_URL

but is there also a way to get an API for the first result of the visually similiar image?

答:
I have sympathy what you need.

I try to use google cse but this is not supported similar images.

So, Next that I try, URL.

But this is able to on the browser.

I just need result of simliar images and then I wish that result is visually.

So,
you can use Vision API of Google.
This is very simple.

https://cloud.google.com/vision/

Title: Google Visually Similar Image API


问:
What are the different calling conventions in C/C++ and what do each mean?
There are different calling conventions available in C/C++: stdcall, extern, pascal, etc. How many such calling conventions are available, and what do each mean? Are there any links that describe these?

答:
They’re platform-specific extensions needed to call functions in certain libraries, particularly the Win32 API. They’re nonstandard and specific to each compiler, although MSVC’s options are the de facto standard for Windows on x86. Normally, a library that needs them will declare them in the header files and they will work transparently.  The main difference between them is that C historically used a less-efficient convention that allowed for a variable number of arguments of any type, while Windows and most other languages did it differently.  A lot of the differences, though, such as pushing left-handed or right-handed and having the caller or the called function clean up, were pretty arbitrary.

They’re largely irrelevant to 64-bit code: the holy wars over calling conventions never happened on those platforms.

There are a few common cases where you might need to add one of these to a function.  A C++ module that needs to link with modules written in other languages (and sometimes even other C++ compilers) will have to use the extern "C" naming convention for compatibility.  A callback function needs to use the same calling convention as the caller, which with the Windows API is CALLBACK, not the default.  A shared library might need to export its functions with a different calling convention than it uses internally, or might want to make its use of __cdecl explicit in case the default changes.  You might or might not get better performance from __fastcall on some platforms: it mostly speeds up short leaf functions with one or two parameters, and could make some programs slower.


问:
LOAD CSV and Commits: Conditional (FOREACH/CASE) Execution Behaving Oddly
I'm using Neo4j version 3.1, running what I thought would be a quite straightforward import, but have run into very significant problems. I'm importing data about pubs (for non-UK users, public houses - places where you have a pint and relax!). A (pl:PubListing) has been commented on by a (u:BiteUser), creating a (bc:BiteComment). I've got two CSV files, and have already imported the (pl:PubListing) nodes, so am trying to import the comments linked to each pub (on pl.source_pub_id) and to each user (on u.username). Importantly, I'd like to add them both as a simple relationship, and as what - for want of a better word - I term a chain.

In this way, the last two comments a user made (bc1 being the most recent, and bc2 the most recent but one) are linked to the user thus:

For the first comment:

(u:BiteUser)-[:USER_PREVIOUS_COMMENT]->(bc1), (u)-[:USER_MADE_COMMENT]->(bc1)

and the second:

(u)-[:USER_MADE_COMMENT]->(bc2), (bc1)-[:USER_PREVIOUS_COMMENT]->(bc2)

So far, so normal (bread and butter in a web app, where a comment might be something like a login event, password change, post, etc.). However, this isn't all happening in one neat transaction, rather when loading via CSV. My query is below.

N.B. - a pre-processing script sorts the data so that all comments are in chronological order: the oldest comments come first, hence why there is no logic to position the comment in the correct place in the chain.

N.B. II - I'm using MERGE over create in several places here because of an expectation the query may be run more than once as new data becomes available or as those following up on this project (it's a talk) try to re-import data after technical difficulties. It's not a production script by any stretch of the imagination, and query optimization here is not top of my list of priorities.

```<code>LOAD CSV WITH HEADERS FROM 'file:///output-comments-0031.csv' AS line
// find the pub it refers to
MATCH (pl:PubListing) WHERE pl.source_pub_id = toInteger(line.source_pub_id)
MERGE (u:BiteUser {username: line.username })
// ensure the comment node is created
MERGE (bc:BiteComment { source_comment_id: toInteger(line.source_comment_id) })
SET
  // be flexible on scraped input
  bc += line,
  // indices should be integers, though
  bc.source_pub_id = toInteger(line.source_pub_id),
  bc.source_comment_id = toInteger(line.source_comment_id),
  bc.created_timestamp = toInteger(line.created_timestamp)
// link the comment to the user and pub directly
MERGE (u)-[:USER_MADE_COMMENT]->(bc)
MERGE (bc)-[:COMMENT_ABOUT_PUT]->(pl)
// and in a chain
// - this section will be repeated to link the comment to the
// pub, in a chain. I've only included the user example
// to isolate the problem for SO
WITH u, pl, bc
OPTIONAL MATCH (u)-[r:USER_PREVIOUS_COMMENT]->(lc:BiteComment)
WHERE lc <> bc
WITH u, bc, pl, r, CASE WHEN r IS NULL THEN [] ELSE [1] END AS upc, lc
FOREACH (i IN upc |
  DELETE r
  CREATE (bc)-[:USER_PREVIOUS_COMMENT]->(lc)
)
// pre-processing means we know this is the most recent comment
// that the graph has seen yet
MERGE (u)-[:USER_PREVIOUS_COMMENT]->(bc)
</code>```

The problem is that at present it creates both relationships for every comment. However, I when change the start of the query and add the following line after the LOAD CSV line,  and so load it one comment per transaction, it works as expected.

WITH line SKIP 0 LIMIT 1

and then,

WITH line SKIP 1 LIMIT 1

and then...

WITH line SKIP 2 LIMIT 1

... you get the idea.

My question is this. Why is this happening during CSV import, and how can I stop it without running the import as individual transactions?

答:
It's important to remember that Cypher queries do not process iteratively per row. Rather, they process all rows simultaneously and the iteration is per operation on all rows.

So you first MATCH to all rows, then you MERGE (second operation after your LOAD CSV) for all rows, etc.

Your CSV import seems to be going off of the (incorrect) assumption that rows are processed iteratively, so you have some kind of dependency on previously processed rows which will not work.

I'd advise you to fix your CSV to remove dependencies on previous row processing.

Either you'll need to do a COLLECT() of comments, then take the last two entries (something like WITH collectedComments[-2..] as lastTwo, then alias each node and create the relevant relationships), or you'll need to add timestamps or some other means of ordering, then perform a post-import query to grab the two latest comments and order them.

Body:
I'm using Neo4j version 3.1, running what I thought would be a quite straightforward import, but have run into very significant problems. I'm importing data about pubs (for non-UK users, public houses - places where you have a pint and relax!). A (pl:PubListing) has been commented on by a (u:BiteUser), creating a (bc:BiteComment). I've got two CSV files, and have already imported the (pl:PubListing) nodes, so am trying to import the comments linked to each pub (on pl.source_pub_id) and to each user (on u.username). Importantly, I'd like to add them both as a simple relationship, and as what - for want of a better word - I term a chain.

In this way, the last two comments a user made (bc1 being the most recent, and bc2 the most recent but one) are linked to the user thus:

For the first comment:

(u:BiteUser)-[:USER_PREVIOUS_COMMENT]->(bc1), (u)-[:USER_MADE_COMMENT]->(bc1)

and the second:

(u)-[:USER_MADE_COMMENT]->(bc2), (bc1)-[:USER_PREVIOUS_COMMENT]->(bc2)

So far, so normal (bread and butter in a web app, where a comment might be something like a login event, password change, post, etc.). However, this isn't all happening in one neat transaction, rather when loading via CSV. My query is below.

N.B. - a pre-processing script sorts the data so that all comments are in chronological order: the oldest comments come first, hence why there is no logic to position the comment in the correct place in the chain.

N.B. II - I'm using MERGE over create in several places here because of an expectation the query may be run more than once as new data becomes available or as those following up on this project (it's a talk) try to re-import data after technical difficulties. It's not a production script by any stretch of the imagination, and query optimization here is not top of my list of priorities.

LOAD CSV WITH HEADERS FROM 'file:///output-comments-0031.csv' AS line
// find the pub it refers to
MATCH (pl:PubListing) WHERE pl.source_pub_id = toInteger(line.source_pub_id)
MERGE (u:BiteUser {username: line.username })
// ensure the comment node is created
MERGE (bc:BiteComment { source_comment_id: toInteger(line.source_comment_id) })
SET
  // be flexible on scraped input
  bc += line,
  // indices should be integers, though
  bc.source_pub_id = toInteger(line.source_pub_id),
  bc.source_comment_id = toInteger(line.source_comment_id),
  bc.created_timestamp = toInteger(line.created_timestamp)
// link the comment to the user and pub directly
MERGE (u)-[:USER_MADE_COMMENT]->(bc)
MERGE (bc)-[:COMMENT_ABOUT_PUT]->(pl)
// and in a chain
// - this section will be repeated to link the comment to the
// pub, in a chain. I've only included the user example
// to isolate the problem for SO
WITH u, pl, bc
OPTIONAL MATCH (u)-[r:USER_PREVIOUS_COMMENT]->(lc:BiteComment)
WHERE lc <> bc
WITH u, bc, pl, r, CASE WHEN r IS NULL THEN [] ELSE [1] END AS upc, lc
FOREACH (i IN upc |
  DELETE r
  CREATE (bc)-[:USER_PREVIOUS_COMMENT]->(lc)
)
// pre-processing means we know this is the most recent comment
// that the graph has seen yet
MERGE (u)-[:USER_PREVIOUS_COMMENT]->(bc)

The problem is that at present it creates both relationships for every comment. However, I when change the start of the query and add the following line after the LOAD CSV line,  and so load it one comment per transaction, it works as expected.

WITH line SKIP 0 LIMIT 1

and then,

WITH line SKIP 1 LIMIT 1

and then...

WITH line SKIP 2 LIMIT 1

... you get the idea.

My question is this. Why is this happening during CSV import, and how can I stop it without running the import as individual transactions?


问:
Laravel 5.4 change password
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

```<code>public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}
</code>```

I created this new route in web.php above the resource route of the User model

```<code>Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');
</code>```

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

```<code>{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}
</code>```

答:
Instead of put, use post in your route as below.

```<code>Route::post('users/{user}', 'UserController@changePassword')->name('users.changePassword');
</code>```

And in your form have you passed the "_method" & CSRF token (CSRF is not required, if you have disabled it, but I recommend to use it always)?

If you are using Form and HTML class (ServiceProviders) for creating HTML & Forms in blades, use as below.

```<code>{!! Form::model($employee, ['method' => 'POST','route' => ['users.changePassword']]) !!}

--- Your Fields Code will go here ----

{!! Form::close() !!}
</code>```

Hope it helps!!

Title: Laravel 5.4 change password

Body:
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}

I created this new route in web.php above the resource route of the User model

Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}

Body:
Instead of put, use post in your route as below.

Route::post('users/{user}', 'UserController@changePassword')->name('users.changePassword');

And in your form have you passed the "_method" & CSRF token (CSRF is not required, if you have disabled it, but I recommend to use it always)?

If you are using Form and HTML class (ServiceProviders) for creating HTML & Forms in blades, use as below.

{!! Form::model($employee, ['method' => 'POST','route' => ['users.changePassword']]) !!}

--- Your Fields Code will go here ----

{!! Form::close() !!}

Hope it helps!!


问:
Add to home screen' Web App Install Banner not showing up in my web app and showing error
Below is the my manifest.json file

```<code>{
    "short_name": "ponds.brandfans.co",
    "name": "ponds.brandfans.co",
    "icons": [{
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "36x36",
        "type": "image/png",
        "density": "0.75"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "48x48",
        "type": "image/png",
        "density": "1.0"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "72x72",
        "type": "image/png",
        "density": "1.5"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "96x96",
        "type": "image/png",
        "density": "2.0"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "144x144",
        "type": "image/png",
        "density": "3.0"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "192x192",
        "type": "image/png",
        "density": "4.0"
    }],
    "start_url": "/",
    "display": "standalone",
    "gcm_sender_id": "482941778795",
    "background_color": "#2c3e50",
    "theme_color": "#2c3e50"
}
</code>```

I am getting an error: "Site cannot be installed: the page does not work offline"
Please let me know if I missed anything?

答:
Funny you asked this question. I was rendering a video that answers this question :)
https://youtu.be/xvLnmdjgEWY

Your serviceworker needs a fetch event handler.

Body:
Below is the my manifest.json file

{
    "short_name": "ponds.brandfans.co",
    "name": "ponds.brandfans.co",
    "icons": [{
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "36x36",
        "type": "image/png",
        "density": "0.75"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "48x48",
        "type": "image/png",
        "density": "1.0"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "72x72",
        "type": "image/png",
        "density": "1.5"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "96x96",
        "type": "image/png",
        "density": "2.0"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "144x144",
        "type": "image/png",
        "density": "3.0"
    }, {
        "src": "/images/logo/favicons/36x36.png",
        "sizes": "192x192",
        "type": "image/png",
        "density": "4.0"
    }],
    "start_url": "/",
    "display": "standalone",
    "gcm_sender_id": "482941778795",
    "background_color": "#2c3e50",
    "theme_color": "#2c3e50"
}

I am getting an error: "Site cannot be installed: the page does not work offline"
Please let me know if I missed anything?


问:
AngularFireMessagingModule and AngularFireStorageModule in AngularFire2
I'm a new baby with angular4, But it is said that angularfire2 is an official for implementation firebase using angular, but I can't see how to implement cloud messaging using the newest release 4.0.0-rc.0

i've try

```<code>import { AngularFireStorageModule } from 'angularfire2/storage';
import { AngularFireMessagingModule } from 'angularfire2/messaging';
</code>```

but those modules doesn't exist

I have to implement fcm for my project, can anyone give me solution?
or perhaps could anyone tell me which angularfire2 version that support cloud messaging and some example maybe??

Any help will be appreciated. I you not capable to solve it, don't close on me please..

答:
It looks like AngularFireStorageModule and AngularFireMessagingModule have not been released yet, and they are working on it. I would suggest that you just wait until it gets released.

Picture from AngularFire2 Github

Body:
I'm a new baby with angular4, But it is said that angularfire2 is an official for implementation firebase using angular, but I can't see how to implement cloud messaging using the newest release 4.0.0-rc.0

i've try

import { AngularFireStorageModule } from 'angularfire2/storage';
import { AngularFireMessagingModule } from 'angularfire2/messaging';

but those modules doesn't exist

I have to implement fcm for my project, can anyone give me solution?
or perhaps could anyone tell me which angularfire2 version that support cloud messaging and some example maybe??

Any help will be appreciated. I you not capable to solve it, don't close on me please..


问:
Data from a DataGridView Configured on Another Form
I have Form1 that has a dataGridView and a button to add contents to that Grid. When selecting this button, I call Form2 which has 2 TextBox and a ComboBox to populate the Name, Directory and Format (for example), plus an OK button to add the row to the dataGridView on Form1.

When I get back on Form1, the dataGridView must be showing the content entered. What happens is that my Grid has three columns: Name, Format and a button column to, when clicking it, reload that screen of Form2 with the previously filled information loaded again in each field to be able to change or just consult.

Firstly I tried to create a function to add the lines to my Grid by parameters, as shown in the code below:

Eu tenho o Form1 que possui uma dataGridView e um botão para adicionar conteúdos nessa Grid. Ao selecionar esse botão, eu chamo o Form2 que possui 2 TextBox e um ComboBox para preencher o Nome, Diretório e Formato (por exemplo), além de um botão OK para adicionar a linha a dataGridView na Form1.

Form 1

```<code>public Form1()
{
    InitializeComponent();
}

public void AddRows(string name, string path)
{
    dataGridView1.Rows.Add(name, path);
    dataGridView1.Update();
}
</code>```

Form 2

```<code>public Form2()
{
    InitializeComponent();
}

private void bt1_Click(object sender, EventArgs e)
{
    var nome = txt_name.Text;
    var path = txt_path.Text;

    var form1 = new Form1();
    form1.AddRows(name, path);
}
</code>```

However, it ended up not working, showing nothing on the Grid. So I thought about creating a class with a name, path and format method (get and set for each) to store everything in a list of objects (I think that's it, forgive me if I'm wrong because I'm a beginner). Or save to a DataSet. But then I thought, I instantiate the class in my Form2 and pass the values filled in the fields, but then, what do I do in my Form1?

I think it's all very confusing, I'd appreciate it if someone could explain a clearer method of resolving this situation and please be very specific since I'm a beginner.

答:
Can you try my demo?</p>

```<code>    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {
        //change code to get current row and check null, etc
        var sels = dataGridView1.SelectedRows;
        if (sels == null || sels.Count == 0)
            return;
        DataGridViewRow selRow = sels[0];
        frmDialog dlg = new frmDialog(
            selRow.Cells[0].Value,
            selRow.Cells[1].Value);
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            selRow.Cells[0].Value = dlg.Col1Value;
            selRow.Cells[1].Value = dlg.Col2Value;
            //...
        }
    }
}

    public partial class frmDialog : Form
{
    public object Col1Value;
    public object Col2Value;
    //...other properties
    public frmDialog()
    {
        InitializeComponent();
    }

    public frmDialog(object col1, object col2)
    {
        InitializeComponent();
        this.Col1Value = col1;
        this.Col2Value = col2;
        //...other properties
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
    }
}
</code>```

Body:
I have Form1 that has a dataGridView and a button to add contents to that Grid. When selecting this button, I call Form2 which has 2 TextBox and a ComboBox to populate the Name, Directory and Format (for example), plus an OK button to add the row to the dataGridView on Form1.

When I get back on Form1, the dataGridView must be showing the content entered. What happens is that my Grid has three columns: Name, Format and a button column to, when clicking it, reload that screen of Form2 with the previously filled information loaded again in each field to be able to change or just consult.

Firstly I tried to create a function to add the lines to my Grid by parameters, as shown in the code below:

Eu tenho o Form1 que possui uma dataGridView e um botão para adicionar conteúdos nessa Grid. Ao selecionar esse botão, eu chamo o Form2 que possui 2 TextBox e um ComboBox para preencher o Nome, Diretório e Formato (por exemplo), além de um botão OK para adicionar a linha a dataGridView na Form1.

Form 1

public Form1()
{
    InitializeComponent();
}

public void AddRows(string name, string path)
{
    dataGridView1.Rows.Add(name, path);
    dataGridView1.Update();
}

Form 2

public Form2()
{
    InitializeComponent();
}

private void bt1_Click(object sender, EventArgs e)
{
    var nome = txt_name.Text;
    var path = txt_path.Text;

    var form1 = new Form1();
    form1.AddRows(name, path);
}

However, it ended up not working, showing nothing on the Grid. So I thought about creating a class with a name, path and format method (get and set for each) to store everything in a list of objects (I think that's it, forgive me if I'm wrong because I'm a beginner). Or save to a DataSet. But then I thought, I instantiate the class in my Form2 and pass the values filled in the fields, but then, what do I do in my Form1?

I think it's all very confusing, I'd appreciate it if someone could explain a clearer method of resolving this situation and please be very specific since I'm a beginner.

Body:
Can you try my demo?

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void btnEdit_Click(object sender, EventArgs e)
    {
        //change code to get current row and check null, etc
        var sels = dataGridView1.SelectedRows;
        if (sels == null || sels.Count == 0)
            return;
        DataGridViewRow selRow = sels[0];
        frmDialog dlg = new frmDialog(
            selRow.Cells[0].Value,
            selRow.Cells[1].Value);
        if (dlg.ShowDialog() == DialogResult.OK)
        {
            selRow.Cells[0].Value = dlg.Col1Value;
            selRow.Cells[1].Value = dlg.Col2Value;
            //...
        }
    }
}

    public partial class frmDialog : Form
{
    public object Col1Value;
    public object Col2Value;
    //...other properties
    public frmDialog()
    {
        InitializeComponent();
    }

    public frmDialog(object col1, object col2)
    {
        InitializeComponent();
        this.Col1Value = col1;
        this.Col2Value = col2;
        //...other properties
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        this.DialogResult = DialogResult.OK;
    }
}


问:
Dynamically sizing width of UICollectionView cell width for various iPhone screen sizes
I have a pretty simple UICollectionView requirement. For iPhone 6/6s/7 and 6/6s/7 Plus sizes the two cells must show side by side i.e. two cells per line. And for iPhone 5/5s/SE it should show 1 cell per line. My cell height is fixed pretty much to 194.

Now I have this code in the view controller to achieve this somewhat-

```<code>import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!
    var screenWidth: CGFloat!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue

        screenWidth = collectionView.frame.width

        // Do any additional setup after loading the view, typically from a nib
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 2)
        layout.itemSize = CGSize(width: screenWidth / 2, height: 194)
        layout.minimumInteritemSpacing = 0
        collectionView.collectionViewLayout = layout
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.blue
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath as IndexPath) as UICollectionViewCell
        cell.backgroundColor = UIColor.white
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 0.5
        return cell
    }

}
</code>```

The resulting output is this-

As you can see, the iPhone Plus size and the 5/5s/SE layouts are fine or I should say that I am fine with those with what I have, but the second i.e. for 6/6s/7 sizes the cells are almost stuck to each other. I know that I have layout.minimumInteritemSpacing = 0 but if I increase this to even by 1 then the cells will be pushed down just like the third image, using UIEdgeInsets are also causing the same issue.

My entire UICollectionView is pinned top 0 , bottom 0 , left 8 and right 8 to the superview. I reviewed a few Q&As in SO which are somewhat related to this and suggests using UICollectionViewDelegateFlowLayout's sizeForItemAt function, but I haven't been able to resolve this using that either.

How do I resolve the spacing issue for 6/6s/7 screen width to have two cells in a line with some spacing? My ultimate goal is to have 2 cells per line on devices 6 and above and 1 cell per line for devices 5s and below (includes SE). Can this be done?

答:
You need to take into account the collectionViews edge insets and minimumInteritemSpacing before creating a size. You should really implement the UICollectionViewFlowLayoutDelegate methods for laying out the collectionView. Your width should be (screenSize - left inset - right inset - minimumInteritemSpacing) / 2.

EDIT

Why not check what device it is and then return a size based on that?

e.g

```<code>if iPhone6 {
    return size / 2
} else {
    return size
}
</code>```

To check what device it currently is refer to the following answer.

Body:
I have a pretty simple UICollectionView requirement. For iPhone 6/6s/7 and 6/6s/7 Plus sizes the two cells must show side by side i.e. two cells per line. And for iPhone 5/5s/SE it should show 1 cell per line. My cell height is fixed pretty much to 194.

Now I have this code in the view controller to achieve this somewhat-

import UIKit

class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!
    var screenWidth: CGFloat!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .blue

        screenWidth = collectionView.frame.width

        // Do any additional setup after loading the view, typically from a nib
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 2)
        layout.itemSize = CGSize(width: screenWidth / 2, height: 194)
        layout.minimumInteritemSpacing = 0
        collectionView.collectionViewLayout = layout
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.blue
    }

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath as IndexPath) as UICollectionViewCell
        cell.backgroundColor = UIColor.white
        cell.layer.borderColor = UIColor.black.cgColor
        cell.layer.borderWidth = 0.5
        return cell
    }

}

The resulting output is this-

As you can see, the iPhone Plus size and the 5/5s/SE layouts are fine or I should say that I am fine with those with what I have, but the second i.e. for 6/6s/7 sizes the cells are almost stuck to each other. I know that I have layout.minimumInteritemSpacing = 0 but if I increase this to even by 1 then the cells will be pushed down just like the third image, using UIEdgeInsets are also causing the same issue.

My entire UICollectionView is pinned top 0 , bottom 0 , left 8 and right 8 to the superview. I reviewed a few Q&As in SO which are somewhat related to this and suggests using UICollectionViewDelegateFlowLayout's sizeForItemAt function, but I haven't been able to resolve this using that either.

How do I resolve the spacing issue for 6/6s/7 screen width to have two cells in a line with some spacing? My ultimate goal is to have 2 cells per line on devices 6 and above and 1 cell per line for devices 5s and below (includes SE). Can this be done?

Body:
You need to take into account the collectionViews edge insets and minimumInteritemSpacing before creating a size. You should really implement the UICollectionViewFlowLayoutDelegate methods for laying out the collectionView. Your width should be (screenSize - left inset - right inset - minimumInteritemSpacing) / 2.

EDIT

Why not check what device it is and then return a size based on that?

e.g

if iPhone6 {
    return size / 2
} else {
    return size
}

To check what device it currently is refer to the following answer.


问:
How to verify whether existing token about to expire in java
How to verify whether existing token about to expire in java and get another new access token before it expires?

I already searched on google on above, found some answer as take expiry time of access token, and write some logic based on system time matching with expiry time, so if current time about to near expiry time, then make a backend call to get new access token. I am not asking how to get new access token using refresh token, for which I already had backend code which takes care of it. All I need is to know when to make a ajax call using java when access token about to expire..

Please tell me is there any better approach for above?

答:
You can calculate the expiration date based on the expires_in value in the response and store both the access token and expiration date in memory. Before using the access token check if it has expired, fetch a new one if expired and store the same in memory.
You can also write a scheduler which runs in the background and fetches the access token before it expires.</p>


问:
How to implement a Shared Kernel (DDD) in .Net properly
I have a legacy app I am redesigning because it's what we call a "ball of mudd" at this point, no layering or SOC at all.  The team is used to working modularly, meaning there is a team that works on "training", "Job Opportunities", one that works on a module managing "Duty Planning (military)".  We have one website exposing these areas to our clients as a portal of services, one database and a few external apps we service.

Im doing well redesigning most of the layers except how to partition the domain properly (I should mention at this point that we are using .Net 4.0).  My original thought was that these were bounded contexts because of the way they were working, they really seemed to have different sets of users, but I believe now the reality is people who use this site may and do use many areas at once.  Sure, some groups ONLY use one service exclusively, but a lot use several.  The goal of the site is one-stop management of "members".  Between the modules we have classes unique to the module and then we have some shared classes, for example, the concept of a member is known and used by all modules.  Member is actually a core concept, the site adds value by tracking member's information in all these areas at once.  That's basically it, a few closely related but separate areas in the system and a shared area.  I hope that is clear enough to answer the question I have.

I am thinking I would still have a shared kernel, even if these are not bounded contexts, for the common entities and shared domain interfaces such as a generic repository interface.  Would it be wise to put all the common code (generic repository, core domain model, shared kernel etc) into the same namespace or namespace hierarchy and should I isolate this namespace in it's own assembly?  Likewise, would I then break out each area ("training", "Opportunities"...) into their own assemblies or is it better to have them all in one assembly and logically partition them by namespace.  On one hand, it's a bit easier to see the modules physically partitioned, but I am worried about situations where two modules need to work together to solve a problem.  How would they communicate and keep things acyclic (through services in the application layer I am guessing).

so (summary of options):

Domain.Model (dll)
  -- Domain.Model.Core
     -- Kernel (shared entities and core domain model)
     -- RepositoryFramework
     -- etc...
  -- Domain.Model.Training
  -- Domain.Model.Opportunities
  ...

or

Domain.Model.Core

Domain.Model.Training (dll)

Domain.Model.Opportunities (dll)
(how do training and opportunities work together?)

Thank you very much for your time,

答:
In case of physical layout, I would put everything (the whole domain model) in one assembly. Using separate assemblies does not give you any benefit while it complicates things and increases compilation time.

On the other hand, if there is a risk that some developers use inappropriate classes (those who belong to other modules/contexts), it may be wise to split the logic into a common assembly (core domain, shared kernel) and assemblies specific to each module/context.

In the case of the logical layout (namespaces) I would give each part a separate namespace (for example DomainModel.Core, DomainModel.Training). Sometimes it is wise to go one step further and put each Aggregate into its own namespace. It prevents accidental crossing of the aggregate boundaries since it requires a separate 'using' directive.

Hope that makes sense.

ContentLicense: CC BY-SA 4.0


问:
jQM/PhoneGap: Navigation started when state=1 bug?
I've overcome a frustrating problem with jQuery Mobile only to run into another one. Here's the story:
I'm using $.mobile.changePage() as shown:

```<code><script type="text/javascript">
$(document).on('click', '#submitroll', function(e) {
    e.preventDefault();
    var dieRoll = $("#dieresult").val();

    $.mobile.changePage('valueresult.html', {
        data: {
                arg1: dieRoll
        }
    });
});
</script>
</code>```

When I click on the button (#submitroll), it doesn't transition to the valueresult.html page (which resides in the same directory as the origin page). Instead, the console output produces the following error:

Failed to load webpage with error: CDVWebViewDelegate: Navigation started when state=1

I searched on that error and found many results, most of them referring to a bug in PhoneGap 2.7. I happened to be running PhoneGap 2.8.1, so I figured/hoped that was the issue. I noticed  PhoneGap 2.9rc1 available (which, according to the release notes, includes a fix to that particular bug), so I installed 2.9rc1 just to see if it would fix the problem.... and it didn't.

But before I inform the PhoneGap folks, I want to rule out the (strong) possibility that I'm doing something wrong.

I'm running jQuery 1.10.1 and jQuery Mobile 1.3.1, currently building/testing on iOS 6.1. If anyone has any suggestions on how to proceed, that would be great. Thanks in advance!

答: This usually means it's a bad URL. Check the link.</p>

Body:
I've overcome a frustrating problem with jQuery Mobile only to run into another one. Here's the story:
I'm using $.mobile.changePage() as shown:

When I click on the button (#submitroll), it doesn't transition to the valueresult.html page (which resides in the same directory as the origin page). Instead, the console output produces the following error:

Failed to load webpage with error: CDVWebViewDelegate: Navigation started when state=1

I searched on that error and found many results, most of them referring to a bug in PhoneGap 2.7. I happened to be running PhoneGap 2.8.1, so I figured/hoped that was the issue. I noticed  PhoneGap 2.9rc1 available (which, according to the release notes, includes a fix to that particular bug), so I installed 2.9rc1 just to see if it would fix the problem.... and it didn't.

But before I inform the PhoneGap folks, I want to rule out the (strong) possibility that I'm doing something wrong.

I'm running jQuery 1.10.1 and jQuery Mobile 1.3.1, currently building/testing on iOS 6.1. If anyone has any suggestions on how to proceed, that would be great. Thanks in advance!


问:
using lexical this in ES6
I was learning about lexical this in ES6, and I countered this example :

```<code>let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function(){
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();
</code>```

so let's say I want to convert the toString function to an array function so I'll have this :

```<code>let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();
</code>```

in this example cars is undefined, why I'm getting that, and how can I call cars from the person object in that example.

the same goes for this :

```<code>let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    cars.forEach(car => console.log(`${this.name} has ${car}`));
  }
}

person.toString();
</code>```

答:
The first example is already broken.

in this example cars is undefined, why I'm getting that

There is no variable with name cars. Whether or not you are using an arrow function doesn't make a difference.

how can I call cars from the person object in that example.

Use a method or function expression and reference it with this.cars:

```<code>let person = {
  name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString() {
    for(let car of this.cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}
</code>```

Arrow functions cannot be used as instance methods, because in instance methods you don't want lexical this. Learn more: Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

Title: using lexical this in ES6

Body:
I was learning about lexical this in ES6, and I countered this example :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : function(){
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();

so let's say I want to convert the toString function to an array function so I'll have this :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    for(let car of cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

person.toString();

in this example cars is undefined, why I'm getting that, and how can I call cars from the person object in that example.

the same goes for this :

let person = {
    name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString : () => {
    cars.forEach(car => console.log(`${this.name} has ${car}`));
  }
}

person.toString();

Body:
The first example is already broken.

in this example cars is undefined, why I'm getting that

There is no variable with name cars. Whether or not you are using an arrow function doesn't make a difference.

how can I call cars from the person object in that example.

Use a method or function expression and reference it with this.cars:

let person = {
  name : 'Alex',
  cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
  toString() {
    for(let car of this.cars){
            console.log(`${this.name} has ${car}`)
        }
  }
}

Arrow functions cannot be used as instance methods, because in instance methods you don't want lexical this. Learn more: Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?


问:
How to move my player sprite?
Here is my code. How can I move my class Player sprite? Would I add an x,y to my def __init__? like def __init__(self, x, y)? Thanks for the answers,

```<code>import pygame as pg
WIDTH = 800
HEIGHT = 600

CLOCK = pg.time.Clock()
FPS = 60

GREEN = (0, 255, 0)
LIGHTBLUE = (20, 130, 230)
BGCOLOR = LIGHTBLUE

class Player(pg.sprite.Sprite):

    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH / 2, HEIGHT / 2))
        self.x = x
        self.y = y

player = Player()

pg.init()

screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('The Moon Smiles Back')

running = True
while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False

    all_sprites = pg.sprite.Group()
    all_sprites.add(player)
    all_sprites.update()
    screen.fill(BGCOLOR)
    all_sprites.draw(screen)
    pg.display.flip()

    CLOCK.tick(FPS)

pg.quit()
</code>```

答:
Add two attributes to the Player class to store the current velocity of the player. In the update method, add the velocities to the x and y attributes and then set the rect to the new position.

```<code>class Player(pg.sprite.Sprite):

    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.x = x
        self.y = y
        self.velocity_x = 0
        self.velocity_y = 0

    def update(self):
        self.x += self.velocity_x
        self.y += self.velocity_y
        self.rect.center = (self.x, self.y)
</code>```

To move the player to the right, set the player.velocity_x to the desired speed if the 'd' key is pressed (in this example), and back to 0 if the key is released. Do the same for the other directions.

```<code>if event.type == pg.KEYDOWN:
    if event.key == pg.K_ESCAPE:
        running = False
    elif event.key == pg.K_d:
        player.velocity_x = 3
elif event.type == pg.KEYUP:
    if event.key == pg.K_d:
        player.velocity_x = 0
</code>```

Title: How to move my player sprite?

Body:
Here is my code. How can I move my class Player sprite? Would I add an x,y to my def __init__? like def __init__(self, x, y)? Thanks for the answers,

import pygame as pg
WIDTH = 800
HEIGHT = 600

CLOCK = pg.time.Clock()
FPS = 60

GREEN = (0, 255, 0)
LIGHTBLUE = (20, 130, 230)
BGCOLOR = LIGHTBLUE

class Player(pg.sprite.Sprite):

    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = ((WIDTH / 2, HEIGHT / 2))
        self.x = x
        self.y = y

player = Player()

pg.init()

screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption('The Moon Smiles Back')

running = True
while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                running = False

    all_sprites = pg.sprite.Group()
    all_sprites.add(player)
    all_sprites.update()
    screen.fill(BGCOLOR)
    all_sprites.draw(screen)
    pg.display.flip()

    CLOCK.tick(FPS)

pg.quit()

Body:
Add two attributes to the Player class to store the current velocity of the player. In the update method, add the velocities to the x and y attributes and then set the rect to the new position.

class Player(pg.sprite.Sprite):

    def __init__(self, x, y):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 50))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.x = x
        self.y = y
        self.velocity_x = 0
        self.velocity_y = 0

    def update(self):
        self.x += self.velocity_x
        self.y += self.velocity_y
        self.rect.center = (self.x, self.y)

To move the player to the right, set the player.velocity_x to the desired speed if the 'd' key is pressed (in this example), and back to 0 if the key is released. Do the same for the other directions.

if event.type == pg.KEYDOWN:
    if event.key == pg.K_ESCAPE:
        running = False
    elif event.key == pg.K_d:
        player.velocity_x = 3
elif event.type == pg.KEYUP:
    if event.key == pg.K_d:
        player.velocity_x = 0


问:
CakePHP 3 sessions table in database
I have some questions regarding having CakePHP 3 sessions table stored in the database:

1) Is there a way to remname the table from sessions to a different name? If yes, where should I specify the new name?

2) Similarly to question 1: Is there a way to remname the names of colums in sessions table, so that CakePHP would still operate correctly?

3) Is there a simple way to add even the most basic encription of the data column of sessions table?

答:
So I will cite the database session docs and then also provide some answers. The answers in the docs are more complete.

Specify the model you want to use by including a 'model' key.

```<code>'Session' => [
    'defaults' => 'database',
    'handler' => [
        'engine' => 'DatabaseSession',
        'model' => 'MyCustomSessions'
    ]
]
</code>```

The DatabaseSession handler appears to hard code 'data' and some of the other columns. However, you can (and should) extend that class if you want to do something special

Based on what you want to do it appears creating your own SessionHandler is the way to go. It is quite simple to do and it is outlined in the docs.

My best advice would to take a peek at cake's DatabaseSession. It seems that your requirements are special and it is probably your best course of action.

Title: CakePHP 3 sessions table in database

Body:
So I will cite the database session docs and then also provide some answers. The answers in the docs are more complete.

Specify the model you want to use by including a 'model' key.

'Session' => [
    'defaults' => 'database',
    'handler' => [
        'engine' => 'DatabaseSession',
        'model' => 'MyCustomSessions'
    ]
]

The DatabaseSession handler appears to hard code 'data' and some of the other columns. However, you can (and should) extend that class if you want to do something special

Based on what you want to do it appears creating your own SessionHandler is the way to go. It is quite simple to do and it is outlined in the docs.

My best advice would to take a peek at cake's DatabaseSession. It seems that your requirements are special and it is probably your best course of action.


问:
Android: How can I put my notification on top of notification area?
I'm trying to put my notification on top of notification area.

A solution is to set the parameter "when" to my notification object with a future time like:

```<code>notification.when = System.currentTimeMills()*2;
</code>```

The code that I'm using in this:

```<code>long timeNotification = System.currentTimeMillis()*2;
Notification notification = new Notification(statusIcon,c.getResources().getString(R.string.app_name),timeNotification);
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notification.when = timeNotification;
notification.priority = Notification.PRIORITY_MAX;
</code>```

but some apps (like Facebook) are able to put a simple notification with their current time over mine.

If I refresh my notification it remains under these ones.

What parameters I have to set to put my Notification to the top of the notifications area?

答:
Please note that if you want a "heads-up" notification i.e., one that displays over the top of the current user window you must have the following set in your builder:

```<code>setDefaults(NotificationCompat.DEFAULT_VIBRATE)
</code>```

The reference is in the javadoc:

A notification that vibrates is more likely to be presented as a heads-up notification, on some platforms.

Complete example for a heads-up notification:

```<code>NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.some_small_icon)
            .setContentTitle("Title")
            .setContentText("This is a test notification with MAX priority")
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(NotificationCompat.DEFAULT_VIBRATE);
</code>```

Body:
I'm trying to put my notification on top of notification area.

A solution is to set the parameter "when" to my notification object with a future time like:

notification.when = System.currentTimeMills()*2;

The code that I'm using in this:

long timeNotification = System.currentTimeMillis()*2;
Notification notification = new Notification(statusIcon,c.getResources().getString(R.string.app_name),timeNotification);
notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
notification.when = timeNotification;
notification.priority = Notification.PRIORITY_MAX;

but some apps (like Facebook) are able to put a simple notification with their current time over mine.

If I refresh my notification it remains under these ones.

What parameters I have to set to put my Notification to the top of the notifications area?

Body:
Please note that if you want a "heads-up" notification i.e., one that displays over the top of the current user window you must have the following set in your builder:

setDefaults(NotificationCompat.DEFAULT_VIBRATE)

The reference is in the javadoc:

A notification that vibrates is more likely to be presented as a heads-up notification, on some platforms.

Complete example for a heads-up notification:

NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.some_small_icon)
            .setContentTitle("Title")
            .setContentText("This is a test notification with MAX priority")
            .setPriority(Notification.PRIORITY_MAX)
            .setDefaults(NotificationCompat.DEFAULT_VIBRATE);


问:
JQuery/Javascript - Search DOM for text and insert HTML
How do I search the DOM for a certain string in the document's text (say, "cheese") then insert some HTML immediately after that string (say, "is fantastic").

I have tried the following:

```<code>for (var tag in document.innerHTML) {
    if (tag.matches(/cheese/) != undefined) {
        document.innerHTML.append(<b>is fantastic</b>
    }
}
</code>```

(The above is more of an illustration of what I have tried, not the actual code. I expect the syntax is horribly wrong so please excuse any errors, they are not the problem).

Cheers,

Pete

答:
The way to do this is to traverse the document and search each text node for the desired text. Any way involving innerHTML is hopelessly flawed.

Here's a function that works in all browsers and recursively traverses the DOM within the specified node and replaces occurrences of a piece of text with nodes copied from the supplied template node replacementNodeTemplate:

```<code>function replaceText(node, text, replacementNodeTemplate) {
    if (node.nodeType == 3) {
        while (node) {
            var textIndex = node.data.indexOf(text), currentNode = node;
            if (textIndex == -1) {
                node = null;
            } else {
                // Split the text node after the text
                var splitIndex = textIndex + text.length;
                var replacementNode = replacementNodeTemplate.cloneNode(true);
                if (splitIndex < node.length) {
                    node = node.splitText(textIndex + text.length);
                    node.parentNode.insertBefore(replacementNode, node);
                } else {
                    node.parentNode.appendChild(replacementNode);
                    node = null;
                }
                currentNode.deleteData(textIndex, text.length);
            }
        }
    } else {
        var child = node.firstChild, nextChild;
        while (child) {
            nextChild = child.nextSibling;
            replaceText(child, text, replacementNodeTemplate);
            child = nextChild;
        }
    }
}
</code>```

Here's an example use:

```<code>replaceText(document.body, "cheese", document.createTextNode("CHEESE IS GREAT"));
</code>```

If you prefer, you can create a wrapper function to allow you to specify the replacement content as a string of HTML instead:

```<code>function replaceTextWithHtml(node, text, html) {
    var div = document.createElement("div");
    div.innerHTML = html;
    var templateNode = document.createDocumentFragment();
    while (div.firstChild) {
        templateNode.appendChild(div.firstChild);
    }
    replaceText(node, text, templateNode);
}
</code>```

Example:

```<code>replaceTextWithHtml(document.body, "cheese", "cheese <b>is fantastic</b>");
</code>```

I've incorporated this into a jsfiddle example: http://jsfiddle.net/timdown/azZsa/

Body:
How do I search the DOM for a certain string in the document's text (say, "cheese") then insert some HTML immediately after that string (say, "is fantastic").

I have tried the following:

for (var tag in document.innerHTML) {
    if (tag.matches(/cheese/) != undefined) {
        document.innerHTML.append(is fantastic
    }
}

(The above is more of an illustration of what I have tried, not the actual code. I expect the syntax is horribly wrong so please excuse any errors, they are not the problem).

Cheers,

Pete

Body:
The way to do this is to traverse the document and search each text node for the desired text. Any way involving innerHTML is hopelessly flawed.

Here's a function that works in all browsers and recursively traverses the DOM within the specified node and replaces occurrences of a piece of text with nodes copied from the supplied template node replacementNodeTemplate:

function replaceText(node, text, replacementNodeTemplate) {
    if (node.nodeType == 3) {
        while (node) {
            var textIndex = node.data.indexOf(text), currentNode = node;
            if (textIndex == -1) {
                node = null;
            } else {
                // Split the text node after the text
                var splitIndex = textIndex + text.length;
                var replacementNode = replacementNodeTemplate.cloneNode(true);
                if (splitIndex < node.length) {
                    node = node.splitText(textIndex + text.length);
                    node.parentNode.insertBefore(replacementNode, node);
                } else {
                    node.parentNode.appendChild(replacementNode);
                    node = null;
                }
                currentNode.deleteData(textIndex, text.length);
            }
        }
    } else {
        var child = node.firstChild, nextChild;
        while (child) {
            nextChild = child.nextSibling;
            replaceText(child, text, replacementNodeTemplate);
            child = nextChild;
        }
    }
}

Here's an example use:

replaceText(document.body, "cheese", document.createTextNode("CHEESE IS GREAT"));

If you prefer, you can create a wrapper function to allow you to specify the replacement content as a string of HTML instead:

function replaceTextWithHtml(node, text, html) {
    var div = document.createElement("div");
    div.innerHTML = html;
    var templateNode = document.createDocumentFragment();
    while (div.firstChild) {
        templateNode.appendChild(div.firstChild);
    }
    replaceText(node, text, templateNode);
}

Example:

replaceTextWithHtml(document.body, "cheese", "cheese <b>is fantastic</b>");

I've incorporated this into a jsfiddle example: http://jsfiddle.net/timdown/azZsa/


问:
peewee 'no such table' error
I am trying to put data into a database using flask and peewee, and I have come across the following error: peewee.OperationalError: no such table: post

My models.py file is below:

```<code>from peewee import *
import datetime

db = SqliteDatabase('posts.db') #create database to interact with

#create a class for blogposts
class Post(Model):
    id = PrimaryKeyField()
    date = DateTimeField(default = datetime.datetime.now)
    title = CharField()
    text = TextField()

    class Meta:
        database = db

def initialize_db():
    db.connect()
    db.create_tables([Post], safe = True)
    db.close()
</code>```

I have Googled this, and for most people the lack of 'db.create_tables()' seems to be the problem. Obviously, it's in my code, so I am really not sure where the error is coming from. Some advice would be much appreciated. The problem seems to arise specifically when I try to populate the 'text' field using another .py file.

答:
I adapted your code into the following snippet and it works for me:

```<code>from peewee import *
import datetime

db = SqliteDatabase('posts.db') #create database to interact with

#create a class for blogposts
class Post(Model):
    id = PrimaryKeyField()
    date = DateTimeField(default = datetime.datetime.now)
    title = CharField()
    text = TextField()

    class Meta:
        database = db

def initialize_db():
    db.connect()
    db.create_tables([Post], safe = True)
    db.close()

initialize_db() #if db tables are not created, create them
post = Post.create(id=4, title="Some title", text="some text1") #add a new row
post.save() #persist it to db, not necessarily needed
</code>```

You'll need to call the create method when creating a new Post (i.e. a new row in your database). Other than that, initialize_db() seems to work just fine.

If you are unable to perform any writes on the database, make sure you have write access in the directory where you are trying to do that (in this case, it would be your working directory)

Title: peewee 'no such table' error

Body:
I am trying to put data into a database using flask and peewee, and I have come across the following error: peewee.OperationalError: no such table: post

My models.py file is below:

from peewee import *
import datetime

db = SqliteDatabase('posts.db') #create database to interact with

#create a class for blogposts
class Post(Model):
    id = PrimaryKeyField()
    date = DateTimeField(default = datetime.datetime.now)
    title = CharField()
    text = TextField()

    class Meta:
        database = db

def initialize_db():
    db.connect()
    db.create_tables([Post], safe = True)
    db.close()

I have Googled this, and for most people the lack of 'db.create_tables()' seems to be the problem. Obviously, it's in my code, so I am really not sure where the error is coming from. Some advice would be much appreciated. The problem seems to arise specifically when I try to populate the 'text' field using another .py file.

Body:
I adapted your code into the following snippet and it works for me:

from peewee import *
import datetime

db = SqliteDatabase('posts.db') #create database to interact with

#create a class for blogposts
class Post(Model):
    id = PrimaryKeyField()
    date = DateTimeField(default = datetime.datetime.now)
    title = CharField()
    text = TextField()

    class Meta:
        database = db

def initialize_db():
    db.connect()
    db.create_tables([Post], safe = True)
    db.close()

initialize_db() #if db tables are not created, create them
post = Post.create(id=4, title="Some title", text="some text1") #add a new row
post.save() #persist it to db, not necessarily needed

You'll need to call the create method when creating a new Post (i.e. a new row in your database). Other than that, initialize_db() seems to work just fine.

If you are unable to perform any writes on the database, make sure you have write access in the directory where you are trying to do that (in this case, it would be your working directory)


问:
How to create an SUnit test in Dolphin Smalltalk?
I've created a small (test) addition to the Dolphin Smalltalk framework
that I want to submit on GitHub later. (1 method: Integer>>isPrime)
But first, I want add my testing method of this method to the standard regression test set, with ~ 2400 tests now. (IntegerTest>>testIsPrime)
I've found the classes TestCase, DolphinTest, IntegerTest and the SUnit browser.
But I didn't find out how to add my test to the standard test set.

Can someone point me the right direction?

答:
I assume you are working from a Git checkout and have the test classes in your image. From there the easiest thing is to modify an existing class (such as IntegerTest) in the code browser, save the package back to the file system, and then Git should show the files as modified.

The neat thing about SUnit is that by default it will include all methods that start with 'test' in the test suite. So just add the test, run the suite, and see the number of tests increase by one!


问:
How do you create a blog post in rails without a topic?
I am doing a Ruby on Rails course and I am on a part where I am trying to create a blog post but it is giving me an error. It says:

1 error prohibited this blog from being saved:

Topic must exist

my code

What do I change to fix it?

答:
you have to put topic_id since blog post belongs_to topic
here is how

inside app/views/blogs/_form.html.erb add f.select to choose topic (I copied the code from the link that you passed)

```<code><%= form_with(model: blog, local: true) do |form| %>
  <% if blog.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:</h2>

      <ul>
      <% blog.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= form.select :topic_id, Topic.pluck(:title, :id).sort, include_blank: false %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title, id: :blog_title %>
  </div>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body, id: :blog_body %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
</code>```

Body:
you have to put topic_id since blog post belongs_to topic
here is how

inside app/views/blogs/_form.html.erb add f.select to choose topic (I copied the code from the link that you passed)

<%= form_with(model: blog, local: true) do |form| %>
  <% if blog.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:</h2>

      <ul>
      <% blog.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= form.select :topic_id, Topic.pluck(:title, :id).sort, include_blank: false %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title, id: :blog_title %>
  </div>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body, id: :blog_body %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>


问:
UNIX sed: How to remove lines with pattern if next line is not a number(or matches the same pattern)?
Here is sample text file:

```<code>$ cat text.txt
Checking log log0.txt
12
Checking log log1.txt
Checking log log2.txt
34
56
78
Checking log log3.txt
Checking log log4.txt
Checking log log5.txt
90
</code>```

How to process it using sed (or any other tool), so it will look like this:

```<code>$ cat text.txt
Checking log log0.txt
12
Checking log log2.txt
34
56
78
Checking log log5.txt
90
</code>```

Pattern is "Checking"

Update:
If last line has "Checking" pattern, it should be removed as well.

Body:
Here is sample text file:

$ cat text.txt
Checking log log0.txt
12
Checking log log1.txt
Checking log log2.txt
34
56
78
Checking log log3.txt
Checking log log4.txt
Checking log log5.txt
90

How to process it using sed (or any other tool), so it will look like this:

$ cat text.txt
Checking log log0.txt
12
Checking log log2.txt
34
56
78
Checking log log5.txt
90

Pattern is "Checking"

Update:
If last line has "Checking" pattern, it should be removed as well.

Body: sed 'N;/^[^0-9].*\n[^0-9]/!P;D'