问:
eslint throws `no-undef` errors when linting Jest test files
I'm using Jest to write some specs and ESLint to lint the styling.

For my foo.spec.js tests, eslint keeps throwing the following errors. It seems to think that jest, beforeEach, afterEach, etc... are not defined in that file.

```<code>   11:1   error  'beforeEach' is not defined  no-undef
   12:3   error  'jest' is not defined        no-undef
   14:13  error  'jest' is not defined        no-undef
   18:1   error  'afterEach' is not defined   no-undef
   20:1   error  'describe' is not defined    no-undef
   21:3   error  'it' is not defined          no-undef
   25:5   error  'expect' is not defined      no-undef
   28:5   error  'expect' is not defined      no-undef
   31:5   error  'expect' is not defined      no-undef
   34:3   error  'it' is not defined          no-undef
   38:5   error  'expect' is not defined      no-undef
   41:5   error  'jest' is not defined        no-undef
   42:5   error  'expect' is not defined      no-undef
   43:5   error  'expect' is not defined      no-undef
   46:3   error  'it' is not defined          no-undef
   54:5   error  'expect' is not defined      no-undef
   58:5   error  'jest' is not defined        no-undef
</code>```

I believe those are included by jest automatically and so they don't need to be explicitly imported in my spec files. In fact the only thing I import via my jest.setup.js file is

```<code>import "react-testing-library/cleanup-after-each";
import "jest-dom/extend-expect";
</code>```

Is there a way to eliminate these errors without having to disable eslint rules at the top of each individual file or inline?

Thanks!

答:
Please, add the following to your .eslintrc file:</p>

```<code>{
  "overrides": [
    {
      "files": [
        "**/*.spec.js",
        "**/*.spec.jsx"
      ],
      "env": {
        "jest": true
      }
    }
  ]
}
</code>```

Body:
I'm using Jest to write some specs and ESLint to lint the styling.

For my foo.spec.js tests, eslint keeps throwing the following errors. It seems to think that jest, beforeEach, afterEach, etc... are not defined in that file.

   11:1   error  'beforeEach' is not defined  no-undef
   12:3   error  'jest' is not defined        no-undef
   14:13  error  'jest' is not defined        no-undef
   18:1   error  'afterEach' is not defined   no-undef
   20:1   error  'describe' is not defined    no-undef
   21:3   error  'it' is not defined          no-undef
   25:5   error  'expect' is not defined      no-undef
   28:5   error  'expect' is not defined      no-undef
   31:5   error  'expect' is not defined      no-undef
   34:3   error  'it' is not defined          no-undef
   38:5   error  'expect' is not defined      no-undef
   41:5   error  'jest' is not defined        no-undef
   42:5   error  'expect' is not defined      no-undef
   43:5   error  'expect' is not defined      no-undef
   46:3   error  'it' is not defined          no-undef
   54:5   error  'expect' is not defined      no-undef
   58:5   error  'jest' is not defined        no-undef

I believe those are included by jest automatically and so they don't need to be explicitly imported in my spec files. In fact the only thing I import via my jest.setup.js file is

import "react-testing-library/cleanup-after-each";
import "jest-dom/extend-expect";

Is there a way to eliminate these errors without having to disable eslint rules at the top of each individual file or inline?

Thanks!

Body:
Please, add the following to your .eslintrc file:

{
  "overrides": [
    {
      "files": [
        "**/*.spec.js",
        "**/*.spec.jsx"
      ],
      "env": {
        "jest": true
      }
    }
  ]
}


来源: stackexchange

问:
Join list of sentences up to max character limit
I have a list in which each item is a sentence. I want to join the items as long as the new combined item does not go over a character limit.

You can join items in a list fairly easily.

x = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
' '.join(x)
>>> 'Alice went to the market. She bought an apple. And she then went to the park.'
```

Now say I would like to sequentially join the items as long as the new combined item is not greater than 50 characters.

The result would be :

['Alice went to the market. She bought an apple.','And she then went to the park.']

You can maybe do a list comprehension like here.  Or I can maybe do a conditional iterator like here.   But I run into problems where the sentences get cut off.

Clarifications

The max character limit refers to the length of a single item in the list...not the length of the entire list. When the list items are combined, no single item in the new list can be over the limit.

The items that were not able to be combined are returned in the list as they were unchanged.

Combine sentences together as long as they do not exceed limit.  If they exceed limit, do not combine and keep as is. Only combine sentences that are sequentially next to each other in the list.

Please make sure your solution satisfies the output result as indicated previously above :
['Alice went to the market. She bought an apple.','And she then went to the park.']

答:
Here's a one-line solution, just because it's possible.

```<code>[x[i] for i in range(len(x)) if [sum(list(map(len,x))[:j+1]) for j in range(len(x))][i] < 50]
</code>```

And here's the same more efficiently - with intermediate results to save recalculation - but still no explicit loops.

```<code>lens = list(map(len, x))
sums = [sum(lens[:i]) for i in range(len(x))]
[x[i] for i in range(len(x)) if sums < 50]
</code>```

I doubt this is going to be more efficient than an explicit loop in any realistic case, though!

ContentLicense: CC BY-SA 4.0

Body:
I have a list in which each item is a sentence. I want to join the items as long as the new combined item does not go over a character limit.

You can join items in a list fairly easily.

x = ['Alice went to the market.', 'She bought an apple.', 'And she then went to the park.']
' '.join(x)
>>> 'Alice went to the market. She bought an apple. And she then went to the park.'

Now say I would like to sequentially join the items as long as the new combined item is not greater than 50 characters.

The result would be :

['Alice went to the market. She bought an apple.','And she then went to the park.']

You can maybe do a list comprehension like here.  Or I can maybe do a conditional iterator like here.   But I run into problems where the sentences get cut off.

Clarifications

The max character limit refers to the length of a single item in the list...not the length of the entire list. When the list items are combined, no single item in the new list can be over the limit.

The items that were not able to be combined are returned in the list as they were unchanged.

Combine sentences together as long as they do not exceed limit.  If they exceed limit, do not combine and keep as is. Only combine sentences that are sequentially next to each other in the list.

Please make sure your solution satisfies the output result as indicated previously above :
['Alice went to the market. She bought an apple.','And she then went to the park.']

Body:
Here's a one-line solution, just because it's possible.

[x[i] for i in range(len(x)) if [sum(list(map(len,x))[:j+1]) for j in range(len(x))][i] < 50]

And here's the same more efficiently - with intermediate results to save recalculation - but still no explicit loops.

lens = list(map(len, x))
sums = [sum(lens[:i]) for i in range(len(x))]
[x[i] for i in range(len(x)) if sums < 50]

I doubt this is going to be more efficient than an explicit loop in any realistic case, though!


问:
Android Picasso Recyclerview Image downloading slow
I have endless recyclerview that almost mimics Instagram list/feeds. Where Image is loading into full screen width Imageview. I am using Picasso to load images. Here is my code:

```<code>public class HomeAdapter extends RecyclerView.Adapter {

Context context;

private Contract contract;

List<Feed> feeds;

static final int ITEM_TYPE_HEADER = 0;

static final int ITEM_TYPE_LOAD_MORE = 1;

static final int ITEM_TYPE_DESIGN = 2;

public HomeAdapter(Context context, List<Feed> feeds) {
    this.context = context;
    this.feeds = feeds;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View row;
    if (viewType == ITEM_TYPE_HEADER) {
        row = inflater.inflate(R.layout.list_item_home_header, parent, false);
        return new HeaderHolder(row);
    } else if (viewType == ITEM_TYPE_LOAD_MORE) {
        row = inflater.inflate(R.layout.list_item_load_more, parent, false);
        return new LoadMoreHolder(row);
    } else if (viewType == ITEM_TYPE_DESIGN) {
        row = inflater.inflate(R.layout.list_item_feed_home, parent, false);
        return new DesignItemHolder(row);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    Feed feed = feeds.get(position);
    if (holder instanceof HeaderHolder) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        Header header = (Header) feed;
        headerHolder.tvTitle.setText(header.getTitle());
        headerHolder.tvDescription.setText(header.getDescription());

    } else if (holder instanceof LoadMoreHolder) {
        LoadMoreHolder loadMoreHolder = (LoadMoreHolder) holder;
        LoadMore loadMore = (LoadMore) feed;
        if(loadMore.getType() == LOAD_MORE_TYPE_PROGRESS) {
            loadMoreHolder.pbLoadMore.setVisibility(View.VISIBLE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.GONE);
        } else {
            loadMoreHolder.pbLoadMore.setVisibility(View.GONE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(loadMore.getTitle())) {
                loadMoreHolder.tvTitle.setText(loadMore.getTitle());
                loadMoreHolder.tvTitle.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvTitle.setVisibility(View.GONE);

            if(StringUtils.isValid(loadMore.getDescription())) {
                loadMoreHolder.tvDescription.setText(loadMore.getDescription());
                loadMoreHolder.tvDescription.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvDescription.setVisibility(View.GONE);
        }

        loadMoreHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onRetryLoadMoreClick();
            }
        });

    } else if (holder instanceof DesignItemHolder) {
        final DesignItemHolder designItemHolder = (DesignItemHolder) holder;
        final DesignFeed designFeed = (DesignFeed) feed;
        String title = getFeedTitle(designFeed.getDesignCategory().getTitle(), designFeed.getEvent().getTitle());
        designItemHolder.tvCategory.setText(StringUtils.toUpperCaseSentence(designFeed.getDesignCategory().getTitle()));
        designItemHolder.tvDate.setText(DateTimeUtils.formatTime(designFeed.getDate()));
        designItemHolder.tvTitle.setText(StringUtils.toUpperCaseSentence(title));
        designItemHolder.tvBrand.setText(getBrandTitle(designFeed.getBrand().getTitle()));

        if(StringUtils.isValid(designFeed.getShopLink())) {
            designItemHolder.tvShop.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(designFeed.getPrice())) {
                designItemHolder.tvPrice.setVisibility(View.VISIBLE);
                designItemHolder.tvPrice.setText(designFeed.getPrice() + " PKR");
            } else
                designItemHolder.tvPrice.setVisibility(View.GONE);

            designItemHolder.tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(contract != null)
                        contract.onOpenShopLink(designFeed.getShopLink());
                }
            });
        }
        else {
            designItemHolder.tvPrice.setVisibility(View.GONE);
            designItemHolder.tvShop.setVisibility(View.GONE);
        }

        showFeedImage(designFeed, designItemHolder.ivThumbnail, designItemHolder.progressBar);

        Picasso.get()
                .load(designFeed.getDesignCategory().getThumbnail())
                .transform(new CircleTransform())
                .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                .into(designItemHolder.ivCategory);

        designItemHolder.ivThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignFeedClick(designFeed);
            }
        });

        designItemHolder.tvCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.ivCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onBrandClick(designFeed.getBrand());
            }
        });

        designItemHolder.ibFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onFavouriteClick(designFeed);
            }
        });

        designItemHolder.ibShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onShareClick(designFeed);
            }
        });

        designItemHolder.ibDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDownloadClick(designFeed);
            }
        });
    }
}

