问:
Create a new Google Maps after Ajax success with Django

I have made a Google Maps with dive location in the Netherlands. The next step is that an user can search on the page for a dive location and that the search results are showing on the Google Maps. So it must replace the exisitng map.

I'm a new to Django and never worked with Javascript before. The problem is that I don't know how to make a new map with dive locations that are getting back from the search result.

Urls.py

```<code>from django.conf.urls import url
from . import views

app_name = 'kaart'

urlpatterns = [
    # /gis
    url(r'^$', views.index, name='index'),

    # Voor ajax zoekfunctie
    url(r'^search/$', views.search_duik_locaties, name='search_duik_locaties'),

    # /gis/id_number/
    url(r'^(?P<duik_id>[0-9]+)/$', views.detail, name='detail'),

]
</code>```

views.py

```<code>from django.shortcuts import render, get_object_or_404
from .models import Duikplaats

def index(request):
    all_duik_locaties = Duikplaats.objects.all()
    longitude = Duikplaats.objects.values('longitude')
    latitude = Duikplaats.objects.values('latitude')

    content = {
        'all_duik_locaties': all_duik_locaties,
        'longitude': longitude,
        'latitude': latitude,
    }
    return render(request, 'kaart/index.html', content)

def detail(request, duik_id):
    duikplaats = get_object_or_404(Duikplaats, pk=duik_id)
    return render(request, 'kaart/details.html', {'duikplaats': duikplaats})

def search_duik_locaties(request):
    query = request.GET.get('q')

    if query is not None and query != '' and request.is_ajax():
        zoek_duik_locaties = Duikplaats.objects.filter(duik_locatie__icontains=query)
        lat = zoek_duik_locaties.values('latitude')

        con = {
            'zoek_duik_locaties': zoek_duik_locaties,
            'lat': lat
        }

        return render(request, 'kaart/ajax_search.html', con)
    return render(request, 'kaart/ajax_search.html')
</code>```

index.html (part of the Ajxax Call)

```<code>    $('#search').keyup(function (event) {
      var query =($('#search').val());

          if (query != '' || query != ' ') {
            $.ajax({
               type: 'GET',
               url: '/gis/search',
               data: {
                 'csrfmiddlewaretoken': '{{ csrf_token }}',
                 'q': query
               },
{#                dataType: 'json',#}
               success: function(data) {
                  $('#search-results').html(data);
                  for (var i=0; i <markers.length; i++) {
                      markers[i].setMap(null);

                  }
                  markers = [];

               },
               error: function(data) {
                  console.log(data);
               }
             });
          }
        });
</code>```

ajax_search.html

```<code><ul id="results">
    {% for locatie in zoek_duik_locaties %}
        <li><a href="/gis/{{ locatie.id }}">{{ locatie.duik_locatie }}</a> </li>
        <p>{{ lat }}</p>
    {% endfor %}

</ul>
</code>```

I want that the map will update with the new markers. So that an user can see on the map where the dive location is where he searched for.

I got now a list of the dive location when the user search and the existing markers are gone but I don't get it done that the markers will update.

答:
I ran into the same problem, please let me share you the code for adding a marker via AJAX.

The following code updates via AJAX markers of interest depending of the user current location.

```<code>var map = new google.maps.Map(document.getElementById('map'),
var pos = {lat: position.coords.latitude,lng: position.coords.longitude};
function updatePosition()
    $.ajax({
    url: '/ajax/geo/',
    type: 'POST',
    data: {
      'csrfmiddlewaretoken': '{{ csrf_token }}',
      'pos': pos
    },
    dataType: 'json',
    success: function (outcome) {
        var locations = outcome;
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                icon : 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                position: new google.maps.LatLng(locations[i].Latitud, locations[i].Longitud),
                map: map
            });
</code>```

The views of ajax/geo looks the following:

```<code>def ajaxGeo(request):
  data = request.POST
  lati = data.get('pos[lat]','')
  longi = data.get('pos[lng]','')
  # EDIT: Only for prototyping
  model = Locacion.objects.filter(Latitud__lte=float(lati)+0.001)
  model = model.filter(Latitud__gte=float(lati)-0.001)
  model = model.filter(Longitud__lte=float(longi)+0.001)
  model = model.filter(Longitud__gte=float(longi)-0.001)
  outcome =[]
  for m in model:
    outcome.append(model_to_dict(m))
  return JsonResponse(outcome, safe=False)
</code>```

For what I am seeing from your code you are entirely missing your view from where the AJAX get its response. And you will need as well to modify your function to add markers.

Note: If you want an entirely new map for prototyping I would best be suited to reload the web page, only afterwards optimize your API quota usage and UX.

Body:
I have made a Google Maps with dive location in the Netherlands. The next step is that an user can search on the page for a dive location and that the search results are showing on the Google Maps. So it must replace the exisitng map.

I'm a new to Django and never worked with Javascript before. The problem is that I don't know how to make a new map with dive locations that are getting back from the search result.

Urls.py

from django.conf.urls import url
from . import views

app_name = 'kaart'

urlpatterns = [
    # /gis
    url(r'^$', views.index, name='index'),

    # Voor ajax zoekfunctie
    url(r'^search/$', views.search_duik_locaties, name='search_duik_locaties'),

    # /gis/id_number/
    url(r'^(?P<duik_id>[0-9]+)/$', views.detail, name='detail'),

]

views.py

from django.shortcuts import render, get_object_or_404
from .models import Duikplaats

def index(request):
    all_duik_locaties = Duikplaats.objects.all()
    longitude = Duikplaats.objects.values('longitude')
    latitude = Duikplaats.objects.values('latitude')

    content = {
        'all_duik_locaties': all_duik_locaties,
        'longitude': longitude,
        'latitude': latitude,
    }
    return render(request, 'kaart/index.html', content)

def detail(request, duik_id):
    duikplaats = get_object_or_404(Duikplaats, pk=duik_id)
    return render(request, 'kaart/details.html', {'duikplaats': duikplaats})

def search_duik_locaties(request):
    query = request.GET.get('q')

    if query is not None and query != '' and request.is_ajax():
        zoek_duik_locaties = Duikplaats.objects.filter(duik_locatie__icontains=query)
        lat = zoek_duik_locaties.values('latitude')

        con = {
            'zoek_duik_locaties': zoek_duik_locaties,
            'lat': lat
        }

        return render(request, 'kaart/ajax_search.html', con)
    return render(request, 'kaart/ajax_search.html')