private void showFeedImage(final DesignFeed designFeed, final ImageView ivThumbnail, final ProgressBar progressBar) {
    Picasso.get()
            .load(designFeed.getThumbnail())
            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(ivThumbnail, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    //Try again online if cache failed
                    Picasso.get()
                            .load(designFeed.getThumbnail())
                            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                            .into(ivThumbnail, new Callback() {
                                @Override
                                public void onSuccess() {
                                }

                                @Override
                                public void onError(Exception e) {

                                }
                            });
                }
            });
}

@Override
public int getItemViewType(int position) {
    Feed feed = feeds.get(position);
    if (feed instanceof Header)
        return ITEM_TYPE_HEADER;
    else if (feed instanceof LoadMore)
        return ITEM_TYPE_LOAD_MORE;
    else if (feed instanceof DesignFeed)
        return ITEM_TYPE_DESIGN;
    else
        return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return feeds.size();
}

public void insertFeedAtStart(Feed feed) {
    feeds.add(0, feed);
    notifyDataSetChanged();
}

public void updateFeeds(ArrayList<Feed> mFeeds) {
    feeds.addAll(mFeeds);
    notifyDataSetChanged();
}

public void addLoadMoreItem(Feed loadMoreFeed) {
    feeds.add(loadMoreFeed);
    notifyItemInserted(getItemCount() - 1);
}

public void removeItem(int index) {
    feeds.remove(index);
    notifyDataSetChanged();
}

private class DesignItemHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvCategory, tvBrand, tvDate, tvPrice, tvShop;
    ImageView ivCategory, ivThumbnail;
    ImageButton ibFavourite, ibShare, ibDownload;
    ProgressBar progressBar;

    DesignItemHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvCategory = itemView.findViewById(R.id.tvCategory);
        tvBrand = itemView.findViewById(R.id.tvBrand);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivCategory = itemView.findViewById(R.id.ivCategory);
        ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvShop = itemView.findViewById(R.id.tvShop);
        ibFavourite = itemView.findViewById(R.id.ibFavourite);
        ibShare = itemView.findViewById(R.id.ibShare);
        ibDownload = itemView.findViewById(R.id.ibDownload);
        progressBar = itemView.findViewById(R.id.progressBar);
    }
}

private class HeaderHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvDescription;
    HeaderHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
    }
}

private class LoadMoreHolder extends RecyclerView.ViewHolder {
    ProgressBar pbLoadMore;
    RelativeLayout rlMessageRetry;
    TextView tvTitle, tvDescription;
    AppCompatButton btnRetry;

    LoadMoreHolder(View itemView) {
        super(itemView);
        pbLoadMore = itemView.findViewById(R.id.pbLoadMore);
        rlMessageRetry = itemView.findViewById(R.id.rlMessageRetry);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
        btnRetry = itemView.findViewById(R.id.btnRetry);
    }
}

public void setContract(Contract contract) {
    this.contract = contract;
}

public interface Contract {

    void onDesignCategoryClick(DesignCategory designCategory);

    void onDesignFeedClick(DesignFeed designCategory);

    void onBrandClick(Brand brand);

    void onRetryLoadMoreClick();

    void onShopClick(String shopLink);

    void onFavouriteClick(DesignFeed designFeed);

    void onShareClick(DesignFeed designFeed);

    void onDownloadClick(DesignFeed designFeed);

    void onOpenShopLink(String shopLink);
}
</code>```

}

Average image size is 80-100 kbs. But image download time is too slow. It almost takes 3-4 seconds to download an image. On the other hand when images are loading from cache it obviously loads an image in no time. I get 15 items from server to load into recyclerview which means 15 images would be downloading in parallel. But still it is quite slow as compared to Instagram or Facebook feeds.

Can anyone guide me about the correct technique to make it as fast as possible, so that when user scrolls down the list images should be already loaded instead him waiting for image to load?

答:
Can you try to put your holder classes static. Every findViewById has a real cost in performance. As you can see your class has a lot of findViewById. In other hand I suggest to take a look the difference between Picasso and Glide, there are differences in how they manage images.

When I tried to download images from the URL, Picasso was quite fast in loading the image from the internet than Glide. Maybe because after downloading the image, Picasso directly pushes the full-size image to the memory; while Glide resizes the image as per the dimension of the ImageView.

https://medium.com/@multidots/glide-vs-picasso-930eed42b81d

Body:
I have endless recyclerview that almost mimics Instagram list/feeds. Where Image is loading into full screen width Imageview. I am using Picasso to load images. Here is my code:

public class HomeAdapter extends RecyclerView.Adapter {

Context context;

private Contract contract;

List<Feed> feeds;

static final int ITEM_TYPE_HEADER = 0;

static final int ITEM_TYPE_LOAD_MORE = 1;

static final int ITEM_TYPE_DESIGN = 2;

public HomeAdapter(Context context, List<Feed> feeds) {
    this.context = context;
    this.feeds = feeds;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View row;
    if (viewType == ITEM_TYPE_HEADER) {
        row = inflater.inflate(R.layout.list_item_home_header, parent, false);
        return new HeaderHolder(row);
    } else if (viewType == ITEM_TYPE_LOAD_MORE) {
        row = inflater.inflate(R.layout.list_item_load_more, parent, false);
        return new LoadMoreHolder(row);
    } else if (viewType == ITEM_TYPE_DESIGN) {
        row = inflater.inflate(R.layout.list_item_feed_home, parent, false);
        return new DesignItemHolder(row);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    Feed feed = feeds.get(position);
    if (holder instanceof HeaderHolder) {
        HeaderHolder headerHolder = (HeaderHolder) holder;
        Header header = (Header) feed;
        headerHolder.tvTitle.setText(header.getTitle());
        headerHolder.tvDescription.setText(header.getDescription());

    } else if (holder instanceof LoadMoreHolder) {
        LoadMoreHolder loadMoreHolder = (LoadMoreHolder) holder;
        LoadMore loadMore = (LoadMore) feed;
        if(loadMore.getType() == LOAD_MORE_TYPE_PROGRESS) {
            loadMoreHolder.pbLoadMore.setVisibility(View.VISIBLE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.GONE);
        } else {
            loadMoreHolder.pbLoadMore.setVisibility(View.GONE);
            loadMoreHolder.rlMessageRetry.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(loadMore.getTitle())) {
                loadMoreHolder.tvTitle.setText(loadMore.getTitle());
                loadMoreHolder.tvTitle.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvTitle.setVisibility(View.GONE);

            if(StringUtils.isValid(loadMore.getDescription())) {
                loadMoreHolder.tvDescription.setText(loadMore.getDescription());
                loadMoreHolder.tvDescription.setVisibility(View.VISIBLE);
            } else
                loadMoreHolder.tvDescription.setVisibility(View.GONE);
        }

        loadMoreHolder.btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onRetryLoadMoreClick();
            }
        });

    } else if (holder instanceof DesignItemHolder) {
        final DesignItemHolder designItemHolder = (DesignItemHolder) holder;
        final DesignFeed designFeed = (DesignFeed) feed;
        String title = getFeedTitle(designFeed.getDesignCategory().getTitle(), designFeed.getEvent().getTitle());
        designItemHolder.tvCategory.setText(StringUtils.toUpperCaseSentence(designFeed.getDesignCategory().getTitle()));
        designItemHolder.tvDate.setText(DateTimeUtils.formatTime(designFeed.getDate()));
        designItemHolder.tvTitle.setText(StringUtils.toUpperCaseSentence(title));
        designItemHolder.tvBrand.setText(getBrandTitle(designFeed.getBrand().getTitle()));

        if(StringUtils.isValid(designFeed.getShopLink())) {
            designItemHolder.tvShop.setVisibility(View.VISIBLE);
            if(StringUtils.isValid(designFeed.getPrice())) {
                designItemHolder.tvPrice.setVisibility(View.VISIBLE);
                designItemHolder.tvPrice.setText(designFeed.getPrice() + " PKR");
            } else
                designItemHolder.tvPrice.setVisibility(View.GONE);

            designItemHolder.tvShop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(contract != null)
                        contract.onOpenShopLink(designFeed.getShopLink());
                }
            });
        }
        else {
            designItemHolder.tvPrice.setVisibility(View.GONE);
            designItemHolder.tvShop.setVisibility(View.GONE);
        }

        showFeedImage(designFeed, designItemHolder.ivThumbnail, designItemHolder.progressBar);

        Picasso.get()
                .load(designFeed.getDesignCategory().getThumbnail())
                .transform(new CircleTransform())
                .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                .into(designItemHolder.ivCategory);

        designItemHolder.ivThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignFeedClick(designFeed);
            }
        });

        designItemHolder.tvCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.ivCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDesignCategoryClick(designFeed.getDesignCategory());
            }
        });

        designItemHolder.tvBrand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onBrandClick(designFeed.getBrand());
            }
        });

        designItemHolder.ibFavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onFavouriteClick(designFeed);
            }
        });

        designItemHolder.ibShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onShareClick(designFeed);
            }
        });

        designItemHolder.ibDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(contract != null)
                    contract.onDownloadClick(designFeed);
            }
        });
    }
}

private void showFeedImage(final DesignFeed designFeed, final ImageView ivThumbnail, final ProgressBar progressBar) {
    Picasso.get()
            .load(designFeed.getThumbnail())
            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
            .networkPolicy(NetworkPolicy.OFFLINE)
            .into(ivThumbnail, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    //Try again online if cache failed
                    Picasso.get()
                            .load(designFeed.getThumbnail())
                            .placeholder(new ColorDrawable(ContextCompat.getColor(context, R.color.colorGreyLight)))
                            .into(ivThumbnail, new Callback() {
                                @Override
                                public void onSuccess() {
                                }

                                @Override
                                public void onError(Exception e) {

                                }
                            });
                }
            });
}

@Override
public int getItemViewType(int position) {
    Feed feed = feeds.get(position);
    if (feed instanceof Header)
        return ITEM_TYPE_HEADER;
    else if (feed instanceof LoadMore)
        return ITEM_TYPE_LOAD_MORE;
    else if (feed instanceof DesignFeed)
        return ITEM_TYPE_DESIGN;
    else
        return super.getItemViewType(position);
}

@Override
public int getItemCount() {
    return feeds.size();
}

public void insertFeedAtStart(Feed feed) {
    feeds.add(0, feed);
    notifyDataSetChanged();
}

public void updateFeeds(ArrayList<Feed> mFeeds) {
    feeds.addAll(mFeeds);
    notifyDataSetChanged();
}

public void addLoadMoreItem(Feed loadMoreFeed) {
    feeds.add(loadMoreFeed);
    notifyItemInserted(getItemCount() - 1);
}

public void removeItem(int index) {
    feeds.remove(index);
    notifyDataSetChanged();
}

private class DesignItemHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvCategory, tvBrand, tvDate, tvPrice, tvShop;
    ImageView ivCategory, ivThumbnail;
    ImageButton ibFavourite, ibShare, ibDownload;
    ProgressBar progressBar;

    DesignItemHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvCategory = itemView.findViewById(R.id.tvCategory);
        tvBrand = itemView.findViewById(R.id.tvBrand);
        tvDate = itemView.findViewById(R.id.tvDate);
        ivCategory = itemView.findViewById(R.id.ivCategory);
        ivThumbnail = itemView.findViewById(R.id.ivThumbnail);
        tvPrice = itemView.findViewById(R.id.tvPrice);
        tvShop = itemView.findViewById(R.id.tvShop);
        ibFavourite = itemView.findViewById(R.id.ibFavourite);
        ibShare = itemView.findViewById(R.id.ibShare);
        ibDownload = itemView.findViewById(R.id.ibDownload);
        progressBar = itemView.findViewById(R.id.progressBar);
    }
}

private class HeaderHolder extends RecyclerView.ViewHolder {
    TextView tvTitle, tvDescription;
    HeaderHolder(View itemView) {
        super(itemView);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
    }
}

private class LoadMoreHolder extends RecyclerView.ViewHolder {
    ProgressBar pbLoadMore;
    RelativeLayout rlMessageRetry;
    TextView tvTitle, tvDescription;
    AppCompatButton btnRetry;

    LoadMoreHolder(View itemView) {
        super(itemView);
        pbLoadMore = itemView.findViewById(R.id.pbLoadMore);
        rlMessageRetry = itemView.findViewById(R.id.rlMessageRetry);
        tvTitle = itemView.findViewById(R.id.tvTitle);
        tvDescription = itemView.findViewById(R.id.tvDescription);
        btnRetry = itemView.findViewById(R.id.btnRetry);
    }
}

public void setContract(Contract contract) {
    this.contract = contract;
}

public interface Contract {

    void onDesignCategoryClick(DesignCategory designCategory);

    void onDesignFeedClick(DesignFeed designCategory);

    void onBrandClick(Brand brand);

    void onRetryLoadMoreClick();

    void onShopClick(String shopLink);

    void onFavouriteClick(DesignFeed designFeed);

    void onShareClick(DesignFeed designFeed);

    void onDownloadClick(DesignFeed designFeed);

    void onOpenShopLink(String shopLink);
}

}

Average image size is 80-100 kbs. But image download time is too slow. It almost takes 3-4 seconds to download an image. On the other hand when images are loading from cache it obviously loads an image in no time. I get 15 items from server to load into recyclerview which means 15 images would be downloading in parallel. But still it is quite slow as compared to Instagram or Facebook feeds.

Can anyone guide me about the correct technique to make it as fast as possible, so that when user scrolls down the list images should be already loaded instead him waiting for image to load?


问:
Cleaning up rails migrations & persisting production data
We maintain a large project with many migrations dating back about 4 years.

Ideally we would like to delete all the old migrations and copy the schema contents into an initial_migration.rb file.

My question then, consists of three things:

Will this wipe out our clients databases?

If so, how do we persist the data?

Generally speaking what is the best way to go about this

Thanks in advance.

答:
Here's how I would approach this:

Back up the database in at least three places.

Make a copy of a small slice of your database.

Convert the copy into seed data (if this is confusing, let me know, and I will provide an example).

Create a new rails app (rails new <appname>).

Create one migration in your new app per table in your old database, with all the fields and formatting you want.

Migrate your new database.

Add at least one ! onto the create method for each table type in your seeds, i.e. Student.create!(name:'Jane', email: 'jane@edu.edu'), Teacher.create!('...).  This will cause ActiveRecord to give you a more verbose error if the data is not persisted to the table.

Run rails db:seed.

When you have that working, repeat the test with a much larger chunk of the database, or skip to trying the whole thing.

Swapping out the databases depends a lot on how you are deployed and I'm not an expert in that area.  You should consult with the persons responsible in your org, or you could try reading up here Application Migration Best Practices.


问:
Django registration and multiple profiles
I'm using django-registration in my application. I want to create different kinds of users with different profiles.
For example, one user is a teacher and another user is a student.

How can I modify registration to set the user_type and create the right profile?

答:
http://docs.djangoproject.com/en/1.2/topics/auth/#groups

Django groups are a great way to define what you are looking for.
You can have one User extended profile that will contain all attributes of teachers and students.

```<code>class MasterProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    # add all the fields here
</code>```

Then define groups: teacher and student and you associate each MasterProfile to either a teacher or a student.

Django Group table can help you define your various roles and allocate users to groups correctly.

ContentLicense: CC BY-SA 2.5

Body:
http://docs.djangoproject.com/en/1.2/topics/auth/#groups

Django groups are a great way to define what you are looking for.
You can have one User extended profile that will contain all attributes of teachers and students.

class MasterProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    # add all the fields here

Then define groups: teacher and student and you associate each MasterProfile to either a teacher or a student.

Django Group table can help you define your various roles and allocate users to groups correctly.

ContentLicense: CC BY-SA 3.0


问:
Haskell point-free style with no functions in the expression
I've been trying to take some simple functions and convert them to point-free style for practice.
I started with something like this:

```<code>zipSorted x y = (zip . sort) y $ sort x --zipSorted(x, y) = zip(sort(y), sort(x))
</code>```

and eventually converted it to

```<code>zipSorted = flip (zip . sort) . sort
</code>```

(I'm not sure if this is even the best way to do it but it works)

Now I'm trying to further reduce this expression by not having it depend on zip and sort at all. In other words, I'm looking for this function: (I think its a combinator if my vocabulary isn't mistaken)

```<code>P(f, g, x, y) = f(g(y), g(x))
</code>```

The fact that sort is present twice but only passed in once hinted to me that I should use the applicative functor operator <*> but I can't figure out how for some reason.

From my understanding, (f <*> g)(x) = f(x, g(x)), so I've tried re-writing the first point-free expression in this form:

```<code>flip (zip . sort) . sort
(.) (flip $ zip . sort) sort
(flip (.)) sort $ flip (zip . sort)
(flip (.)) sort $ flip $ (zip .) sort
</code>```

It seems that sort should be x, (flip (.)) should be f, and flip . (zip .) should be g.

```<code>p = (flip (.)) <*> (flip . (zip .))
p sort [2, 1, 3] [4, 1, 5]
</code>```

yields [(1, 1), (4, 2), (5, 3)] as expected, but now I'm lost on how to pull the zip out. I've tried

```<code>p = (flip (.)) <*> (flip . (.))
p zip sort [2, 1, 3] [4, 1, 5]
</code>```

but this doesn't work. Is there a way to convert that expression to a combinator that factors out zip?

答:
I just asked lambdabot for the answer, rather than trying to work it out by hand:</p>

```<code><amalloy> @pl \zip sort x y -> (zip . sort) y $ sort x
<lambdabot> join . (((.) . flip) .) . (.)
</code>```

Body:
I've been trying to take some simple functions and convert them to point-free style for practice.
I started with something like this:

zipSorted x y = (zip . sort) y $ sort x --zipSorted(x, y) = zip(sort(y), sort(x))

and eventually converted it to

zipSorted = flip (zip . sort) . sort

(I'm not sure if this is even the best way to do it but it works)

Now I'm trying to further reduce this expression by not having it depend on zip and sort at all. In other words, I'm looking for this function: (I think its a combinator if my vocabulary isn't mistaken)

P(f, g, x, y) = f(g(y), g(x))

The fact that sort is present twice but only passed in once hinted to me that I should use the applicative functor operator <*> but I can't figure out how for some reason.

From my understanding, (f <*> g)(x) = f(x, g(x)), so I've tried re-writing the first point-free expression in this form:

flip (zip . sort) . sort
(.) (flip $ zip . sort) sort
(flip (.)) sort $ flip (zip . sort)
(flip (.)) sort $ flip $ (zip .) sort

It seems that sort should be x, (flip (.)) should be f, and flip . (zip .) should be g.

p = (flip (.)) <*> (flip . (zip .))
p sort [2, 1, 3] [4, 1, 5]

yields [(1, 1), (4, 2), (5, 3)] as expected, but now I'm lost on how to pull the zip out. I've tried

p = (flip (.)) <*> (flip . (.))
p zip sort [2, 1, 3] [4, 1, 5]

but this doesn't work. Is there a way to convert that expression to a combinator that factors out zip?

Body:
I just asked lambdabot for the answer, rather than trying to work it out by hand:

<amalloy> @pl \zip sort x y -> (zip . sort) y $ sort x
<lambdabot> join . (((.) . flip) .) . (.)


答:
Let's start from the beginning:

```<code>zipSort x y = zip (sort y) (sort x)
</code>```

It's slightly weird that it uses its arguments in the opposite order, but we can fix that later with flip.

Here we have a general pattern of a "combining" function of two arguments (here: zip) being passed two values transformed by another function. If we had the same base argument but different transformers, this would have been a liftA2 pattern:

```<code>  c (f x) (g x)
==
  liftA2 c f g x