index.html (part of the Ajxax Call)

    $('#search').keyup(function (event) {
      var query =($('#search').val());

          if (query != '' || query != ' ') {
            $.ajax({
               type: 'GET',
               url: '/gis/search',
               data: {
                 'csrfmiddlewaretoken': '{{ csrf_token }}',
                 'q': query
               },
{#                dataType: 'json',#}
               success: function(data) {
                  $('#search-results').html(data);
                  for (var i=0; i <markers.length; i++) {
                      markers[i].setMap(null);

                  }
                  markers = [];

               },
               error: function(data) {
                  console.log(data);
               }
             });
          }
        });

ajax_search.html

    {% for locatie in zoek_duik_locaties %}

{{ locatie.duik_locatie }}

{{ lat }}

    {% endfor %}

I want that the map will update with the new markers. So that an user can see on the map where the dive location is where he searched for.

I got now a list of the dive location when the user search and the existing markers are gone but I don't get it done that the markers will update.

Body:
I ran into the same problem, please let me share you the code for adding a marker via AJAX.

The following code updates via AJAX markers of interest depending of the user current location.

var map = new google.maps.Map(document.getElementById('map'),
var pos = {lat: position.coords.latitude,lng: position.coords.longitude};
function updatePosition()
    $.ajax({
    url: '/ajax/geo/',
    type: 'POST',
    data: {
      'csrfmiddlewaretoken': '{{ csrf_token }}',
      'pos': pos
    },
    dataType: 'json',
    success: function (outcome) {
        var locations = outcome;
        for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
                icon : 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
                position: new google.maps.LatLng(locations[i].Latitud, locations[i].Longitud),
                map: map
            });

The views of ajax/geo looks the following:

def ajaxGeo(request):
  data = request.POST
  lati = data.get('pos[lat]','')
  longi = data.get('pos[lng]','')
  # EDIT: Only for prototyping
  model = Locacion.objects.filter(Latitud__lte=float(lati)+0.001)
  model = model.filter(Latitud__gte=float(lati)-0.001)
  model = model.filter(Longitud__lte=float(longi)+0.001)
  model = model.filter(Longitud__gte=float(longi)-0.001)
  outcome =[]
  for m in model:
    outcome.append(model_to_dict(m))
  return JsonResponse(outcome, safe=False)

For what I am seeing from your code you are entirely missing your view from where the AJAX get its response. And you will need as well to modify your function to add markers.

Note: If you want an entirely new map for prototyping I would best be suited to reload the web page, only afterwards optimize your API quota usage and UX.


来源: stackexchange

问:
Appending predicted residuals and rsquared to pandas dataframe - by groups
There is a question like this already but I want modifications and have tried few methods without much luck.

I have data and want to add the R squared of a regression by groups as a seperate column in the pandas dataframe. The caveat here is I only want to do the regression on values which do not have a extreme residual values within each group (ie, within 1 standard deviations or between -1 and 1 z score).

Here is the SAMPLE data frame:

```<code>df = pd.DataFrame({'gp': [1,1,1,1,1,2,2,2,2,2],
               'x1': [3.17, 4.76, 4.17, 8.70, 11.45, 3.17, 4.76, 4.17, 8.70, 1.45],
               'x2': [23, 26, 73, 72, 16, 26, 73, 72, 16, 25],
               'y': [880.37, 716.20, 974.79, 322.80, 1054.25, 980.37, 816.20, 1074.79, 522.80, 1254.25]},
               index=np.arange(10, 30, 2))
</code>```

Now the answer which was on another post is such which works for me to get residuals in the group. This was the solution:

```<code>import pandas as pd
import numpy as np
import statsmodels.formula.api as sm

regmodel = 'y ~ x1 + x2'

def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid
    return g

df = df.groupby('gp').apply(groupreg)
print(df)
</code>```

Now this is great because I have a column residuals which gives the residual of the linear regression within each group.

However now I want to add another column which is R squared, where I want to add the R squared of the regression within each group only for the points where the residual is within +1/-1 zscore within within each group. So the goal is to add a R-squared which is stripping out extreme outliers in the regression (this should improve the R-squared values of a normal R-squared using all the data). Any help would be appreciated.

Edit**

FYI to add just a normal R squared the function would be this:

```<code>def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid
    g['rsquared'] = sm.ols(formula=regmodel, data=g).fit().rsquared
   return g
</code>```

EDIT 2 **

Here is my code:

```<code>import pandas as pd
import numpy as np
import statsmodels.formula.api as sm

df = pd.DataFrame({'gp': [1,1,1,1,1,2,2,2,2,2],
               'x1': [3.17, 4.76, 4.17, 8.70, 11.45, 3.17, 4.76, 4.17, 8.70, 1.45],
               'x2': [23, 26, 73, 72, 16, 26, 73, 72, 16, 25],
               'y': [880.37, 716.20, 974.79, 322.80, 1054.25, 980.37, 816.20, 1074.79, 522.80, 1254.25]},
               index=np.arange(10, 30, 2))

regmodel = 'y ~ x1 + x2'

def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid

    return g

df = df.groupby('gp').apply(groupreg)
print(df)

df['z_score'] = df.groupby('gp')['residual'].apply(lambda x: (x - x.mean())/x.std())
</code>```

Output:

```<code>    gp     x1  x2        y    residual   z_score
10   1   3.17  23   880.37  -43.579309 -0.173726
12   1   4.76  26   716.20 -174.532201 -0.695759
14   1   4.17  73   974.79  318.634921  1.270214
16   1   8.70  72   322.80 -287.710952 -1.146938
18   1  11.45  16  1054.25  187.187542  0.746209
20   2   3.17  26   980.37  -67.245089 -0.822329
22   2   4.76  73   816.20  -96.883281 -1.184770
24   2   4.17  72  1074.79  104.400010  1.276691
26   2   8.70  16   522.80   21.017543  0.257020
28   2   1.45  25  1254.25   38.710817  0.473388
</code>```

So Here I would like another column of R squared per group whilst not using the points which have a z-score greater and less than 1 and -1 respectively (eg would not use index 14, 16, 22 and 24 in the group by r square calculation.

ContentLicense: CC BY-SA 3.0

Body:
There is a question like this already but I want modifications and have tried few methods without much luck.

I have data and want to add the R squared of a regression by groups as a seperate column in the pandas dataframe. The caveat here is I only want to do the regression on values which do not have a extreme residual values within each group (ie, within 1 standard deviations or between -1 and 1 z score).

Here is the SAMPLE data frame:

df = pd.DataFrame({'gp': [1,1,1,1,1,2,2,2,2,2],
               'x1': [3.17, 4.76, 4.17, 8.70, 11.45, 3.17, 4.76, 4.17, 8.70, 1.45],
               'x2': [23, 26, 73, 72, 16, 26, 73, 72, 16, 25],
               'y': [880.37, 716.20, 974.79, 322.80, 1054.25, 980.37, 816.20, 1074.79, 522.80, 1254.25]},
               index=np.arange(10, 30, 2))

Now the answer which was on another post is such which works for me to get residuals in the group. This was the solution:

import pandas as pd
import numpy as np
import statsmodels.formula.api as sm

regmodel = 'y ~ x1 + x2'

def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid
    return g

df = df.groupby('gp').apply(groupreg)
print(df)

Now this is great because I have a column residuals which gives the residual of the linear regression within each group.

However now I want to add another column which is R squared, where I want to add the R squared of the regression within each group only for the points where the residual is within +1/-1 zscore within within each group. So the goal is to add a R-squared which is stripping out extreme outliers in the regression (this should improve the R-squared values of a normal R-squared using all the data). Any help would be appreciated.

Edit**

FYI to add just a normal R squared the function would be this:

def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid
    g['rsquared'] = sm.ols(formula=regmodel, data=g).fit().rsquared
   return g

EDIT 2 **

Here is my code:

import pandas as pd
import numpy as np
import statsmodels.formula.api as sm

df = pd.DataFrame({'gp': [1,1,1,1,1,2,2,2,2,2],
               'x1': [3.17, 4.76, 4.17, 8.70, 11.45, 3.17, 4.76, 4.17, 8.70, 1.45],
               'x2': [23, 26, 73, 72, 16, 26, 73, 72, 16, 25],
               'y': [880.37, 716.20, 974.79, 322.80, 1054.25, 980.37, 816.20, 1074.79, 522.80, 1254.25]},
               index=np.arange(10, 30, 2))

regmodel = 'y ~ x1 + x2'

def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid

    return g

df = df.groupby('gp').apply(groupreg)
print(df)

df['z_score'] = df.groupby('gp')['residual'].apply(lambda x: (x - x.mean())/x.std())

Output:

    gp     x1  x2        y    residual   z_score
10   1   3.17  23   880.37  -43.579309 -0.173726
12   1   4.76  26   716.20 -174.532201 -0.695759
14   1   4.17  73   974.79  318.634921  1.270214
16   1   8.70  72   322.80 -287.710952 -1.146938
18   1  11.45  16  1054.25  187.187542  0.746209
20   2   3.17  26   980.37  -67.245089 -0.822329
22   2   4.76  73   816.20  -96.883281 -1.184770
24   2   4.17  72  1074.79  104.400010  1.276691
26   2   8.70  16   522.80   21.017543  0.257020
28   2   1.45  25  1254.25   38.710817  0.473388

So Here I would like another column of R squared per group whilst not using the points which have a z-score greater and less than 1 and -1 respectively (eg would not use index 14, 16, 22 and 24 in the group by r square calculation.

Body:
First, use your full definition of groupreg that assigns both resid and rsquared columns:

def groupreg(g):
    g['residual'] = sm.ols(formula=regmodel, data=g).fit().resid
    g['rsquared'] = sm.ols(formula=regmodel, data=g).fit().rsquared
   return g

Then, at the very end of your current code (after creating the z_score column), try the following to delete the rsquared entries in rows where -1 < z_score < 1:

df.loc[df['z_score'].abs() < 1, 'rsquared'] = np.NaN

Output:

    gp     x1  x2        y    residual  rsquared   z_score
10   1   3.17  23   880.37  -43.579309       NaN -0.173726
12   1   4.76  26   716.20 -174.532201       NaN -0.695759
14   1   4.17  73   974.79  318.634921  0.250573  1.270214
16   1   8.70  72   322.80 -287.710952  0.250573 -1.146938
18   1  11.45  16  1054.25  187.187542       NaN  0.746209
20   2   3.17  26   980.37  -67.245089       NaN -0.822329
22   2   4.76  73   816.20  -96.883281  0.912987 -1.184770
24   2   4.17  72  1074.79  104.400010  0.912987  1.276691
26   2   8.70  16   522.80   21.017543       NaN  0.257020
28   2   1.45  25  1254.25   38.710817       NaN  0.473388


问:
for loop condition in 2nd clause and no condition in 3rd clause
```<code>for(i=5;--i;)
 printf("%d ",i);
</code>```

The output I am getting is proper which is 4 3 2 1. There is no i>0 condition in 3rd clause, so how is loop stopping when i=0?

答:
You didn't noticed that your loop start from 4 instead of 5!

In for statement

```<code>for (expr1;expr2;expr3)
</code>```

expr1 executes on the start of loop and will never execute during the iterations

expr2 is checked for true or any-none-zero-value; before every iteration if this expression is false or 0 the loop will be stopped.

and expr3 is executed after the completion of an iteration.

so in your case you don't have any third expression and the second expression which is checked for 0 or false will eventually become zero after four iterations

Body:
for(i=5;--i;)
 printf("%d ",i);

The output I am getting is proper which is 4 3 2 1. There is no i>0 condition in 3rd clause, so how is loop stopping when i=0?

Body:
You didn't noticed that your loop start from 4 instead of 5!

In for statement

for (expr1;expr2;expr3)

expr1 executes on the start of loop and will never execute during the iterations

expr2 is checked for true or any-none-zero-value; before every iteration if this expression is false or 0 the loop will be stopped.

and expr3 is executed after the completion of an iteration.

so in your case you don't have any third expression and the second expression which is checked for 0 or false will eventually become zero after four iterations


问:
Redirecting the link without click
Sorry if it seems a stupid noob question, but I can't understand why this page gets me to new page without a single mouse click after loading in Chrome. I am trying to make clicking on google link to get another page... Thanks!</p>

```<code><!DOCTYPE html>
<html>
<head>

</head>
<body>
<h1>3 JS</h1>
<a id="googlelink" href="https://www.google.com">Google</a>
<hr>
<a href="https://www.google.com">Google</a>
<hr>
</body>
</html>

<script>
document.getElementById("googlelink").addEventListener("click", redirectToYahoo());
document.getElementById("googlelink").addEventListener("auxclick", redirectToYahooNewTab());

 function redirectToYahoo() {
    window.location.href = "https://www.yahoo.com";
  }

 function redirectToYahooNewTab() {
    window.open('https://www.yahoo.com', '_blank');
 }

</script>
</code>```

答:
It appears that in your addEventListener call you are executing the redirection function instead of passing it as parameter to addEventListener. Should be:

```<code>addEventListener("click", redirectToYahoo);
</code>```

without parenthesis to avoid calling it during page load.

Title: Redirecting the link without click

Body:
Sorry if it seems a stupid noob question, but I can't understand why this page gets me to new page without a single mouse click after loading in Chrome. I am trying to make clicking on google link to get another page... Thanks!

<!DOCTYPE html>

3 JS

Google

Google

Body:
It appears that in your addEventListener call you are executing the redirection function instead of passing it as parameter to addEventListener. Should be:

addEventListener("click", redirectToYahoo);

without parenthesis to avoid calling it during page load.


问:
Java: Testing Concrete Class passing by Interface, Mockito, JUnit
I have this interface:

```<code>public interface RepositoryUserDB {

    User createUser(User user);
}
</code>```

and the method implemented into the following class:

```<code>public class MemoryUserDB implements RepositoryUserDB{

    Map<String, User> repo = new HashMap<>();

    @Override
    public User createUser(User user) {
        return repo.put(user.getUsername(), user);
    }
}
</code>```

The target is to test the method. I started to write this, but I think it is not correct:

```<code>@Test
public void testCreateUser(){
    User result = new User("luca", "antico", "23.11.2011", "112");
    Assert.assertEquals("luca", result.getUsername());
}
</code>```

How can I accomplish it?

Thanks

edit:

the class User:

```<code> public class User {

    private String username;
    private String password;
    private String dateOfBirth;
    private String SSN;

    public User(String username, String password, String dateOfBirth, String SSN) {
        this.username = username;
        this.password = password;
        this.dateOfBirth = dateOfBirth;
        this.SSN = SSN;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public String getSSN() {
        return SSN;
    }
}
</code>```

答:
Frankly, that test does not add much of a value.

What you should aim for is to verify whether the repo contains the user that you have passed through that method.

Assuming you have some kind of getByUserName method on that repo, and the User class has equals and hashCode properly defined, you could go for a test like this:

```<code>private MemoryUserDB memoryUserDB;

@Test
public void shouldCreateUser(){
   // Arrange
   User user = new User("luca", "antico", "23.11.2011", "112");

   // Act
   User addedUser = memoryUserDB.createUser(user);

   // Assert
   assertEquals(user, addedUser);
   assertEquals(user, memoryUserDB.getByUsername("luca");
}
</code>```

Also try not to put test in your test method names, try to explain the bahavior through the name.

Body:
I have this interface:

public interface RepositoryUserDB {

    User createUser(User user);
}

and the method implemented into the following class:

public class MemoryUserDB implements RepositoryUserDB{

    Map<String, User> repo = new HashMap<>();

    @Override
    public User createUser(User user) {
        return repo.put(user.getUsername(), user);
    }
}

The target is to test the method. I started to write this, but I think it is not correct:

@Test
public void testCreateUser(){
    User result = new User("luca", "antico", "23.11.2011", "112");
    Assert.assertEquals("luca", result.getUsername());
}

How can I accomplish it?

Thanks

edit:

the class User:

 public class User {

    private String username;
    private String password;
    private String dateOfBirth;
    private String SSN;

    public User(String username, String password, String dateOfBirth, String SSN) {
        this.username = username;
        this.password = password;
        this.dateOfBirth = dateOfBirth;
        this.SSN = SSN;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public String getSSN() {
        return SSN;
    }
}

Body:
Frankly, that test does not add much of a value.

What you should aim for is to verify whether the repo contains the user that you have passed through that method.

Assuming you have some kind of getByUserName method on that repo, and the User class has equals and hashCode properly defined, you could go for a test like this:

private MemoryUserDB memoryUserDB;

@Test
public void shouldCreateUser(){
   // Arrange
   User user = new User("luca", "antico", "23.11.2011", "112");

   // Act
   User addedUser = memoryUserDB.createUser(user);

   // Assert
   assertEquals(user, addedUser);
   assertEquals(user, memoryUserDB.getByUsername("luca");
}

Also try not to put test in your test method names, try to explain the bahavior through the name.


问:
Dynamically updating a specific view in a RecyclerView
I'm currently working on android using RecyclerView, let's say I have 2 TextView in my custom row, I wanted to dynamically change the text of one in the TextView, how can I do that?

I do have the following code in my MainActivity

```<code>public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AdaptersOnline adaptersOnline;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<ModelClientInformation> modelOnlineLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();

        mLayoutManager = new LinearLayoutManager(this);
        adaptersOnline = new AdaptersOnline(this, modelOnlineLists);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adaptersOnline);
    }

    //call this to new row
    public void initializeClient(String id, String data1, String data2){
        this.modelOnlineLists.add(new ModelClientInformation(id, data1, data2));
        adaptersOnline.notifyDataSetChanged();
    }

    //Call this method to update textview
    public void updateSpecificViewItem(String theID){
         //get position base on the ID
         adaptersOnline.updateTextView(
         adaptersOnline.getPositionBaseOnItemID(theID));
    }

}
</code>```

in my Adapter Class

```<code>public class AdaptersOnline extends RecyclerView.Adapter<AdaptersOnline.TheViewHolder> {
    Context mContext;
    public List<ModelClientInformation> onlineList;

    public AdaptersOnline(Context mContext, List<ModelClientInformation> modelOnlineList){
        this.mContext = mContext;
        this.onlineList = modelOnlineList;
    }

    public class TheViewHolder extends RecyclerView.ViewHolder {

        TextView text1, text2;

        public TheViewHolder(View view) {
            super(view);

            text1 = (TextView)view.findViewById(R.id.text1);
            text2 = (TextView)view.findViewById(R.id.text2);
        }
    }

    @Override
    public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_row, parent, false);
        return new TheViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(TheViewHolder holder, int position) {
        final ModelClientInformation info = onlineList.get(position);

        holder.text1.setText(holder.getText1());
        holder.text1.setText(holder.getText2());
    }

    /**Function to Return the size of List**/
    @Override
    public int getItemCount() {
        return onlineList.size();
    }

    /**Function to Clear the List**/
    public void clear(){
        onlineList.clear();
    }

    /**Possibly way to update one of the TextView here**/
    public void updateTextView(int position){
        //what should I do to update the TextView
    }

    /*Get the position of item inside data list base on the given ID*/
    public int getPositionBaseOnItemID(String theID) {

    int length = onlineList.size();
    for (int i = 0; i < length; i ++) {
        if(onlineList.get(i).getItemID().equals(theID)) {
            return i;
        }
    }
    return -1; //Item not found
}
}
</code>```

and the Pojo

```<code>public ModelClientInformation class{

    private String theID, text1, text2;

    public ModelClientInformation(String theID, String text1, String text2){
        this.theID = theID;
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getItemID(){
        return theID;
    }

    public String getText1(){
        return text1;
    }

    public String getText2(){
        return text2;
    }

}
</code>```

I'm don't have any idea to do it. . .
Anyone can help me?

UPDATE:

Please look at my changes,

1: I want to update one of the TextView inside MainActivity class by calling updateSpecificViewItem("theID").

2: Get the position of the item base on the given id by calling getPositionBaseOnItemID("theID").

3: To finally update the specific item, I want to call updateTextView(int position) method.

the only problem I'm facing right now is the number 3, how can I update only the text2 and not the entire item?

答:
In your adapter,

```<code>String textToUpdate;

@Override
public void onBindViewHolder(TheViewHolder holder, int position) {
    final ModelClientInformation info = onlineList.get(position);

    holder.text1.setText(holder.getText1());// update the textview u want by setting the "textToUpdate" variable
    holder.text1.setText(holder.getText2());
}

public void updateTextView(String text){
    textToUpdate = text;
    notifyDatasetChanged();
}
</code>```

Hope it helps !

Body:
I'm currently working on android using RecyclerView, let's say I have 2 TextView in my custom row, I wanted to dynamically change the text of one in the TextView, how can I do that?

I do have the following code in my MainActivity

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AdaptersOnline adaptersOnline;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<ModelClientInformation> modelOnlineLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = getApplicationContext();

        mLayoutManager = new LinearLayoutManager(this);
        adaptersOnline = new AdaptersOnline(this, modelOnlineLists);
        recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adaptersOnline);
    }

    //call this to new row
    public void initializeClient(String id, String data1, String data2){
        this.modelOnlineLists.add(new ModelClientInformation(id, data1, data2));
        adaptersOnline.notifyDataSetChanged();
    }

    //Call this method to update textview
    public void updateSpecificViewItem(String theID){
         //get position base on the ID
         adaptersOnline.updateTextView(
         adaptersOnline.getPositionBaseOnItemID(theID));
    }

}

in my Adapter Class

public class AdaptersOnline extends RecyclerView.Adapter<AdaptersOnline.TheViewHolder> {
    Context mContext;
    public List<ModelClientInformation> onlineList;

    public AdaptersOnline(Context mContext, List<ModelClientInformation> modelOnlineList){
        this.mContext = mContext;
        this.onlineList = modelOnlineList;
    }

    public class TheViewHolder extends RecyclerView.ViewHolder {

        TextView text1, text2;

        public TheViewHolder(View view) {
            super(view);

            text1 = (TextView)view.findViewById(R.id.text1);
            text2 = (TextView)view.findViewById(R.id.text2);
        }
    }

    @Override
    public TheViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.recyclerview_row, parent, false);
        return new TheViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(TheViewHolder holder, int position) {
        final ModelClientInformation info = onlineList.get(position);

        holder.text1.setText(holder.getText1());
        holder.text1.setText(holder.getText2());
    }

    /**Function to Return the size of List**/
    @Override
    public int getItemCount() {
        return onlineList.size();
    }

    /**Function to Clear the List**/
    public void clear(){
        onlineList.clear();
    }

    /**Possibly way to update one of the TextView here**/
    public void updateTextView(int position){
        //what should I do to update the TextView
    }

    /*Get the position of item inside data list base on the given ID*/
    public int getPositionBaseOnItemID(String theID) {

    int length = onlineList.size();
    for (int i = 0; i < length; i ++) {
        if(onlineList.get(i).getItemID().equals(theID)) {
            return i;
        }
    }
    return -1; //Item not found
}
}

and the Pojo

public ModelClientInformation class{

    private String theID, text1, text2;

    public ModelClientInformation(String theID, String text1, String text2){
        this.theID = theID;
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getItemID(){
        return theID;
    }

    public String getText1(){
        return text1;
    }

    public String getText2(){
        return text2;
    }

}

I'm don't have any idea to do it. . .
Anyone can help me?

UPDATE:

Please look at my changes,

1: I want to update one of the TextView inside MainActivity class by calling updateSpecificViewItem("theID").

2: Get the position of the item base on the given id by calling getPositionBaseOnItemID("theID").

3: To finally update the specific item, I want to call updateTextView(int position) method.

the only problem I'm facing right now is the number 3, how can I update only the text2 and not the entire item?

Body:
In your adapter,

String textToUpdate;

@Override
public void onBindViewHolder(TheViewHolder holder, int position) {
    final ModelClientInformation info = onlineList.get(position);

    holder.text1.setText(holder.getText1());// update the textview u want by setting the "textToUpdate" variable
    holder.text1.setText(holder.getText2());
}

public void updateTextView(String text){
    textToUpdate = text;
    notifyDatasetChanged();
}

Hope it helps !


问:
Processing/Java pixel array slicing assignment
I'm am using processing / Java and i am using the pixel array to assign a color to every pixel,  but the framerate is way too low if I assign every pixel so I want to treat a block of 5 pixels as one, so make them the same color.   I am nog doing this,      </p>

```<code>for (int x = 0; x < width; x += 5) {
    // for loop width
    for (int y = 0; y < height; y += 5) {
        // For loop height
        // Assigning pixel color
        for (int px = 0; px < 5; px++) {
            for (int py = 0; py < 5; py++) {
                pixels[x + px + (y + py) * width] = color(myCol);
            }
        }
    }
}
</code>```

<p>but I wanted to know if I can assign a slice of the array something like this </p>

```<code>pixels[startIndex : endIndex] = color(myColor);
</code>```

答:
Processing does have a set() function that takes an image parameter. From the reference:

```<code>size(100, 100);
PImage myImage = loadImage("apples.jpg");
set(0, 0, myImage);
line(0, 0, width, height);
line(0, height, width, 0);
</code>```

(source: processing.org)

You could put your color into an image, and then draw the image. I don't know whether this will be any faster or not.

Another option would be to simply resize the input image at startup.

Body:
I'm am using processing / Java and i am using the pixel array to assign a color to every pixel,  but the framerate is way too low if I assign every pixel so I want to treat a block of 5 pixels as one, so make them the same color.   I am nog doing this,

for (int x = 0; x < width; x += 5) {
    // for loop width
    for (int y = 0; y < height; y += 5) {
        // For loop height
        // Assigning pixel color
        for (int px = 0; px < 5; px++) {
            for (int py = 0; py < 5; py++) {
                pixels[x + px + (y + py) * width] = color(myCol);
            }
        }
    }
}

but I wanted to know if I can assign a slice of the array something like this

pixels[startIndex : endIndex] = color(myColor);

Body:
Processing does have a set() function that takes an image parameter. From the reference:

size(100, 100);
PImage myImage = loadImage("apples.jpg");
set(0, 0, myImage);
line(0, 0, width, height);
line(0, height, width, 0);

(source: processing.org)

You could put your color into an image, and then draw the image. I don't know whether this will be any faster or not.

Another option would be to simply resize the input image at startup.

ContentLicense: CC BY-SA 4.0


问:
Unable to store parsed items as dictionary
I've written a tiny script in python using BeautifulSoup to parse some items out of some element stored within content variable within the below script. I do not wish to append items to the previously created empty dictionary; rather, i wish to parse it on the fly. However, I tried but could not achieve that. Any help would be highly appreciated.

This is my attempt:

```<code>from bs4 import BeautifulSoup

content="""
<table class="data">
    <tbody>
        <tr class="blue">
            <td>hot</td>
            <td>cold</td>
        </tr>
        <tr>
            <td>day</td>
            <td>night</td>
        </tr>
    </tbody>
</table>
"""
soup = BeautifulSoup(content,'lxml')
for items in soup.select('tr'):
    data = [item.text for item in items.select("td")]
    dict_val = {data[0] : data[1]}
    print(dict_val)
</code>```

The way I'm getting the output:

```<code>{'hot': 'cold'}
{'day': 'night'}
</code>```

The way I expect to have the output:

```<code>{'hot': 'cold','day': 'night'}
</code>```

答:
Remember that a computer will only do exactly what you tell it to. Your original code has this line:

```<code>dict_val = {data[0] : data[1]}
</code>```

This creates a new dictionary every time the loop iterates. If instead, you want to create a single dictionary and add elements to it, you need to do just that. Often it helps to write out the steps in words:

```<code>create a dictionary
for each row in the table:
    parse the <td> elements from the row
    add an entry to the dictionary
</code>```

Most of this you have already translated into Python. The key differences are where the dictionary is created and how the data from the HTML is inserted into the dictionary. I will leave the details of how to do this in Python as an exercise. (Hint: look at the other answer.) The important thing here is thinking clearly about the order of the steps you want to perform and then figuring out how to do it in Python.

Body:
I've written a tiny script in python using BeautifulSoup to parse some items out of some element stored within content variable within the below script. I do not wish to append items to the previously created empty dictionary; rather, i wish to parse it on the fly. However, I tried but could not achieve that. Any help would be highly appreciated.

This is my attempt:

from bs4 import BeautifulSoup

content="""

            hot
            cold

            day
            night

"""
soup = BeautifulSoup(content,'lxml')
for items in soup.select('tr'):
    data = [item.text for item in items.select("td")]
    dict_val = {data[0] : data[1]}
    print(dict_val)

The way I'm getting the output:

{'hot': 'cold'}
{'day': 'night'}

The way I expect to have the output:

{'hot': 'cold','day': 'night'}

Body:
Remember that a computer will only do exactly what you tell it to. Your original code has this line:

dict_val = {data[0] : data[1]}

This creates a new dictionary every time the loop iterates. If instead, you want to create a single dictionary and add elements to it, you need to do just that. Often it helps to write out the steps in words:

create a dictionary
for each row in the table:
    parse the <td> elements from the row
    add an entry to the dictionary

Most of this you have already translated into Python. The key differences are where the dictionary is created and how the data from the HTML is inserted into the dictionary. I will leave the details of how to do this in Python as an exercise. (Hint: look at the other answer.) The important thing here is thinking clearly about the order of the steps you want to perform and then figuring out how to do it in Python.


问:
add combobox to mainwindow
I created a Main window with 2 button by pyqt5 and now i want to add a combo box to it. But if i keep App(QMainWindow), the combo box wont show. Only if i write App(QWidgets) it will show. Are there any way to add a combo box to main window ? here is my code:</p>

```<code>class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Phan mem quan ly tai lieu- Tuan tien mom'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('chaychuongtrinh', self)
        button.setToolTip('bam vao nut nay de chay chuong trinh')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        button1 = QPushButton('kiemtra', self)
        button1.setToolTip('kiem tra thong tin')
        button1.move(200, 70)
        button1.clicked.connect(self.on_click)

        layout = QHBoxLayout()
        self.cb = QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        layout.addWidget(self.cb)
        self.setLayout(layout)
        self.setWindowTitle("combo box demo")
        self.show()
    def selectionchange(self,i):
        print ("Items in the list are :")
        print(self.cb.currentText())
</code>```

答:
Every widget needs parent.

For QPushButton you used self as parent. For QComboBox use self as parent too

```<code>self.cb = QComboBox(self)
</code>```

Title: add combobox to mainwindow

Body:
I created a Main window with 2 button by pyqt5 and now i want to add a combo box to it. But if i keep App(QMainWindow), the combo box wont show. Only if i write App(QWidgets) it will show. Are there any way to add a combo box to main window ? here is my code:

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Phan mem quan ly tai lieu- Tuan tien mom'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('chaychuongtrinh', self)
        button.setToolTip('bam vao nut nay de chay chuong trinh')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        button1 = QPushButton('kiemtra', self)
        button1.setToolTip('kiem tra thong tin')
        button1.move(200, 70)
        button1.clicked.connect(self.on_click)

        layout = QHBoxLayout()
        self.cb = QComboBox()
        self.cb.addItem("C")
        self.cb.addItem("C++")
        self.cb.addItems(["Java", "C#", "Python"])
        self.cb.currentIndexChanged.connect(self.selectionchange)
        layout.addWidget(self.cb)
        self.setLayout(layout)
        self.setWindowTitle("combo box demo")
        self.show()
    def selectionchange(self,i):
        print ("Items in the list are :")
        print(self.cb.currentText())

Body:
Every widget needs parent.

For QPushButton you used self as parent. For QComboBox use self as parent too

self.cb = QComboBox(self)


问:
Java: String not printed
I am reading some data from a file and each line is assigned to one cell of the String array. For some reason when I try to print the array after reading the file(lines 8-10), I get nothing printed. When I print the line in the While loop(line 5) I get the line printed correctly.

```<code>    1: int count = 0;
    2: String[] s = new String[300];

    3: while(!StdIn.isEmpty()) {
    4:  s[count]=StdIn.readLine();
    5:  System.out.println(s[count]);
    6:  count++;
    7: }

    8:  for(int i=0;i<count;i++) {
    9:   System.out.println(s[i]);
   10: }
</code>```

Same code using Scanner:

```<code>    Scanner in = new Scanner(System.in);

    int count = 0;
    String[] s = new String[300];

    while(in.hasNextLine()) {
        s[count]=in.nextLine();
        System.out.println(s[count]);
        count++;
    }
    for(int i=0;i<count;i++) {
        System.out.println(s[i]);
    }
</code>```

I can't figure out what's wrong with my code.

Thanks in advance.

EDIT: When the last line has been read, the in.hasNextLine() is not returning anything. It got stuck at the count++. See photo -> DEBUGGER

答:
```<code>8:  for(int i=0;i<count;i++) {
</code>```

here your error, this should be s.length instead of count

Title: Java: String not printed

Body:
I am reading some data from a file and each line is assigned to one cell of the String array. For some reason when I try to print the array after reading the file(lines 8-10), I get nothing printed. When I print the line in the While loop(line 5) I get the line printed correctly.

    1: int count = 0;
    2: String[] s = new String[300];

    3: while(!StdIn.isEmpty()) {
    4:  s[count]=StdIn.readLine();
    5:  System.out.println(s[count]);
    6:  count++;
    7: }

    8:  for(int i=0;i<count;i++) {
    9:   System.out.println(s[i]);
   10: }

Same code using Scanner:

    Scanner in = new Scanner(System.in);

    int count = 0;
    String[] s = new String[300];

    while(in.hasNextLine()) {
        s[count]=in.nextLine();
        System.out.println(s[count]);
        count++;
    }
    for(int i=0;i<count;i++) {
        System.out.println(s[i]);
    }

I can't figure out what's wrong with my code.

Thanks in advance.

EDIT: When the last line has been read, the in.hasNextLine() is not returning anything. It got stuck at the count++. See photo -> DEBUGGER

Body:
8:  for(int i=0;i<count;i++) {

here your error, this should be s.length instead of count


问:
svn add trunk/* not working
I'm using TortoiseSVN-1.9.7 and trying to upload my plugin files to wordpress svn of my plugin.

I'm on this folder:

```<code>C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg
</code>```

And then:

```<code>svn add trunk/*
</code>```

I got this in return:

```<code>svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: E200009: Could not add all targets because some targets don't exist
svn: E200009: Illegal target for the requested operation
</code>```

It doesn't make sense! I'm on the dotorg folder which has a trunk folder with my plugin files, also the https://plugins.svn.wordpress.org/my-plugin/ url shows me there is a trunk folder. So what I'm missing here?

答:
Try following commands:

```<code>svn cleanup
svn cleanup *
svn cleanup dotorg
svn add --force dotorg
svn commit
</code>```

If it still doesn't work then try this:

```<code>rm -rf dotorg/.svn
svn add dotorg
svn commit
</code>```

Title: svn add trunk/* not working

Body:
I'm using TortoiseSVN-1.9.7 and trying to upload my plugin files to wordpress svn of my plugin.

I'm on this folder:

C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg

And then:

svn add trunk/*

I got this in return:

svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: warning: W155010: The node 'C:\xampp\htdocs\wordpress\wp-content\plugins\my-plugin\dotorg' was not found.
svn: E200009: Could not add all targets because some targets don't exist
svn: E200009: Illegal target for the requested operation

It doesn't make sense! I'm on the dotorg folder which has a trunk folder with my plugin files, also the https://plugins.svn.wordpress.org/my-plugin/ url shows me there is a trunk folder. So what I'm missing here?

Body:
Try following commands:

svn cleanup
svn cleanup *
svn cleanup dotorg
svn add --force dotorg
svn commit

If it still doesn't work then try this:

rm -rf dotorg/.svn
svn add dotorg
svn commit


问:
Can Arduino relay module change the speed of fan?
I have a 240V fan connected to Arduino 5V relay. Is it possible to change the speed of fan from low to medium to high depends on the temperature?

I've tried to use the following code but I don't see my 240V fan changing the speed. It just turn on and off.

int fan = 13;
int fanSpeed;
int tempMin = 25;
int tempMax = 75;

void loop(){
if ((temp >= tempMin) && (temp <= tempMax)) {
    fanSpeed = map(temp, tempMin, tempMax, 32, 255);
    analogWrite(fan, fanSpeed);
  }
}
```

答: That's perfectly impossible!! It's as impossible as making your breakfast using a program without any hardware. Relay module can only turn things on or off. They can't alter the resistance. Firstly, you haven't defined temp. Moreover, since you are using PWM, this code can easily and conveniently destroy your relay module.


问:
Filtering JavaScript objects using values from multiple arrays
If I have array of objects.

```<code>var products = [{
       names: ["hammer", "nail", "rubber duck"],
       colors: ["yellow", "red", "pink"]
    },
    {
       names: ["saw", "tractor", "bowling ball"],
       colors: ["gray", "purple", "green"]
    }]
</code>```

Then I have object with arrays of filter values:

```<code>var filters = {names: ["saw", "bowling ball"], colors:["purple"]}
</code>```

I need to filter the objects so that if I've got no filters I get all objects back. If I've got any filter values in "names" I get objects back with matching names. If I've got any filter values in both "names" and "colors" I get objects back with matching values on both.

For example:

```<code>var filters = {names: ["saw", "bowling ball"], colors:["purple"]}
</code>```

would return

```<code>[{
names: ["saw", "tractor" "bowling ball"],
colors: ["gray", "purple", "green"]
}]
</code>```

答:
You can use array#filter to iterate through your products array and inside it you can check for existence of name and color using array#some and array#includes.

var products = [{ names: ["hammer", "nail", "rubber duck"], colors: ["yellow", "red", "pink"] }, { names: ["saw", "tractor", "bowling ball"],colors: ["gray", "purple", "green"] }],
    filters = {names: ["saw", "bowling ball"], colors:["purple"]};
var result = products.filter(({names, colors}) => {
  return filters.names.some(name => names.includes(name)) && filters.colors.some(color => colors.includes(color));
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
If I have array of objects.

var products = [{
       names: ["hammer", "nail", "rubber duck"],
       colors: ["yellow", "red", "pink"]
    },
    {
       names: ["saw", "tractor", "bowling ball"],
       colors: ["gray", "purple", "green"]
    }]

Then I have object with arrays of filter values:

var filters = {names: ["saw", "bowling ball"], colors:["purple"]}

I need to filter the objects so that if I've got no filters I get all objects back. If I've got any filter values in "names" I get objects back with matching names. If I've got any filter values in both "names" and "colors" I get objects back with matching values on both.

For example:

var filters = {names: ["saw", "bowling ball"], colors:["purple"]}

would return

[{
names: ["saw", "tractor" "bowling ball"],
colors: ["gray", "purple", "green"]
}]

Body:
You can use array#filter to iterate through your products array and inside it you can check for existence of name and color using array#some and array#includes.

var products = [{ names: ["hammer", "nail", "rubber duck"], colors: ["yellow", "red", "pink"] }, { names: ["saw", "tractor", "bowling ball"],colors: ["gray", "purple", "green"] }],
    filters = {names: ["saw", "bowling ball"], colors:["purple"]};
var result = products.filter(({names, colors}) => {
  return filters.names.some(name => names.includes(name)) && filters.colors.some(color => colors.includes(color));
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Error in Types for the reducers in TypeScript in React-Redux
I am using TypeScript for my React-Redux app. I have followed the TypeScript React Starter, however, the example mentioned there does not have any action methods that has some arguments/payload.

I have a simple requirement -

Show a list of names and when a button is clicked a new name is added. When another button is clicked 2 names are added.

The entry point for the app index.tsx looks like this -

```<code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { createStore } from 'redux';
import { StoreState } from './types';
import { listUsers } from './reducers';
import { Provider } from 'react-redux';
import ListUsers from './containers/ListUsers';

const store = createStore<StoreState>(listUsers, {
  'users': [
    {
      'id': 0,
      'firstName': 'Aniyah',
      'lastName': 'Luettgen',
      'phone': '861-332-5113',
      'email': 'Danika.Ryan84@yahoo.com',
      'role': 'admin'
    },
    {
      'id': 1,
      'firstName': 'Alisa',
      'lastName': 'Pacocha',
      'phone': '085-056-3901',
      'email': 'Eusebio68@yahoo.com',
      'role': 'admin'
    }
  ]
});

ReactDOM.render(
  <Provider store={store}>
    <ListUsers/>
  </Provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();
</code>```

The constants file (constants/index.tsx) looks like this -

```<code>export const LIST_USERS = 'LIST_USERS';
export type LIST_USERS = typeof LIST_USERS;

export const ADD_USER = 'ADD_USER';
export type ADD_USER = typeof ADD_USER;

export const ADD_USERS = 'ADD_USERS';
export type ADD_USERS = typeof ADD_USERS;
</code>```

The types (types/index.tsx) are -

```<code>export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export interface Action<T> {
  type: string;
  payload?: T;
}
</code>```

My Component (components/ListUsers.tsx) looks like this -

```<code>import * as React from 'react';
import { DispatchProps, ListUsersProps } from '../containers/ListUsers';
import { User } from '../types';

interface ListState {
  counter: number;
}

class ListUsers extends React.Component<ListUsersProps & DispatchProps, ListState> {

  constructor(props: ListUsersProps & DispatchProps) {
    super(props);

    this.addUser = this.addUser.bind(this);
    this.addMultipleUser = this.addMultipleUser.bind(this);

    this.state = {
      counter: 0
    };
  }

  render() {
    return (
      <div>
        <button onClick={() => this.addUser()}>Add User</button>
        <button onClick={() => this.addMultipleUser()}>Add User</button>
        {this.props.users.map((user: User) => (
          <div key={user.id}>{user.firstName}</div>
        ))}
      </div>
    );
  }

  private addUser() {
    this.props.addUser({
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    });
    this.setState({
      ...this.state,
      counter: this.state.counter + 1
    });
  }

  private addMultipleUser() {
    this.props.addUsers([{
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }, {
      id: this.state.counter,
      firstName: 'ijkl',
      lastName: 'mnop',
      email: 'ijkl@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }]);
    this.setState({
      ...this.state,
      counter: this.state.counter + 2
    });
  }
}

export default ListUsers;
</code>```

My container component (containers/ListUsers.tsx) looks like this -

```<code>import { connect, Dispatch } from 'react-redux';
import { Action, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): Action<User>;
  addUsers(users: Array<User>): Action<Array<User>>;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps, {}>(mapStateToProps, mapDispatchToProps)(ListUsers);
</code>```

Now here is the reducer where I am facing issues (reducers/index.tsx) -

```<code>import { Action, StoreState, User } from '../types';
import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export const listUsers = (state: StoreState, action: Action<User>): StoreState => {
  switch (action.type) {
    case LIST_USERS:
      return state;
    case ADD_USER:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, action.payload]
      };
    case ADD_USERS:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
      };
    default:
      return state;
  }
};
</code>```

Here the compiler says that in the reducers/index.tsx in

```<code>case ADD_USERS:
  return {
    ...state,
    users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
  };
</code>```

that action.payload is User and not Array<User> which is right (I have declared the reducer with type (state: StoreState, action: Action<User>)).

How do I work with this? If there isn't an alternative, I will have to write separate reducers for every ACTION that has a different payload which I think is bad.

The way I am using the DispatchProps type also looks very odd to me. I am trying to follow this for the types of mapStateToProps and mapDispatchToProps.

Is there any work around for this?

PS: I am using react, redux and react-redux libraries.

答:
I found a solution for this. I am not sure if it is right way to do this.

Instead of making the Action Type generic like so -

```<code>interface Action<T> {
  type: string;
  payload?: T;
}
</code>```

I created a Separate Action Type for each Action and then the Action Type accepted by the Reducer would be the | of them.

So, the types look like this (types/index.tsx) -

```<code>import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export type ListUsersAction = {type: typeof LIST_USERS};
export type AddUserAction = {type: typeof ADD_USER, payload: User};
export type AddUsersAction = {type: typeof ADD_USERS, payload: Array<User>};

export type Actions = ListUsersAction | AddUserAction | AddUsersAction;
</code>```

and the Container Component (containers/ListUsers.tsx) looks like this -

```<code>import { connect, Dispatch } from 'react-redux';
import { AddUserAction, AddUsersAction, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): AddUserAction;
  addUsers(users: Array<User>): AddUsersAction;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps>(mapStateToProps, mapDispatchToProps)(ListUsers);
</code>```

There are no compilation errors any more, and payload for both ADD_USER and ADD_USERS is received properly.

There is a recommendation to reduce the Action Type boilerplate here.

Body:
I am using TypeScript for my React-Redux app. I have followed the TypeScript React Starter, however, the example mentioned there does not have any action methods that has some arguments/payload.

I have a simple requirement -

Show a list of names and when a button is clicked a new name is added. When another button is clicked 2 names are added.

The entry point for the app index.tsx looks like this -

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { createStore } from 'redux';
import { StoreState } from './types';
import { listUsers } from './reducers';
import { Provider } from 'react-redux';
import ListUsers from './containers/ListUsers';

const store = createStore<StoreState>(listUsers, {
  'users': [
    {
      'id': 0,
      'firstName': 'Aniyah',
      'lastName': 'Luettgen',
      'phone': '861-332-5113',
      'email': 'Danika.Ryan84@yahoo.com',
      'role': 'admin'
    },
    {
      'id': 1,
      'firstName': 'Alisa',
      'lastName': 'Pacocha',
      'phone': '085-056-3901',
      'email': 'Eusebio68@yahoo.com',
      'role': 'admin'
    }
  ]
});

ReactDOM.render(
  <Provider store={store}>
    <ListUsers/>
  </Provider>,
  document.getElementById('root') as HTMLElement
);
registerServiceWorker();

The constants file (constants/index.tsx) looks like this -

export const LIST_USERS = 'LIST_USERS';
export type LIST_USERS = typeof LIST_USERS;

export const ADD_USER = 'ADD_USER';
export type ADD_USER = typeof ADD_USER;

export const ADD_USERS = 'ADD_USERS';
export type ADD_USERS = typeof ADD_USERS;

The types (types/index.tsx) are -

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export interface Action<T> {
  type: string;
  payload?: T;
}

My Component (components/ListUsers.tsx) looks like this -

import * as React from 'react';
import { DispatchProps, ListUsersProps } from '../containers/ListUsers';
import { User } from '../types';

interface ListState {
  counter: number;
}

class ListUsers extends React.Component<ListUsersProps & DispatchProps, ListState> {

  constructor(props: ListUsersProps & DispatchProps) {
    super(props);

    this.addUser = this.addUser.bind(this);
    this.addMultipleUser = this.addMultipleUser.bind(this);

    this.state = {
      counter: 0
    };
  }

  render() {
    return (

        <button onClick={() => this.addUser()}>Add User</button>
        <button onClick={() => this.addMultipleUser()}>Add User</button>
        {this.props.users.map((user: User) => (

{user.firstName}

        ))}

    );
  }

  private addUser() {
    this.props.addUser({
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    });
    this.setState({
      ...this.state,
      counter: this.state.counter + 1
    });
  }

  private addMultipleUser() {
    this.props.addUsers([{
      id: this.state.counter,
      firstName: 'abcd',
      lastName: 'efgh',
      email: 'abcd@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }, {
      id: this.state.counter,
      firstName: 'ijkl',
      lastName: 'mnop',
      email: 'ijkl@gmail.com',
      phone: '1234567890',
      role: 'admin'
    }]);
    this.setState({
      ...this.state,
      counter: this.state.counter + 2
    });
  }
}

export default ListUsers;

My container component (containers/ListUsers.tsx) looks like this -

import { connect, Dispatch } from 'react-redux';
import { Action, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): Action<User>;
  addUsers(users: Array<User>): Action<Array<User>>;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps, {}>(mapStateToProps, mapDispatchToProps)(ListUsers);

Now here is the reducer where I am facing issues (reducers/index.tsx) -

import { Action, StoreState, User } from '../types';
import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export const listUsers = (state: StoreState, action: Action<User>): StoreState => {
  switch (action.type) {
    case LIST_USERS:
      return state;
    case ADD_USER:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, action.payload]
      };
    case ADD_USERS:
      return {
        ...state,
        users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
      };
    default:
      return state;
  }
};

Here the compiler says that in the reducers/index.tsx in

case ADD_USERS:
  return {
    ...state,
    users: action.payload === undefined ? [...state.users] : [...state.users, ...action.payload]
  };

that action.payload is User and not Array<User> which is right (I have declared the reducer with type (state: StoreState, action: Action<User>)).

How do I work with this? If there isn't an alternative, I will have to write separate reducers for every ACTION that has a different payload which I think is bad.

The way I am using the DispatchProps type also looks very odd to me. I am trying to follow this for the types of mapStateToProps and mapDispatchToProps.

Is there any work around for this?

PS: I am using react, redux and react-redux libraries.

Body:
I found a solution for this. I am not sure if it is right way to do this.

Instead of making the Action Type generic like so -

interface Action<T> {
  type: string;
  payload?: T;
}

I created a Separate Action Type for each Action and then the Action Type accepted by the Reducer would be the | of them.

So, the types look like this (types/index.tsx) -

import { ADD_USER, ADD_USERS, LIST_USERS } from '../constants';

export interface User {
  id: number;
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  role: string;
}

export interface StoreState {
  users: Array<User>;
}

export type ListUsersAction = {type: typeof LIST_USERS};
export type AddUserAction = {type: typeof ADD_USER, payload: User};
export type AddUsersAction = {type: typeof ADD_USERS, payload: Array<User>};

export type Actions = ListUsersAction | AddUserAction | AddUsersAction;

and the Container Component (containers/ListUsers.tsx) looks like this -

import { connect, Dispatch } from 'react-redux';
import { AddUserAction, AddUsersAction, StoreState, User } from '../types';
import ListUsers from '../components/ListUsers';
import { addUser, addUsers } from '../actions';

export interface ListUsersProps {
  users: Array<User>;
}

export interface DispatchProps {
  addUser(user: User): AddUserAction;
  addUsers(users: Array<User>): AddUsersAction;
}

export const mapStateToProps = (state: StoreState): ListUsersProps => {
  return {
    users: state.users
  };
};

export const mapDispatchToProps = (dispatch: Dispatch<DispatchProps>) => {
  return {
    addUser: (user: User) => dispatch(addUser(user)),
    addUsers: (users: Array<User>) => dispatch(addUsers(users))
  };
};

export default connect<ListUsersProps, DispatchProps>(mapStateToProps, mapDispatchToProps)(ListUsers);

There are no compilation errors any more, and payload for both ADD_USER and ADD_USERS is received properly.

There is a recommendation to reduce the Action Type boilerplate here.


问:
How to access a form field's custom attribute at save time in Django?
Should be awarding double points for this one; I think it's going to be tricky.

Say for example I had a form field which looked like this:

```<code><li><label for="id_question_3_1"><input name="question_3" question_id="3" type="radio" class="inlinechoice" value="4" id="id_question_3_1" /> Agree</label></li>
</code>```

And I really really had to put that custom attribute "question_id" into my response that I was saving into the database.  How would I go about grabbing it?  I can't find an example of anyone needing to do this, so can't crib from anyone!

If it's not possible, how do I go about doing it?

I'm building a dynamic form, from some (usually 5 but not necessarily) questions stored in the database.  I need to store the answers along with a reference to the question it refers to.

I've got a response model to store, with a fk to the question, but need to get that custom attr out of the form data that is submitted.

答:
What's the purpose of that question_id attribute? Obviously that attribute itself isn't going to come back in the request, unless...

Parse the name=question_{id} of the input field (if this is the id) which implies you don't really need the question_id attribute

Server-side, generate a hidden form field with name=question_id and value=3 using your template.

Client-side, generate a hidden form field with some javascript. Not sure I like this one though, since it relies on the client having javascript.

Hidden form fields are normally the way to go here.

ContentLicense: CC BY-SA 2.5

Body:
Should be awarding double points for this one; I think it's going to be tricky.

Say for example I had a form field which looked like this:

<input name="question_3" question_id="3" type="radio" class="inlinechoice" value="4" id="id_question_3_1" /> Agree

And I really really had to put that custom attribute "question_id" into my response that I was saving into the database.  How would I go about grabbing it?  I can't find an example of anyone needing to do this, so can't crib from anyone!

If it's not possible, how do I go about doing it?

I'm building a dynamic form, from some (usually 5 but not necessarily) questions stored in the database.  I need to store the answers along with a reference to the question it refers to.

I've got a response model to store, with a fk to the question, but need to get that custom attr out of the form data that is submitted.


答:
You need to initialize the dictionary before the for loop, in your code in every iteration a new dictionary is being created in this line dict_val = {data[0] : data[1]}. You can try the following code:

```<code>from bs4 import BeautifulSoup

content="""
<table class="data">
    <tbody>
        <tr class="blue">
            <td>hot</td>
            <td>cold</td>
        </tr>
        <tr>
            <td>day</td>
            <td>night</td>
        </tr>
    </tbody>
</table>
"""
soup = BeautifulSoup(content,'lxml')
dict_val = {}
for items in soup.select('tr'):
    data = [item.text for item in items.select("td")]
    dict_val[data[0]] = data[1]
print(dict_val)
</code>```

Title: Unable to store parsed items as dictionary

Body:
You need to initialize the dictionary before the for loop, in your code in every iteration a new dictionary is being created in this line dict_val = {data[0] : data[1]}. You can try the following code:

from bs4 import BeautifulSoup

content="""
<table class="data">
    <tbody>
        <tr class="blue">
            <td>hot</td>
            <td>cold</td>
        </tr>
        <tr>
            <td>day</td>
            <td>night</td>
        </tr>
    </tbody>
</table>
"""
soup = BeautifulSoup(content,'lxml')
dict_val = {}
for items in soup.select('tr'):
    data = [item.text for item in items.select("td")]
    dict_val[data[0]] = data[1]
print(dict_val)


问:
How to override max length of username in Django by creating a custom model
I have a problem. I'm using Django 1.7, and have already made a custom user model, that inherits Django's abstract user like this:

```<code>class CustomUser(AbstractUser, BaseModel):
</code>```

Now they say in here Django-ticket, that I could avoid the problem of username's max_length being 30, by creating a custom user. Well, I already have a custom user, so it should be easy right? How I tried to do it was:

```<code>class CustomUser(AbstractUser, BaseModel):

      username = models.CharField(max_length=70, unique=True, db_index=True)
</code>```

Now when I try to make migrations for changing this field, it results in an error: django.core.exceptions.FieldError: Local field 'username' in class 'CustomUser' clashes with field of similar name from base class 'AbstractUser'

What am I doing wrong? How could I solve this problem? I have data that should be migrated, so I cannot empty database.

答: As I understood you can't override any Django ORM model's attribute, nor from AbstractUser, nor from PermissionsMixin classes. So, If you have your own approach to Permissions, Groups(Roles), even if you want another attribute name than user_permissions or groups, then you should inherit from AbstractBaseUser, doing a lot of copy-paste from AbstractUser and inherit your Permission and Group models from django.db.models.Model class as @levi and @Hedde van der Heide suggested.

Body:
I have a problem. I'm using Django 1.7, and have already made a custom user model, that inherits Django's abstract user like this:

class CustomUser(AbstractUser, BaseModel):

Now they say in here Django-ticket, that I could avoid the problem of username's max_length being 30, by creating a custom user. Well, I already have a custom user, so it should be easy right? How I tried to do it was:

class CustomUser(AbstractUser, BaseModel):

      username = models.CharField(max_length=70, unique=True, db_index=True)

Now when I try to make migrations for changing this field, it results in an error: django.core.exceptions.FieldError: Local field 'username' in class 'CustomUser' clashes with field of similar name from base class 'AbstractUser'

What am I doing wrong? How could I solve this problem? I have data that should be migrated, so I cannot empty database.


问:
Fitting 4 triangles within a background image
I'm trying to fit 4 triangles in a master template using jquery, html5 and canvas,

I can't seem to make them fit...

Here is what I got so far...

https://jsfiddle.net/ax67r91y/

The code I think is wrong:

```<code>ctx.drawImage(part.img,                             // random image
    0, 0, part.w, part.h,                           // source
    part.x,part.y,part.trisize.w,part.trisize.h);   // destination
</code>```

All images should be cut down into 2 forms: a " v " and a " ^ ",

I can move images, but shrinking them to the correct size seems unattainable...

I think I'm close, but it's been hours I'm on this, help is welcome!!!

Expected result:

答:
Is this what you are looking for?

function createSVG(name, attributes) {
 var svg_node = document.createElementNS("http://www.w3.org/2000/svg", name);

 Object.keys(attributes).forEach(function(key) {
  if (key == 'textContent') {
   svg_node.textContent = attributes[key];
   return;
  }
  svg_node.setAttribute(key, attributes[key]);
 });

 return svg_node;
}

Element.prototype.appendSVG = function(name, attributes) {
 this.appendChild(createSVG(name, attributes));
}

function Polygons() {
 this.canvas = createSVG('svg', {
  'version':    '1.1',
  'shape-rendering':  'geometricPrecision',
  'viewBox':    '0 0 1589 745',
    'class': 'svg-content',
 });
  this.defs = createSVG('defs', {});
  this.canvas.appendChild(this.defs);
  this.registerPatterns();

  this.drawInnerLayer();
 this.drawOuterLayer();
}

Polygons.prototype.registerPatterns = function() {
 var patternBottom = createSVG('pattern', {
   'height': "100%",
    'width': "100%",
    'patternContentUnits': "objectBoundingBox",
    'viewBox': "0 0 1 1",
    'preserveAspectRatio': "xMidYMid slice",
  });
  var imgBottom = createSVG('image', {
   'height': "1",
    'width': "1",
    'preserveAspectRatio': "xMidYMid slice",
  });
  var imgLeft = imgBottom.cloneNode(true)
  imgLeft.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/1.png");
  var imgMiddle = imgBottom.cloneNode(true);
  imgMiddle.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/2.png");
  var imgRight = imgBottom.cloneNode(true);
  imgRight.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/3.png");

  imgBottom.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/4.png");

  var patternLeft = patternBottom.cloneNode(true);
  patternLeft.setAttribute('id', "img-left");
  patternLeft.appendChild(imgLeft);
  var patternRight = patternBottom.cloneNode(true);
  patternRight.setAttribute('id', "img-right");
  patternRight.appendChild(imgRight);
  var patternMiddle = patternBottom.cloneNode(true);
  patternMiddle.setAttribute('id', "img-middle");
  patternMiddle.appendChild(imgMiddle);

  patternBottom.setAttribute('id', "img-bottom");
  patternBottom.appendChild(imgBottom);

  this.defs.appendChild(patternLeft);
  this.defs.appendChild(patternRight);
  this.defs.appendChild(patternMiddle);
  this.defs.appendChild(patternBottom);

 var patternOverlayer = createSVG('pattern', {
   'height': "100%",
    'width': "100%",
    'patternContentUnits': "objectBoundingBox",
    'id': "img-overlayer",
  });
  var imgOverlayer = createSVG('image', {
   'height': "1",
    'width': "1",
    'preserveAspectRatio': "none",
  });
  imgOverlayer.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/assets/images/frame-all.png");
  patternOverlayer.appendChild(imgOverlayer);
  this.defs.appendChild(patternOverlayer);
}

Polygons.prototype.drawOuterLayer = function() {
 this.canvas.appendSVG('rect', {
  'x': '0',
    'y': '0',
    'width': '100%',
    'height': '100%',
    'fill': 'url(#img-overlayer)',
  'class':   'img-overlayer',
 });
}

Polygons.prototype.drawInnerLayer = function() {
 this.canvas.appendSVG('polygon', {
  'points':   '500,55 800,50 643,370',
  'class':   'inner-polygon polygon-left',
    'fill': 'url(#img-left)',
 });
 this.canvas.appendSVG('polygon', {
  'points':   '800,70 665,395 935,395',
  'class':   'inner-polygon polygon-middle',
    'fill': 'url(#img-middle)',
 });
 this.canvas.appendSVG('polygon', {
  'points':   '820,50 1115,45 950,375',
  'class':   'inner-polygon polygon-right',
    'fill': 'url(#img-right)',
 });
 this.canvas.appendSVG('polygon', {
  'points':   '660,415 940,415 805,720',
  'class':   'inner-polygon polygon-down',
    'fill': 'url(#img-bottom)',
 });
}

var polygons = new Polygons();
document.getElementById('svg-container').appendChild(polygons.canvas);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#svg-container {
 display: inline-block;
 position: relative;
 width: 100%;
 padding-bottom: 100%;
 vertical-align: middle;
 overflow: hidden;
}

.svg-content {
 display: inline-block;
 position: absolute;
 top: 0;
 left: 0;
}</code>```

```

Body:
I'm trying to fit 4 triangles in a master template using jquery, html5 and canvas,

I can't seem to make them fit...

Here is what I got so far...

https://jsfiddle.net/ax67r91y/

The code I think is wrong:

ctx.drawImage(part.img,                             // random image
    0, 0, part.w, part.h,                           // source
    part.x,part.y,part.trisize.w,part.trisize.h);   // destination

All images should be cut down into 2 forms: a " v " and a " ^ ",

I can move images, but shrinking them to the correct size seems unattainable...

I think I'm close, but it's been hours I'm on this, help is welcome!!!

Expected result:

Body:
Is this what you are looking for?

function createSVG(name, attributes) {
 var svg_node = document.createElementNS("http://www.w3.org/2000/svg", name);

 Object.keys(attributes).forEach(function(key) {
  if (key == 'textContent') {
   svg_node.textContent = attributes[key];
   return;
  }
  svg_node.setAttribute(key, attributes[key]);
 });

 return svg_node;
}

Element.prototype.appendSVG = function(name, attributes) {
 this.appendChild(createSVG(name, attributes));
}

function Polygons() {
 this.canvas = createSVG('svg', {
  'version':    '1.1',
  'shape-rendering':  'geometricPrecision',
  'viewBox':    '0 0 1589 745',
    'class': 'svg-content',
 });
  this.defs = createSVG('defs', {});
  this.canvas.appendChild(this.defs);
  this.registerPatterns();

  this.drawInnerLayer();
 this.drawOuterLayer();
}

Polygons.prototype.registerPatterns = function() {
 var patternBottom = createSVG('pattern', {
   'height': "100%",
    'width': "100%",
    'patternContentUnits': "objectBoundingBox",
    'viewBox': "0 0 1 1",
    'preserveAspectRatio': "xMidYMid slice",
  });
  var imgBottom = createSVG('image', {
   'height': "1",
    'width': "1",
    'preserveAspectRatio': "xMidYMid slice",
  });
  var imgLeft = imgBottom.cloneNode(true)
  imgLeft.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/1.png");
  var imgMiddle = imgBottom.cloneNode(true);
  imgMiddle.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/2.png");
  var imgRight = imgBottom.cloneNode(true);
  imgRight.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/3.png");

  imgBottom.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/TMP/4.png");

  var patternLeft = patternBottom.cloneNode(true);
  patternLeft.setAttribute('id', "img-left");
  patternLeft.appendChild(imgLeft);
  var patternRight = patternBottom.cloneNode(true);
  patternRight.setAttribute('id', "img-right");
  patternRight.appendChild(imgRight);
  var patternMiddle = patternBottom.cloneNode(true);
  patternMiddle.setAttribute('id', "img-middle");
  patternMiddle.appendChild(imgMiddle);

  patternBottom.setAttribute('id', "img-bottom");
  patternBottom.appendChild(imgBottom);

  this.defs.appendChild(patternLeft);
  this.defs.appendChild(patternRight);
  this.defs.appendChild(patternMiddle);
  this.defs.appendChild(patternBottom);

 var patternOverlayer = createSVG('pattern', {
   'height': "100%",
    'width': "100%",
    'patternContentUnits': "objectBoundingBox",
    'id': "img-overlayer",
  });
  var imgOverlayer = createSVG('image', {
   'height': "1",
    'width': "1",
    'preserveAspectRatio': "none",
  });
  imgOverlayer.setAttributeNS('http://www.w3.org/1999/xlink','href', "http://waw.wizard.build/wp-content/themes/twentyseventeen/assets/images/frame-all.png");
  patternOverlayer.appendChild(imgOverlayer);
  this.defs.appendChild(patternOverlayer);
}

Polygons.prototype.drawOuterLayer = function() {
 this.canvas.appendSVG('rect', {
  'x': '0',
    'y': '0',
    'width': '100%',
    'height': '100%',
    'fill': 'url(#img-overlayer)',
  'class':   'img-overlayer',
 });
}

Polygons.prototype.drawInnerLayer = function() {
 this.canvas.appendSVG('polygon', {
  'points':   '500,55 800,50 643,370',
  'class':   'inner-polygon polygon-left',
    'fill': 'url(#img-left)',
 });
 this.canvas.appendSVG('polygon', {
  'points':   '800,70 665,395 935,395',
  'class':   'inner-polygon polygon-middle',
    'fill': 'url(#img-middle)',
 });
 this.canvas.appendSVG('polygon', {
  'points':   '820,50 1115,45 950,375',
  'class':   'inner-polygon polygon-right',
    'fill': 'url(#img-right)',
 });
 this.canvas.appendSVG('polygon', {
  'points':   '660,415 940,415 805,720',
  'class':   'inner-polygon polygon-down',
    'fill': 'url(#img-bottom)',
 });
}

var polygons = new Polygons();
document.getElementById('svg-container').appendChild(polygons.canvas);

#svg-container {
 display: inline-block;
 position: relative;
 width: 100%;
 padding-bottom: 100%;
 vertical-align: middle;
 overflow: hidden;
}

.svg-content {
 display: inline-block;
 position: absolute;
 top: 0;
 left: 0;
}

<div id="svg-container"></div>


问:
asp.net mvc EntityTypeConfiguration
Please shed some light on this...
I have an Employee and Department entity model having 1-to-many relation like this below

```<code>namespace Entities
{
    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Department Department { get; set; }
    }
}

namespace Entities
{
    public class Department
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public  ICollection<Employee> Employees { get; set; }
    }
}
</code>```

To make my entity classes more clean, I have used EntityConfiguration classes to declare annotations like below..

```<code>namespace Entities.EntityConfiguration
{
  public  class EmployeeConfiguration : EntityTypeConfiguration<Employee>
    {
        public EmployeeConfiguration()
        {
            Property(e => e.FirstName).IsRequired().HasMaxLength(10);

            Property(e => e.LastName).IsRequired().HasMaxLength(10);

HasRequired(a=>a.Department).WithMany(a=> a.Employees).Map(x=> x.MapKey("DepartmentID"));
        }
    }
}
</code>```

A part of my "create" view in Employee Controller is like this below

```<code><div class="form-group">
           @Html.LabelFor(model => model.Department, "Department", htmlAttributes: new { @class = "control-label col-md-2" })
           <div class="col-md-10">
               @Html.DropDownList("Department", @ViewBag.Department as SelectList,"--Please Select--", htmlAttributes: new { @class = "form-control" })
               @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
           </div>
       </div>
</code>```

And in the "Create" Post-method, I get the employees values like this below

Here above, The "Department" is showing null.

But I want to have the values like this

My question is: If I want to have "DepartmentID" here then I have to change my employee model class like this below.

```<code>namespace Entities
{
    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public int DepartmentID { get; set; }
        [ForeignKey("DepartmentID")]
        public Department Department { get; set; }
    }
}
</code>```

i.e I had to enter data annotations right inside my employee model class,
then what is the use of specifying the same in the EntityConfiguration Class.
Actually I want to have "DepartmentID" in the "Create" Post-method but i dont want to clutter my employee class with data annotations.

Also, How can I access the "Department" entity value in the "Create" Post method ?

Please give your suggestions and any other way out for this.

Thanks a lot.

答:
If your entity model exposes the DepartmentId like this:

```<code>public class Employee
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DepartmentID { get; set; }
    public Department Department { get; set; }
}
</code>```

Then build your ViewBag in the [HttpGet]:

```<code>ViewBag.Departments = _RepoDepartment.Select(x => new SelectListItem {
   Text = x.IDToString(),
   Value = x.Name
}).ToList();
</code>```

Now in your view:

```<code>@Html.DropDownListFor(model => model.DepartmentID, ViewBag.Departments as IEnumerable<SelectListItem>)
</code>```

Now when you select a department, it's DepartmentID will be posted back. There are other ways to do this as well.

Title: asp.net mvc EntityTypeConfiguration

Body:
Please shed some light on this...
I have an Employee and Department entity model having 1-to-many relation like this below

namespace Entities
{
    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Department Department { get; set; }
    }
}

namespace Entities
{
    public class Department
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public  ICollection<Employee> Employees { get; set; }
    }
}

To make my entity classes more clean, I have used EntityConfiguration classes to declare annotations like below..

namespace Entities.EntityConfiguration
{
  public  class EmployeeConfiguration : EntityTypeConfiguration<Employee>
    {
        public EmployeeConfiguration()
        {
            Property(e => e.FirstName).IsRequired().HasMaxLength(10);

            Property(e => e.LastName).IsRequired().HasMaxLength(10);

HasRequired(a=>a.Department).WithMany(a=> a.Employees).Map(x=> x.MapKey("DepartmentID"));
        }
    }
}

A part of my "create" view in Employee Controller is like this below

           @Html.LabelFor(model => model.Department, "Department", htmlAttributes: new { @class = "control-label col-md-2" })

               @Html.DropDownList("Department", @ViewBag.Department as SelectList,"--Please Select--", htmlAttributes: new { @class = "form-control" })
               @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })

And in the "Create" Post-method, I get the employees values like this below

Here above, The "Department" is showing null.

But I want to have the values like this

My question is: If I want to have "DepartmentID" here then I have to change my employee model class like this below.

namespace Entities
{
    public class Employee
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public int DepartmentID { get; set; }
        [ForeignKey("DepartmentID")]
        public Department Department { get; set; }
    }
}

i.e I had to enter data annotations right inside my employee model class,
then what is the use of specifying the same in the EntityConfiguration Class.
Actually I want to have "DepartmentID" in the "Create" Post-method but i dont want to clutter my employee class with data annotations.

Also, How can I access the "Department" entity value in the "Create" Post method ?

Please give your suggestions and any other way out for this.

Thanks a lot.

Body:
If your entity model exposes the DepartmentId like this:

public class Employee
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int DepartmentID { get; set; }
    public Department Department { get; set; }
}

Then build your ViewBag in the [HttpGet]:

ViewBag.Departments = _RepoDepartment.Select(x => new SelectListItem {
   Text = x.IDToString(),
   Value = x.Name
}).ToList();

Now in your view:

@Html.DropDownListFor(model => model.DepartmentID, ViewBag.Departments as IEnumerable<SelectListItem>)

Now when you select a department, it's DepartmentID will be posted back. There are other ways to do this as well.


问:
Dissecting a simple Javascript Closure
When looking at the code for the addSuffix function

```<code>const addSuffix = (x) => {
    const concat = (y) => {
        return y + x
    }
return concat;
}

let add_ful = addSuffix("ful");
</code>```

If I were to console.log(add_ful);  why do I get

```<code>(y) => {
    return y + x
}
</code>```

instead of

```<code>(y) => {
    return y + "ful"
}
</code>```

?

This is the most confusing point about closures for me, I understand that I can return a function, but I'm not sure where the reference to "ful" is being stored in the function.

Where is the value of x being stored in the add_ful function?

答:
The value is not stored in the code. It does not get inlined at every place where x is used in the closure - the code still contains a variable x that is dynamically resolved when encountered (it's also still writable).

The value is stored in the scope object containing the variable, and this is referenced by the function object (that's what we call a closure). You can also inspect this hidden [[Scope]] slot in the devtools when you are logging the function object (and not just the function code produced by .toString()):

Title: Dissecting a simple Javascript Closure

Body:
When looking at the code for the addSuffix function

const addSuffix = (x) => {
    const concat = (y) => {
        return y + x
    }
return concat;
}

let add_ful = addSuffix("ful");

If I were to console.log(add_ful);  why do I get

(y) => {
    return y + x
}

instead of

(y) => {
    return y + "ful"
}

?

This is the most confusing point about closures for me, I understand that I can return a function, but I'm not sure where the reference to "ful" is being stored in the function.

Where is the value of x being stored in the add_ful function?


问:
How do you determine how far to normalize a database?
When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?</p>

答:
You want to start designing a normalized database up to 3rd normal form. As you develop the business logic layer you may decide you have to denormalize a bit but never, never go below the 3rd form. Always, keep 1st and 2nd form compliant. You want to denormalize for simplicity of code, not for performance. Use indexes and stored procedures for that :)

The reason not "normalize as you go" is that you would have to modify the code you already have written most every time you modify the database design.

There are a couple of good articles:

http://www.agiledata.org/essays/dataNormalization.html

OwnerDisplayName: sergeb