</code>```

But here it's the opposite: We have the same transform function on both sides (here: sort), but different arguments (x and y). That's on:

```<code>  c (f x) (f y)
==
  (c `on` f) x y
</code>```

In your case we get:

```<code>zip (sort y) (sort x)
(zip `on` sort) y x
flip (zip `on` sort) x y
</code>```

So

```<code>zipSort = flip (zip `on` sort)  -- or: flip (on zip sort)
</code>```

We can further pull out zip and sort by recognizing the standard two-argument-into-one-argument-function composition:

```<code>(\x y -> f (g x y)) == (f .) . g
</code>```

giving

```<code>zipSort = ((flip .) . on) zip sort
</code>```

Note that this function is less general than the pointful version, however. The original function has type

```<code>(Ord a, Ord b) => [a] -> [b] -> [(b, a)]
</code>```

but the pointfree version has type

```<code>(Ord a) => [a] -> [a] -> [(a, a)]
</code>```

because unifying the two sorts forces them to have the same type.

Title: Haskell point-free style with no functions in the expression

Body:
Let's start from the beginning:

zipSort x y = zip (sort y) (sort x)

It's slightly weird that it uses its arguments in the opposite order, but we can fix that later with flip.

Here we have a general pattern of a "combining" function of two arguments (here: zip) being passed two values transformed by another function. If we had the same base argument but different transformers, this would have been a liftA2 pattern:

  c (f x) (g x)
==
  liftA2 c f g x

But here it's the opposite: We have the same transform function on both sides (here: sort), but different arguments (x and y). That's on:

  c (f x) (f y)
==
  (c `on` f) x y

In your case we get:

zip (sort y) (sort x)
(zip `on` sort) y x
flip (zip `on` sort) x y

So

zipSort = flip (zip `on` sort)  -- or: flip (on zip sort)

We can further pull out zip and sort by recognizing the standard two-argument-into-one-argument-function composition:

(\x y -> f (g x y)) == (f .) . g

giving

zipSort = ((flip .) . on) zip sort

Note that this function is less general than the pointful version, however. The original function has type

(Ord a, Ord b) => [a] -> [b] -> [(b, a)]

but the pointfree version has type

(Ord a) => [a] -> [a] -> [(a, a)]

because unifying the two sorts forces them to have the same type.


问:
TypeError: too many data entries
i am trying to recreate a picture. I take a picture edging it and save it. after i made it grayscale and save it. Found the common pixels of the two images and I am trying to recreate again the picture and i get this error. It is a picture of a road and i am trying to keep only the white lanes. so after i compare the edged picture with the first picture most common pixels are the white ones that represent the lanes of the road.

The error is thrown in line marked <———-- near the end of the code listing

```<code>TypeError: too many data entries
</code>```

newpic is the list in that form `[1,1,1,1,...,1]

here is my code and explaining every part. if you have any other suggestion how to achieve the result i want please say it

```<code>    #LIBRARIES
    import cv2
    import numpy as np
     import matplotlib as mpl
    from matplotlib import pyplot as plt

    #read and display the image
    img = cv2.imread("road.jpg")

    #original picture show
    cv2.imshow("Window Name",img)

    # edging the image
    edges = cv2.Canny(img,255,255)

    #show the canny picture
    cv2.imshow("Window Name",edges)

     #save the canny picture First argument is the file name, second
    argument is the image you want to save.
    cv2.imwrite('canny.png',edges)

      #making the image an array
    from PIL import Image
    #read the pciture
    img = Image.open('road.jpg').convert('LA')

     #save it
    img.save('greyscale.png')
    #open the edited
     im=Image.open("greyscale.png")
     #make it an array
    pix_val = list(im.getdata())
    pix_val_flat = [x for sets in pix_val for x in sets]
    # pix_val_flat has the pixels for out first image without edging
    #print the array
    #print (pix_val_flat[125]);
    #get the lenght of the array
    lenght=len(pix_val_flat)
    #print the array
    #print(lenght);
    #take the canny picture and make it grayscale
    edge = Image.open('canny.png').convert('LA')
    #make it array
    pix_val1 = list(edge.getdata())
    pix_val_flat1 = [x for sets in pix_val for x in sets]
    #get the lenght of the array
    #lenght1=len(pix_val_flat1)
    #prnt the array
    #print(lenght);
    #print the array
    #print (pix_val_flat1[125]);

    print(lenght)

     newpic = [0]*lenght
    lenght2=len(newpic)
    print (newpic)

     for c1 in range(0,lenght,3):

         if pix_val_flat[c1]==pix_val_flat1[c1] and
         pix_val_flat[c1+1]==pix_val_flat1[c1+1] and
                        pix_val_flat[c1+2]==pix_val_flat1[c1+2]:
        newpic[c1]= pix_val_flat1[c1]
        newpic[c1+1]= pix_val_flat1[c1+1]
        newpic[c1+2]= pix_val_flat1[c1+2]

     array = np.array(newpic, dtype=np.uint8)
     print (array)
     im2 = Image.new(im.mode, im.size)
     im2.putdata    (newpic)  ---------------------> here i get the error
     new_image = Image.fromarray(array)
     new_image.save('hello.png')

           cv2.waitKey(0)
      cv2.destroyAllWindows()
</code>```

答:
In this case it means that your putting more data than the size you set before.
You can check the length of data you put in with len(the_list_of_data), so you'll see length gets double every time you put data (even if you overwrite). You can set the_list_of_data length to 0 and then fill it with data. This error occurs in loops too.</p>

Title: TypeError: too many data entries

Body:
i am trying to recreate a picture. I take a picture edging it and save it. after i made it grayscale and save it. Found the common pixels of the two images and I am trying to recreate again the picture and i get this error. It is a picture of a road and i am trying to keep only the white lanes. so after i compare the edged picture with the first picture most common pixels are the white ones that represent the lanes of the road.

The error is thrown in line marked <———-- near the end of the code listing

TypeError: too many data entries

newpic is the list in that form `[1,1,1,1,...,1]

here is my code and explaining every part. if you have any other suggestion how to achieve the result i want please say it

    #LIBRARIES
    import cv2
    import numpy as np
     import matplotlib as mpl
    from matplotlib import pyplot as plt

    #read and display the image
    img = cv2.imread("road.jpg")

    #original picture show
    cv2.imshow("Window Name",img)

    # edging the image
    edges = cv2.Canny(img,255,255)

    #show the canny picture
    cv2.imshow("Window Name",edges)

     #save the canny picture First argument is the file name, second
    argument is the image you want to save.
    cv2.imwrite('canny.png',edges)

      #making the image an array
    from PIL import Image
    #read the pciture
    img = Image.open('road.jpg').convert('LA')

     #save it
    img.save('greyscale.png')
    #open the edited
     im=Image.open("greyscale.png")
     #make it an array
    pix_val = list(im.getdata())
    pix_val_flat = [x for sets in pix_val for x in sets]
    # pix_val_flat has the pixels for out first image without edging
    #print the array
    #print (pix_val_flat[125]);
    #get the lenght of the array
    lenght=len(pix_val_flat)
    #print the array
    #print(lenght);
    #take the canny picture and make it grayscale
    edge = Image.open('canny.png').convert('LA')
    #make it array
    pix_val1 = list(edge.getdata())
    pix_val_flat1 = [x for sets in pix_val for x in sets]
    #get the lenght of the array
    #lenght1=len(pix_val_flat1)
    #prnt the array
    #print(lenght);
    #print the array
    #print (pix_val_flat1[125]);

    print(lenght)

     newpic = [0]*lenght
    lenght2=len(newpic)
    print (newpic)

     for c1 in range(0,lenght,3):

         if pix_val_flat[c1]==pix_val_flat1[c1] and
         pix_val_flat[c1+1]==pix_val_flat1[c1+1] and
                        pix_val_flat[c1+2]==pix_val_flat1[c1+2]:
        newpic[c1]= pix_val_flat1[c1]
        newpic[c1+1]= pix_val_flat1[c1+1]
        newpic[c1+2]= pix_val_flat1[c1+2]

     array = np.array(newpic, dtype=np.uint8)
     print (array)
     im2 = Image.new(im.mode, im.size)
     im2.putdata    (newpic)  ---------------------> here i get the error
     new_image = Image.fromarray(array)
     new_image.save('hello.png')

           cv2.waitKey(0)
      cv2.destroyAllWindows()


问:
How to check if a variable has been declared even if it hasn't been defined?
This question:

JavaScript check if variable exists (is defined/initialized)

does not regard the case of variables which have been declared but not defined (as opposed to undeclared and undefined). Specifically, if I want to check whether x has been declared, this:

typeof x == 'undefined'

will not do, because...

```<code>var x; //<- declared but undefined
// idontexist  not declared

typeof idontexist === typeof x; // evaluates to true
</code>```

This has implications: if variable has been declared it wont become a global variable, whereas if a variable has not declared, it would become a global variable, possibly leading to memory leak.

So how do I check in javascript if undefined variable has been declared?

Regarding the implications of this, consider this code:

```<code>function test() {

  var x
  console.log(typeof x == typeof y); // true
  if (typeof x == 'undefined') {
     x = 3;
  }
  if (typeof y == 'undefined') {
     y = 5;
  }
}
test();
y; // 5
x; // Reference Error
</code>```

答:
I had answered this several years ago..., can't remember where.

```<code>    "variablename" in this //> true : false
</code>```

where this is any executional context which would otherwise have access to that variable name value.

```<code>    function exists( x ){ return x in this }
</code>```

Body:
This question:

JavaScript check if variable exists (is defined/initialized)

does not regard the case of variables which have been declared but not defined (as opposed to undeclared and undefined). Specifically, if I want to check whether x has been declared, this:

typeof x == 'undefined'

will not do, because...

var x; //<- declared but undefined
// idontexist  not declared

typeof idontexist === typeof x; // evaluates to true

This has implications: if variable has been declared it wont become a global variable, whereas if a variable has not declared, it would become a global variable, possibly leading to memory leak.

So how do I check in javascript if undefined variable has been declared?

Regarding the implications of this, consider this code:

function test() {

  var x
  console.log(typeof x == typeof y); // true
  if (typeof x == 'undefined') {
     x = 3;
  }
  if (typeof y == 'undefined') {
     y = 5;
  }
}
test();
y; // 5
x; // Reference Error

Body:
I had answered this several years ago..., can't remember where.

    "variablename" in this //> true : false

where this is any executional context which would otherwise have access to that variable name value.

    function exists( x ){ return x in this }


问:
How to Unit test Util class with dependency on other Util class method?
I have a util class which takes String jwtToken and Key key and decodes the jwt using io.jsonwebtoken.jwts.

However, I am not able to test this. The reason is, I am not able to mock the public key and pass to the method. So, the method breaks at Jwts.parser().serSigningKey(key)...

I tried mocking the Public key but that too did not work as I am passing mock data to real function and get UnSupportedJwtException.

One way I can think of is to move the Util that converts String to Key into Util helper for test and use it and pass the converted key into the method. This works however, I do not think it is the right way to approach the problem.

```<code>       Claims claims = null;

       try {
           claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwtToken).getBody();
       } catch (UnsupportedJwtException | MalformedJwtException | ExpiredJwtException
               | IllegalArgumentException ex) {
           LOGGER.error("Error in JWT/JWS validation", ex);
       }
       LOGGER.debug("Return Claims: ", claims);
       return claims;
   } ```
```

答: You can extract Jwts.parser() as separate field of your class instead of invoking this factory method directly in your method. Then  you will be able to replace this object with mock</p>

Body:
I have a util class which takes String jwtToken and Key key and decodes the jwt using io.jsonwebtoken.jwts.

However, I am not able to test this. The reason is, I am not able to mock the public key and pass to the method. So, the method breaks at Jwts.parser().serSigningKey(key)...

I tried mocking the Public key but that too did not work as I am passing mock data to real function and get UnSupportedJwtException.

One way I can think of is to move the Util that converts String to Key into Util helper for test and use it and pass the converted key into the method. This works however, I do not think it is the right way to approach the problem.

       Claims claims = null;

       try {
           claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwtToken).getBody();
       } catch (UnsupportedJwtException | MalformedJwtException | ExpiredJwtException
               | IllegalArgumentException ex) {
           LOGGER.error("Error in JWT/JWS validation", ex);
       }
       LOGGER.debug("Return Claims: ", claims);
       return claims;
   } ```


问:
Duplicate on 2 fields
I looking a way to avoid the duplicates in Laravel. For example, I have a table with 2 fields which are name and firstname.

How to manage the duplicates on the Controller? I am newbie...

Here is my function store().

```<code>public function store(Request $request)
    {
        $request->validate([
                'name' => 'required|string|max:25',
                'firstname' => 'required|string|max:25'

        ]);

        $exists = Auteur::where('name', $request->get('name'))->where('firstName', $request->get('firstName'))->count();

        if (!$exists){
            Auteur::create($request->all());
            return redirect()->route('auteurs.index')
                    ->with('success', 'save');
        }

    }
</code>```

I thank you for your help and your explanations.

答:
If it were one field, you could use validation, or make that field unique and that would take care of it with a little error handling.  However, with two fields to have to check against, it might be easiest to check if the element is already in the database and deduplicate from there.  So in the store() method:

```<code>$exists = Auteur::where('name', $req->get('name'))->where('firstname', $req->get('firstname')->count();

if (!$exists){
    // create the new model, now that we know there is no duplicate in the database
    Auteur::create($request->all());
}
</code>```

Title: Duplicate on 2 fields

Body:
I looking a way to avoid the duplicates in Laravel. For example, I have a table with 2 fields which are name and firstname.

How to manage the duplicates on the Controller? I am newbie...

Here is my function store().

public function store(Request $request)
    {
        $request->validate([
                'name' => 'required|string|max:25',
                'firstname' => 'required|string|max:25'

        ]);

        $exists = Auteur::where('name', $request->get('name'))->where('firstName', $request->get('firstName'))->count();

        if (!$exists){
            Auteur::create($request->all());
            return redirect()->route('auteurs.index')
                    ->with('success', 'save');
        }

    }

I thank you for your help and your explanations.

Body:
If it were one field, you could use validation, or make that field unique and that would take care of it with a little error handling.  However, with two fields to have to check against, it might be easiest to check if the element is already in the database and deduplicate from there.  So in the store() method:

$exists = Auteur::where('name', $req->get('name'))->where('firstname', $req->get('firstname')->count();

if (!$exists){
    // create the new model, now that we know there is no duplicate in the database
    Auteur::create($request->all());
}


问:
How to change all the numbers in a list to have the same amount of digits - Python
I have a list of numbers that I am reading from a file. I want to make it so the length of the numbers is all the same based on what I want it to be (7 digits, 4 digits, etc.). If there is a 5 and I want it to be 4 digits, I'd want the output to be 5.000 and if there was a 1048 and I want 4 digits It would already be in the correct digit place</p>

```<code>firstline = line.strip().replace('\t', ' ').split()[1:]
trythis = (map(float, (firstline)))
print(list(trythis))
for i in range(len(firstline)):
    trythis[i] = round(trythis[i], 4)
print(list(trythis))

[0.0, 0.053, 0.105, 0.158, 0.211, 0.263, 0.316, 0.368, 0.421, 0.474, 0.526, 0.579, 0.632, 0.684, 0.737, 0.789, 0.842, 0.895, 0.947, 1.0]
Traceback (most recent call last):
    trythis[i] = round(trythis[i], 4)
TypeError: 'map' object is not subscriptable
</code>```

答:
You can use the following condition "%.xf" (x being the number of digits you wnat to display after the comma) :

```<code>list_1  =[1.2, 1.345, 1.32]
list_2 = ["%.3f" % x for x in list_1]

print(list_2)
['1.200', '1.345', '1.320']
</code>```

Or you could cast your number into a string and check their length :

```<code>list_1  =[1.2, 1.345, 1.32]
len_wanted = 5
list_2 = [x if len(str(x))==len_wanted  else str(x)+'0'*(len_wanted -len(str(x))) for x in list_1]

print(list_2)
['1.200', 1.345, '1.320']
</code>```

Body:
I have a list of numbers that I am reading from a file. I want to make it so the length of the numbers is all the same based on what I want it to be (7 digits, 4 digits, etc.). If there is a 5 and I want it to be 4 digits, I'd want the output to be 5.000 and if there was a 1048 and I want 4 digits It would already be in the correct digit place

firstline = line.strip().replace('\t', ' ').split()[1:]
trythis = (map(float, (firstline)))
print(list(trythis))
for i in range(len(firstline)):
    trythis[i] = round(trythis[i], 4)
print(list(trythis))

[0.0, 0.053, 0.105, 0.158, 0.211, 0.263, 0.316, 0.368, 0.421, 0.474, 0.526, 0.579, 0.632, 0.684, 0.737, 0.789, 0.842, 0.895, 0.947, 1.0]
Traceback (most recent call last):
    trythis[i] = round(trythis[i], 4)
TypeError: 'map' object is not subscriptable

Body:
You can use the following condition "%.xf" (x being the number of digits you wnat to display after the comma) :

list_1  =[1.2, 1.345, 1.32]
list_2 = ["%.3f" % x for x in list_1]

print(list_2)
['1.200', '1.345', '1.320']

Or you could cast your number into a string and check their length :

list_1  =[1.2, 1.345, 1.32]
len_wanted = 5
list_2 = [x if len(str(x))==len_wanted  else str(x)+'0'*(len_wanted -len(str(x))) for x in list_1]

print(list_2)
['1.200', 1.345, '1.320']


问:
Confusion with scanf() or if()
I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

```<code>#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}
</code>```

答:
I believe there's an error with how you're using scanf, specifically, at this point:

```<code>scanf(" %s", &tempConvering[10]);
                  ^
                  |
                  +---- here
</code>```

The second argument to scanf should be the address of the place to store the result. Here, you're saying "place the string that's read in in the memory just after the buffer that I've set up," which isn't probably want you wanted to do. Instead, write this:

```<code>scanf(" %s", tempConvering);
</code>```

This says "place the string inside the buffer named tempConverting." If you're just getting started with C and haven't learned much about pointers and arrays, a good rule of thumb is that if you're reading a string with `scanf, you should just give the name of the array variable where you want to store the string rather than using an ampersand.

Hope this helps!

Title: Confusion with scanf() or if()

Body:
I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

Body:
I believe there's an error with how you're using scanf, specifically, at this point:

scanf(" %s", &tempConvering[10]);
                  ^
                  |
                  +---- here

The second argument to scanf should be the address of the place to store the result. Here, you're saying "place the string that's read in in the memory just after the buffer that I've set up," which isn't probably want you wanted to do. Instead, write this:

scanf(" %s", tempConvering);

This says "place the string inside the buffer named tempConverting." If you're just getting started with C and haven't learned much about pointers and arrays, a good rule of thumb is that if you're reading a string with `scanf, you should just give the name of the array variable where you want to store the string rather than using an ampersand.

Hope this helps!


问:
Why browsers keeps old code in symfony 4?
I have app in symfony 4, but sometimes when I have changed something this is not refreshed on page in browser.

Example.

I have class col-md-5 and is change to col-md-3 and then is refreshing page and there is still col-md-5. It's strange.

Similar is with CSS. I have width: 50%;, then I change  to 10%, then refresh page and still is width 50%.

I have to change something else in code, write something, some text and then refresh and is ok, is refreshed. Or after clear cache in symfony is ok.

It's standard symfony 4 app.

It's dev mode and twig cache is disabled. Guys, where is the problem?

答:
The problem comes from the cache. if the browser does not detect a big change, it will keep "previous version". You should save in PHPStorm (or your text editor, probably Ctrl+S), and if the changes do not appear, you can refresh your browser without cache: CTRL+R.

If your app is in production or change still not appear you can clear the cache. In symfony you can use the command :

```<code>php bin/console cache:clear
</code>```

or alias :

```<code>bin/console c:c
</code>```

I hope it will help, feel free to ask if you want more info.

Body:
The problem comes from the cache. if the browser does not detect a big change, it will keep "previous version". You should save in PHPStorm (or your text editor, probably Ctrl+S), and if the changes do not appear, you can refresh your browser without cache: CTRL+R.

If your app is in production or change still not appear you can clear the cache. In symfony you can use the command :

php bin/console cache:clear

or alias :

bin/console c:c

I hope it will help, feel free to ask if you want more info.


问:
Add action to scaffold generated controller
I have created model, view and controller:

```<code>$ rails generate scaffold Post name:string title:string content:text
</code>```

Then I have added the method on Post controller:

```<code>def fill_default_data
  Post.fill_default_data
end
</code>```

But when I have open http://localhost:3000/posts/fill_default_data in browser I get the error:

ActiveRecord::RecordNotFound in
  PostsController#show

Couldn't find Post with
  ID=fill_default_data

It looks like Rails don't see fill_default_data action and use show method.  How can I add new method to scaffold generated controller?

答:
Or if you want to add the method to a member rather than the collection, use the following:

```<code>resources :posts do
  member do
    get :fill_default_data, :as => 'fill_out_data'
  end
end
</code>```

This using member if preferred if you are performing the action on a single post rather than on a collection of posts.  Also, the :as option generates named route helpers (stuff like *_path or *_url) in case you want them.

Body:
I have created model, view and controller:

$ rails generate scaffold Post name:string title:string content:text

Then I have added the method on Post controller:

def fill_default_data
  Post.fill_default_data
end

But when I have open http://localhost:3000/posts/fill_default_data in browser I get the error:

ActiveRecord::RecordNotFound in
  PostsController#show

Couldn't find Post with
  ID=fill_default_data

It looks like Rails don't see fill_default_data action and use show method.  How can I add new method to scaffold generated controller?

Body:
Or if you want to add the method to a member rather than the collection, use the following:

resources :posts do
  member do
    get :fill_default_data, :as => 'fill_out_data'
  end
end

This using member if preferred if you are performing the action on a single post rather than on a collection of posts.  Also, the :as option generates named route helpers (stuff like *_path or *_url) in case you want them.


问:
How to stop overwrite txt file and let it write in new line
The problem occurs from my while code, it first takes the user input and put it to the text file and ask if it wants to answer it again but every the user do that and end the loop it just takes the latest user input and just overwrites the previous input user did. But that's not what I want from my code to do. Instead, the new answer should just then be on a new line on the text file.</p>

```<code>public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;

    try{
    File folder = new File("folderName");
    folder.mkdir();
    File f = new File(folder, "file1.txt"); //file to folder
    f.createNewFile(); //skapar fil
    //Scanner fileIn = new Scanner(f);
    System.out.println("File path" +f.getPath());

   //.----------------------------------
while(anw.equals("j")){

        Scanner in = new Scanner(System.in);
        FileWriter fWriter ;// removed null
        BufferedWriter writr;// removed null

        System.out.println("Ange utgiftspost:"); //post
        String post = in.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=in.nextInt();
        in.nextLine();
        saldo = +saldo -cost;
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = in.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo;

        fWriter = new FileWriter(f);
        writr = new BufferedWriter(fWriter);
        writr.write(fileContent);
        writr.newLine();

        if (anw.equals("n")) {
            writr.close();
            //writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);

        }
    } //frågan slut
    }//try

    //Scanner fileIn = new Scanner(f);

      catch(Exception e){
  System.err.println(e.getMessage());
}

    }
</code>```

答:
You are defining with each loop new Scanner and *Writer objects which cause the content is overwritten. Define those once and reuse with each iteration.

```<code>Scanner in = new Scanner(System.in);
FileWriter fWriter = new FileWriter(f);
BufferedWriter writr = new BufferedWriter(fWriter);

while (anw.equals("j")) {
    // ...
}
</code>```

Don't forget to close the resources after the loop.

Body:
The problem occurs from my while code, it first takes the user input and put it to the text file and ask if it wants to answer it again but every the user do that and end the loop it just takes the latest user input and just overwrites the previous input user did. But that's not what I want from my code to do. Instead, the new answer should just then be on a new line on the text file.

public static void main(String[] args) throws IOException {
    // TODO code application logic here

    int saldo = 10000;
    String anw = "j";
    int cost;

    try{
    File folder = new File("folderName");
    folder.mkdir();
    File f = new File(folder, "file1.txt"); //file to folder
    f.createNewFile(); //skapar fil
    //Scanner fileIn = new Scanner(f);
    System.out.println("File path" +f.getPath());

   //.----------------------------------
while(anw.equals("j")){

        Scanner in = new Scanner(System.in);
        FileWriter fWriter ;// removed null
        BufferedWriter writr;// removed null

        System.out.println("Ange utgiftspost:"); //post
        String post = in.nextLine();
        System.out.println("Ange kostnad:"); //kost
        cost=in.nextInt();
        in.nextLine();
        saldo = +saldo -cost;
        System.out.println("saldo:" +saldo);
        System.out.println("Vill du mata in fler uppgifter? (j/n) :");
        anw = in.nextLine();
        String fileContent = "---"+post+"---"+cost+"---"+saldo;

        fWriter = new FileWriter(f);
        writr = new BufferedWriter(fWriter);
        writr.write(fileContent);
        writr.newLine();

        if (anw.equals("n")) {
            writr.close();
            //writer.close();
        //System.out.println("---"+post+"---"+cost+"---"+saldo);

        }
    } //frågan slut
    }//try

    //Scanner fileIn = new Scanner(f);

      catch(Exception e){
  System.err.println(e.getMessage());
}

    }

Body:
You are defining with each loop new Scanner and *Writer objects which cause the content is overwritten. Define those once and reuse with each iteration.

Scanner in = new Scanner(System.in);
FileWriter fWriter = new FileWriter(f);
BufferedWriter writr = new BufferedWriter(fWriter);

while (anw.equals("j")) {
    // ...
}

Don't forget to close the resources after the loop.


问:
Microsoft Identtiy & Identity Server 4 process flow relationships
I'm working on building a series of micro-services using Aspnet Core. A mobile application, desktop application and web-application will consume the services over Http REST APIs.

For user auth, I'm utilizing the Aspnet Core Identity platform, but I'm exposing the creation of user accounts via a REST API. The clients make a REST call with the credential information and my API uses the Microsoft Identity APIs to provision the user. The user would be authorized to hit the individual resource servers with an auth server using IdentityServer4.

I have two questions that I've not been able to find clear guidance on from a security stand-point. Should the Aspnet Core project that utilizes Microsoft Identity for user creation be in an independent Aspnet Core project from the project that handles auth via IdentityServer4? Are there downsides do separating the two out that I need to consider?

The Microsoft Identity API has template and Razor Views that can be used to handle the auth from a server-side perspective, including redirects on account creation or sign-in etc. If I'm doing everything via SPA or Client-side native apps, is there anything wrong with just providing a POST API that accepts the user information, creates the account via UserManager<T> and returns the UserId?

I want to provide a dedicated sign-in page, similar to FB/Google/Twitter etc for Auth to happen across any app that wants to authorize a user for my services. I don't typically see account creation as part of the OAuth process though. Is it typical that you would allow for redirects to an account creation page, that redirects back to a client upon successful account creation or is that process typically just used for Auth via OAuth flows?

答:
I would suggest to consider using one service for IDS4 and ASP.NET Identity since they can be integrated and give you the full functionality you're looking for(auth, and users management).

IDS4 has examples and good documentations regarding that.

To me, I think separating them would be an over engineering.

one example: when IDS4 generate access token for a user, you should get claims, roles and validate username and password, all of that are stored in ASP.NET Identity.

So for more details you can check the docs of Identity Server 4: http://docs.identityserver.io/en/latest/quickstarts/0_overview.html

or it's my pleasure to check my little blog post that I tried to give some more detailed and step by step.
https://feras.blog/how-to-use-asp-net-identity-and-identityserver4-in-your-solution/

Start with IDS4 link because it might be enough :)


问:
What is wrong with my Factorial Function logic?
I'm trying to get a factorial number in the JS console in Chrome.

Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.

Thank you very much for answers <3

```<code>var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};
</code>```

答:
You have to remove var inside the for loop. Also, you should move the declaration of newX inside the function. And there's some other errors too.

```<code>function factorial(x) {
    var newX = 1
    if(x > 0){
        for(i = 1;i <= x;i++){
            newX = newX * i ;
        }
    return newX;
    }
}
</code>```

Also, for completeness, you should return 1 when x is 0 and NaN when x is negative or not an integer.

You could rewrite it as a recursive function:

```<code>function factorial(x) {
    if(x == 0) return 1;
    return x*factorial(x-1);
}
</code>```

Looks way cleaner.

Body:
I'm trying to get a factorial number in the JS console in Chrome.

Obviously, there is something wrong with my understanding of the for loop, and I'd like to know what part of it is not logical to me.

Thank you very much for answers <3

var newX

function factorial(x) {
    if(x > 0){
        for(i = 1;i <= x;i++){
            var newX = x * i ;
} return newX;
};
};

Body:
You have to remove var inside the for loop. Also, you should move the declaration of newX inside the function. And there's some other errors too.

function factorial(x) {
    var newX = 1
    if(x > 0){
        for(i = 1;i <= x;i++){
            newX = newX * i ;
        }
    return newX;
    }
}

Also, for completeness, you should return 1 when x is 0 and NaN when x is negative or not an integer.

You could rewrite it as a recursive function:

function factorial(x) {
    if(x == 0) return 1;
    return x*factorial(x-1);
}

Looks way cleaner.


问:
Do all operating systems already have JRE installed for running java applications?
Let say I am not a java developer and an ordinary person, and installing any application that is written in Java. So, do I need to first install the JRE or no all operating systems already have JRE installed on them?</p>

答:
The Java Runtime Environment has nothing to do with the OS. You could install any OS with or without the JRE. If you installed the OS yourself, I'd guess it doesn't have it. If you bought the computer with the OS on it, it depends who you bought it from.

Checking if you have JRE installed is pretty much the same on all OS. Open a Terminal (on windows run CMD) and type java --version.

If you don't have it, you need to install it. Just google install JRE on [insert your os here]


问:
Firestore - Simple full text search solution
I know that firestore doesn't support full text search and it giving us solution to use third party services. However I found a simple solution to simple "full text search" and I think this might help others who doesn't want to use third party services as me for such a simple task.
I'm trying to search for company name which is saved in firestore collection under my companyName which can be in any format for example "My Awesome Company". When adding new company with companyName or updating a value in companyName I'm also saving searchName with it which is the same value as company name but in lower case without spaces

```<code>searchName: removeSpace(companyName).toLowerCase()
</code>```

removeSpace is my simple custom function which remove all spaces from a text

```<code>export const removeSpace = (string) => {
    return string.replace(/\s/g, '');
}
</code>```

That turns our company name to myawesomecompany which is saved in searchName

Now I've got a firestore function to search for company which indexing through searchName and returning companyName. Minumum search value is a searched value without last character and maximum search value is a searched value with added "zzzzzzzzzzzzzzzzzzzzzzzz" transformed to lower case. That means if you search for My Aw then min value will be mya and max value will be myawzzzzzzzzzzzzzzzzzzzzzzz

```<code>exports.handler = ((data) => {
const searchValue = data.value.replace(/\s/g, '').toLowerCase()
const minName = searchValue.substr(0, searchName.length-1)
const maxName = searchValue + "zzzzzzzzzzzzzzzzzzzzzzzz"
let list = []
const newRef = db.collection("user").where("profile.searchName", ">=", minName).where("profile.searchName", "<=", maxName)
return newRef.get()
.then(querySnapshot => {
    querySnapshot.forEach(doc => {
        list.push({ name: doc.data().profile.companyName})
    })
    return list
})
})
</code>```

I didn't have time to fully test it but so far it works without any problems. Please let me know if you spot anything wrong with it. Now the question is

Is "z" character the highest value character in firestore or is there any other more decent way to add into the search value maximum amount without adding "zzzzzzzzzzzzz"?

答:
I like your decision to preprocess the text so that it can be queried, but you could provide for a more flexible search by storing lowercase keywords with the users and searching those.  In other words, transform:

```<code>"My Awesome Company"
</code>```

to...

```<code>{ my: true, awesome: true, company: true }
</code>```

...and test against that.

When adding/updating the property:

```<code>// save keywords on the user
let keywords = {}
companyName.split(' ').forEach(word => keywords[word.toLowerCase()] = true)
</code>```

When querying:

```<code>let searchKeywords = userInputString.split(' ').map(word => word.toLowerCase())

let collection = db.collection("user")
searchKeywords.forEach(keyword => {
  collection = collection.where(`keywords.${keyword}` , '==' , true);
});
</code>```

Body:
I know that firestore doesn't support full text search and it giving us solution to use third party services. However I found a simple solution to simple "full text search" and I think this might help others who doesn't want to use third party services as me for such a simple task.
I'm trying to search for company name which is saved in firestore collection under my companyName which can be in any format for example "My Awesome Company". When adding new company with companyName or updating a value in companyName I'm also saving searchName with it which is the same value as company name but in lower case without spaces

searchName: removeSpace(companyName).toLowerCase()

removeSpace is my simple custom function which remove all spaces from a text

export const removeSpace = (string) => {
    return string.replace(/\s/g, '');
}

That turns our company name to myawesomecompany which is saved in searchName

Now I've got a firestore function to search for company which indexing through searchName and returning companyName. Minumum search value is a searched value without last character and maximum search value is a searched value with added "zzzzzzzzzzzzzzzzzzzzzzzz" transformed to lower case. That means if you search for My Aw then min value will be mya and max value will be myawzzzzzzzzzzzzzzzzzzzzzzz

exports.handler = ((data) => {
const searchValue = data.value.replace(/\s/g, '').toLowerCase()
const minName = searchValue.substr(0, searchName.length-1)
const maxName = searchValue + "zzzzzzzzzzzzzzzzzzzzzzzz"
let list = []
const newRef = db.collection("user").where("profile.searchName", ">=", minName).where("profile.searchName", "<=", maxName)
return newRef.get()
.then(querySnapshot => {
    querySnapshot.forEach(doc => {
        list.push({ name: doc.data().profile.companyName})
    })
    return list
})
})

I didn't have time to fully test it but so far it works without any problems. Please let me know if you spot anything wrong with it. Now the question is

Is "z" character the highest value character in firestore or is there any other more decent way to add into the search value maximum amount without adding "zzzzzzzzzzzzz"?

Body:
I like your decision to preprocess the text so that it can be queried, but you could provide for a more flexible search by storing lowercase keywords with the users and searching those.  In other words, transform:

"My Awesome Company"

to...

{ my: true, awesome: true, company: true }

...and test against that.

When adding/updating the property:

// save keywords on the user
let keywords = {}
companyName.split(' ').forEach(word => keywords[word.toLowerCase()] = true)

When querying:

let searchKeywords = userInputString.split(' ').map(word => word.toLowerCase())

let collection = db.collection("user")
searchKeywords.forEach(keyword => {
  collection = collection.where(`keywords.${keyword}` , '==' , true);
});


问:
How to properly Forward the dropout layer
I created the following deep network with dropout layers like below:

```<code>class QNet_dropout(nn.Module):

    """
        A MLP with 2 hidden layer and dropout

        observation_dim (int): number of observation features
        action_dim (int): Dimension of each action
        seed (int): Random seed
    """

    def __init__(self, observation_dim, action_dim, seed):
        super(QNet_dropout, self).__init__()
        self.seed = torch.manual_seed(seed)
        self.fc1 = nn.Linear(observation_dim, 128)
        self.fc2 = nn.Dropout(0.5)
        self.fc3 = nn.Linear(128, 64)
        self.fc4 = nn.Dropout(0.5)
        self.fc5 = nn.Linear(64, action_dim)

    def forward(self, observations):
        """
           Forward propagation of neural network

        """

        x = F.relu(self.fc1(observations))
        x = F.linear(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = F.linear(self.fc4(x))
        x = self.fc5(x)
        return x
</code>```

However, when I tried to run the code, I got the following errors:

```<code>/home/workspace/QNetworks.py in forward(self, observations)
     90
     91         x = F.relu(self.fc1(observations))
---> 92         x = F.linear(self.fc2(x))
     93         x = F.relu(self.fc3(x))
     94         x = F.linear(self.fc4(x))

TypeError: linear() missing 1 required positional argument: 'weight'
</code>```

It seems like I didn't properly use/forward the dropout layer. What should be the correct way to do the Forward for the dropout layer? Thanks!

答:
The F.linear() function used incorrectly. You should use your stated linear function instead of torch.nn.functional. The dropout layer should be after Relu. You can call Relu function from torch.nn.functional. </p>

```<code>import torch
import torch.nn.functional as F

class QNet_dropout(nn.Module):

    """
        A MLP with 2 hidden layer and dropout

        observation_dim (int): number of observation features
        action_dim (int): Dimension of each action
        seed (int): Random seed
    """

    def __init__(self, observation_dim, action_dim, seed):
        super(QNet_dropout, self).__init__()
        self.seed = torch.manual_seed(seed)
        self.fc1 = nn.Linear(observation_dim, 128)
        self.fc2 = nn.Dropout(0.5)
        self.fc3 = nn.Linear(128, 64)
        self.fc4 = nn.Dropout(0.5)
        self.fc5 = nn.Linear(64, action_dim)

    def forward(self, observations):
        """
           Forward propagation of neural network

        """
        x = self.fc2(F.relu(self.fc1(observations)))
        x = self.fc4(F.relu(self.fc3(x)))
        x = self.fc5(x)
        return x

observation_dim = 512
model = QNet_dropout(observation_dim, 10, 512)
batch_size = 8
inpt  = torch.rand(batch_size, observation_dim)
output = model(inpt)
print ("output shape: ", output.shape)
</code>```

Body:
I created the following deep network with dropout layers like below:

class QNet_dropout(nn.Module):

    """
        A MLP with 2 hidden layer and dropout

        observation_dim (int): number of observation features
        action_dim (int): Dimension of each action
        seed (int): Random seed
    """

    def __init__(self, observation_dim, action_dim, seed):
        super(QNet_dropout, self).__init__()
        self.seed = torch.manual_seed(seed)
        self.fc1 = nn.Linear(observation_dim, 128)
        self.fc2 = nn.Dropout(0.5)
        self.fc3 = nn.Linear(128, 64)
        self.fc4 = nn.Dropout(0.5)
        self.fc5 = nn.Linear(64, action_dim)

    def forward(self, observations):
        """
           Forward propagation of neural network

        """

        x = F.relu(self.fc1(observations))
        x = F.linear(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = F.linear(self.fc4(x))
        x = self.fc5(x)
        return x

However, when I tried to run the code, I got the following errors:

/home/workspace/QNetworks.py in forward(self, observations)
     90
     91         x = F.relu(self.fc1(observations))
---> 92         x = F.linear(self.fc2(x))
     93         x = F.relu(self.fc3(x))
     94         x = F.linear(self.fc4(x))

TypeError: linear() missing 1 required positional argument: 'weight'

It seems like I didn't properly use/forward the dropout layer. What should be the correct way to do the Forward for the dropout layer? Thanks!

Body:
The F.linear() function used incorrectly. You should use your stated linear function instead of torch.nn.functional. The dropout layer should be after Relu. You can call Relu function from torch.nn.functional.

import torch
import torch.nn.functional as F

class QNet_dropout(nn.Module):

    """
        A MLP with 2 hidden layer and dropout

        observation_dim (int): number of observation features
        action_dim (int): Dimension of each action
        seed (int): Random seed
    """

    def __init__(self, observation_dim, action_dim, seed):
        super(QNet_dropout, self).__init__()
        self.seed = torch.manual_seed(seed)
        self.fc1 = nn.Linear(observation_dim, 128)
        self.fc2 = nn.Dropout(0.5)
        self.fc3 = nn.Linear(128, 64)
        self.fc4 = nn.Dropout(0.5)
        self.fc5 = nn.Linear(64, action_dim)

    def forward(self, observations):
        """
           Forward propagation of neural network

        """
        x = self.fc2(F.relu(self.fc1(observations)))
        x = self.fc4(F.relu(self.fc3(x)))
        x = self.fc5(x)
        return x

observation_dim = 512
model = QNet_dropout(observation_dim, 10, 512)
batch_size = 8
inpt  = torch.rand(batch_size, observation_dim)
output = model(inpt)
print ("output shape: ", output.shape)


问:
not all of my list wraps around the image
I have an unordered list and I am trying to get it to wrap around an image.  For some reason, the bottom two elements of the list "stick out".

Below is the html code I have written:

```<code><div class="skills">
    <h2>My Skills.</h2>
    <div class="skill-row">
        <img class="computer-class" src="/image/computer.png" alt="Computer">
        <h3>Makers Academy</h3>
        <ul class="list">
            <li>Agile Principles and Extreme Programming (XP) Values</li>
            <li>HTML, CSS and JavaScript</li>
            <li>Pair Programming </li>
            <li>Independent and Remote Learning</li>
            <li>Problem Solving</li>
            <li>OOP, TDD, SOLID, MVC, DDD</li>
            <li>JavaScript ES6</li>
            <li>SQL, PostgreSQL</li>
            <li>MongoDB</li>
            <li>Swift</li>
        </ul>
    </div>
</div>
</code>```

and this is the css code I have written:

```<code>h2 {
    color: #66BFBF;
    font-family: 'Monserrat', sans-serif;
    font-size: 2.5rem;
}

h3 {
    text-align: center;
    font-family: 'Montserrat', sans-serif;
    font-size: 2.8rem;
    color: #66BFBF;
    font-weight: normal;
    /* line-height: 2; */
}

.middle {
    height: 200px;
    width: 200px;
    background-color: red;
}

.bottom {
    height: 200px;
    width: 200px;
    background-color: blue;
    position: relative;
}

.bottom-cloud {
    position: absolute;
    left: 300px;
    bottom: 300px;
}

.top-cloud {
    position: absolute;
    right: 300px;
    top: 50px;
}

.list {
    text-align: left;
    position: relative;
    left: 15rem;
    width: 70%;
    margin-bottom: 100px;
    /* line-height: 2; */
}

.skill-row {
    width: 50%;
    margin: 100px auto;
}

.computer-class {
    width: 25%;
    float: left;
}

.chilli-img {
    width: 25%;
    float: left;
}
</code>```

Any help would be appreciated.  I have used pesticide to give a perspective of where the divs are.

答:
The simplest solution is to either add a left margin that is at least the width of the image to the list or to give the list overflow:auto or overflow:hidden. If you use the latter, the list's width will automatically shrink to allow room for the image.

.list {
    text-align: left;
    position: relative;
    left: 15rem;
    width: 70%;
    margin-bottom: 100px;
    /* line-height: 2; */
}

.skill-row {
    width: 50%;
    margin: 100px auto;
}

.computer-class {
    width: 25%;
    float: left;
}

.computer-class+.list {
  margin-left: 25%;
  padding-left: 2em;
  width: auto;
}

.chilli-img {
    width: 25%;
    float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="skills">
    <h2>My Skills.</h2>
    <div class="skill-row">
        <img class="computer-class" src="/image/computer.png" alt="Computer">
        <h3>Makers Academy</h3>
        <ul class="list">
            <li>Agile Principles and Extreme Programming (XP) Values</li>
            <li>HTML, CSS and JavaScript</li>
            <li>Pair Programming </li>
            <li>Independent and Remote Learning</li>
            <li>Problem Solving</li>
            <li>OOP, TDD, SOLID, MVC, DDD</li>
            <li>JavaScript ES6</li>
            <li>SQL, PostgreSQL</li>
            <li>MongoDB</li>
            <li>Swift</li>
        </ul>
    </div>
</div></code>```

```<code>.computer-class+.list {
  margin-left: auto;
  overflow: auto;
  padding-left: 2em;
  width: auto;
}
</code>```

Body:
I have an unordered list and I am trying to get it to wrap around an image.  For some reason, the bottom two elements of the list "stick out".

Below is the html code I have written:

My Skills.

Makers Academy

Agile Principles and Extreme Programming (XP) Values

HTML, CSS and JavaScript

Pair Programming

Independent and Remote Learning

Problem Solving

OOP, TDD, SOLID, MVC, DDD

JavaScript ES6

SQL, PostgreSQL

MongoDB

Swift

and this is the css code I have written:

h2 {
    color: #66BFBF;
    font-family: 'Monserrat', sans-serif;
    font-size: 2.5rem;
}

h3 {
    text-align: center;
    font-family: 'Montserrat', sans-serif;
    font-size: 2.8rem;
    color: #66BFBF;
    font-weight: normal;
    /* line-height: 2; */
}

.middle {
    height: 200px;
    width: 200px;
    background-color: red;
}

.bottom {
    height: 200px;
    width: 200px;
    background-color: blue;
    position: relative;
}

.bottom-cloud {
    position: absolute;
    left: 300px;
    bottom: 300px;
}

.top-cloud {
    position: absolute;
    right: 300px;
    top: 50px;
}

.list {
    text-align: left;
    position: relative;
    left: 15rem;
    width: 70%;
    margin-bottom: 100px;
    /* line-height: 2; */
}

.skill-row {
    width: 50%;
    margin: 100px auto;
}

.computer-class {
    width: 25%;
    float: left;
}

.chilli-img {
    width: 25%;
    float: left;
}

Any help would be appreciated.  I have used pesticide to give a perspective of where the divs are.

Body:
The simplest solution is to either add a left margin that is at least the width of the image to the list or to give the list overflow:auto or overflow:hidden. If you use the latter, the list's width will automatically shrink to allow room for the image.

.list {
    text-align: left;
    position: relative;
    left: 15rem;
    width: 70%;
    margin-bottom: 100px;
    /* line-height: 2; */
}

.skill-row {
    width: 50%;
    margin: 100px auto;
}

.computer-class {
    width: 25%;
    float: left;
}

.computer-class+.list {
  margin-left: 25%;
  padding-left: 2em;
  width: auto;
}

.chilli-img {
    width: 25%;
    float: left;
}

<div class="skills">
    <h2>My Skills.</h2>
    <div class="skill-row">
        <img class="computer-class" src="/image/computer.png" alt="Computer">
        <h3>Makers Academy</h3>
        <ul class="list">
            <li>Agile Principles and Extreme Programming (XP) Values</li>
            <li>HTML, CSS and JavaScript</li>
            <li>Pair Programming </li>
            <li>Independent and Remote Learning</li>
            <li>Problem Solving</li>
            <li>OOP, TDD, SOLID, MVC, DDD</li>
            <li>JavaScript ES6</li>
            <li>SQL, PostgreSQL</li>
            <li>MongoDB</li>
            <li>Swift</li>
        </ul>
    </div>
</div>

.computer-class+.list {
  margin-left: auto;
  overflow: auto;
  padding-left: 2em;
  width: auto;
}


答:
You would require some interpolation methods to get a smooth spline/curve. That is in itself a different question. I will answer the question regarding the different scales. Since the order of magnitudes of your data are quite different, in such situations, the best solution is to use a logarithmic y-scale using semilogy. P.S: You had written mse_loss instead of rmse_loss in the last plot line.

```<code>plt.semilogy(epochs, mae_loss, 'b', label='MAE')
plt.semilogy(epochs, mse_loss, 'r', label='MSE')
plt.semilogy(epochs, rmse_loss, 'g', label='RMSE')
plt.legend()
plt.show()
</code>```

Title: Plotting multiple curve line plots in python with Matplotlib

Body:
I am trying to plot 3 loss curves in one figure. I have the following problems.

I can't get a smooth curve, instead it joins point-to-point in a sharp line

How do I change the scales of the axis, to display the MSE loss which disappears because it is too small?

from matplotlib import pyplot as plt

epochs=list(range(5000,50001,5000))
print(epochs)
mae_loss=[0.500225365,
0.000221096,
0.000060971,
0.000060323,
0.000059905,
0.000059579,
0.000059274,
0.000058972,
0.000058697,
0.000058476]

mse_loss=[0.135419831,
0.018331185,
0.002481434,
0.000335913,
0.000045486,
0.000006180,
0.000000867,
0.000000147,
0.000000042,
0.000000042]

rmse_loss=[0.500225306,
0.000293739,
0.000126985,
0.000121944,
0.000119484,
0.000117791,
0.000116400,
0.000115198,
0.000114148,
0.000113228]

plt.plot(epochs, mae_loss, 'b', label='MAE')
plt.plot(epochs, mse_loss, 'r', label='MSE')
plt.plot(epochs, mse_loss, 'g', label='RMSE')
plt.legend()
plt.show()

Body:
You would require some interpolation methods to get a smooth spline/curve. That is in itself a different question. I will answer the question regarding the different scales. Since the order of magnitudes of your data are quite different, in such situations, the best solution is to use a logarithmic y-scale using semilogy. P.S: You had written mse_loss instead of rmse_loss in the last plot line.

plt.semilogy(epochs, mae_loss, 'b', label='MAE')
plt.semilogy(epochs, mse_loss, 'r', label='MSE')
plt.semilogy(epochs, rmse_loss, 'g', label='RMSE')
plt.legend()
plt.show()


问:
Understanding the future of the .NET framework
I currently use Qt for my desktop app (simple apps) development. The one thing I don’t like about Qt is the fact that I have a feeling that the free license will eventually disappear and I would rather move to a different framework. On the other side I have been hearing about .NET going open source and cross platform.

Can someone clarify what exactly does this means because I have read that only the server side will be open sourced and cross platform but I’m not sure if this will only affect Linux servers.

Does this mean that we will be able to create cross platform application in Visual Studio?

Does this means that Visual Studio will run on Linux and Mac?

Thanks a lot

答:
Breaking news:  This just in from Scott Hunter, Director of .NET Program Management:

All future investment in .NET will be in .NET Core. This includes:
  Runtime, JIT, AOT, GC, BCL (Base Class Library), C#, VB.NET, F#,
  ASP.NET, Entity Framework, ML.NET, WinForms, WPF and Xamarin.

https://devblogs.microsoft.com/dotnet/net-core-is-the-future-of-net/