问:
Unable to deploy Django on local with gunicorn and nginx
I am trying to deploy my first django web app. My knowledge in web servers is near by 0. After having configured everything, I get 502 Bad Gateway when trying to access my page.

Gunicorn command

sudo gunicorn website.wsgi --log-level debug -u root -group root. This allow me to access my app on localhost:8000, but the medias and static are not working.

Nginx configuration:

```<code>worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server{
        listen 80;
        server_name localhost.kevin.lo;
        charset utf-8;

        access_log /var/log/nginx/oktomus.access.log;
        error_log /var/log/nginx/oktomus.error.log;

        location /media {
            alias /home/oktomus/workspace/code/web/website-prod/media;
        }

        location /static {
            alias /home/oktomus/workspace/code/web/website-prod/static;
        }

        location / {
            include fastcgi_params;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_set_header X-Real-IP $remote_addr;
            fastcgi_pass localhost:8000;

        }

    }
}
</code>```

Nginx error

The error log when I try too access the app on port 80.

```<code>2017/07/05 21:06:20 [error] 9767#9767: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://[::1]:8000", host: "localhost"
2017/07/05 21:07:00 [error] 9767#9767: *7 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:8000", host: "localhost"
2017/07/05 21:07:31 [error] 9767#9767: *7 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:8000", host: "localhost"
2017/07/05 21:07:31 [error] 9767#9767: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://[::1]:8000", host: "localhost"
</code>```

Gunicorn output

This is what output when I try to access the app and then stop the browser after few seconds.

```<code>[10024] [DEBUG] Ignored premature client disconnection. No more data after: b'\x01\x01\x00\x01\x00\x08\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x01\x04\x00\x01\x03\x06\x02\x00\x0c\x00QUERY_STRING\x0e\x03REQUEST_METHODGET\x0c\x00CONTENT_TYPE\x0e\x00CONTENT_LENGTH\x0b\x01SCRIPT_NAME/\x0b\x01REQUEST_URI/\x0c\x01DOCUMENT_URI/\r\x0fDOCUMENT_ROOT/etc/nginx/html\x0f\x08SERVER_PROTOCOLHTTP/1.1\x0e\x04REQUEST_SCHEMEhttp\x11\x07GATEWAY_INTERFACECGI/1.1\x0f\x0cSERVER_SOFTWAREnginx/1.12.0\x0b\tREMOTE_ADDR127.0.0.1\x0b\x05REMOTE_PORT37886\x0b\tSERVER_ADDR127.0.0.1\x0b\x02SERVER_PORT80\x0b\x12SERVER_NAMElocalhost.kevin.lo\x0f\x03REDIRECT_STATUS200\t\tHTTP_HOSTlocalhost\x0fDHTTP_USER_AGENTMozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0\x0b?HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\x14\x0eHTTP_ACCEPT_LANGUAGEen-US,en;q=0.5\x14\rHTTP_ACCEPT_ENCODINGgzip, deflate\x0bJHTTP_COOKIEcsrftoken=bOeYkxXdfepIfgwiNnNMeT21NznPM3y1fAR07wp8MyCJtAAbrXdiVfHZxbmuSx0l\x08\x01HTTP_DNT1\x0f\nHTTP_CONNECTIONkeep-alive\x1e\x01HTTP_UPGRADE_INSECURE_REQUESTS1\x00\x00\x01\x04\x00\x01\x00\x00\x00\x00\x01\x05\x00\x01\x00\x00\x00\x00'
</code>```

And if I don't stop the browser, I land on 502 nginx Bad Gateway, and gunicorn outputs this.

```<code>[2017-07-05 21:29:04 +0200] [10135] [CRITICAL] WORKER TIMEOUT (pid:10146)
</code>```

I have readed the nginx beginer's guide which helped me understand few things, but still I don't know what to do to solve this problem.

答: I was just following too old tutorials. I readed the gunicorn documentation, and it works perfectly. </p>

Body:
I am trying to deploy my first django web app. My knowledge in web servers is near by 0. After having configured everything, I get 502 Bad Gateway when trying to access my page.

Gunicorn command

sudo gunicorn website.wsgi --log-level debug -u root -group root. This allow me to access my app on localhost:8000, but the medias and static are not working.

Nginx configuration:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server{
        listen 80;
        server_name localhost.kevin.lo;
        charset utf-8;

        access_log /var/log/nginx/oktomus.access.log;
        error_log /var/log/nginx/oktomus.error.log;

        location /media {
            alias /home/oktomus/workspace/code/web/website-prod/media;
        }

        location /static {
            alias /home/oktomus/workspace/code/web/website-prod/static;
        }

        location / {
            include fastcgi_params;
            proxy_set_header X-Forwarded-Host $server_name;
            proxy_set_header X-Real-IP $remote_addr;
            fastcgi_pass localhost:8000;

        }

    }
}

Nginx error

The error log when I try too access the app on port 80.

2017/07/05 21:06:20 [error] 9767#9767: *4 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://[::1]:8000", host: "localhost"
2017/07/05 21:07:00 [error] 9767#9767: *7 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:8000", host: "localhost"
2017/07/05 21:07:31 [error] 9767#9767: *7 upstream prematurely closed connection while reading response header from upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://127.0.0.1:8000", host: "localhost"
2017/07/05 21:07:31 [error] 9767#9767: *7 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: localhost.kevin.lo, request: "GET / HTTP/1.1", upstream: "fastcgi://[::1]:8000", host: "localhost"

Gunicorn output

This is what output when I try to access the app and then stop the browser after few seconds.

[10024] [DEBUG] Ignored premature client disconnection. No more data after: b'\x01\x01\x00\x01\x00\x08\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x01\x04\x00\x01\x03\x06\x02\x00\x0c\x00QUERY_STRING\x0e\x03REQUEST_METHODGET\x0c\x00CONTENT_TYPE\x0e\x00CONTENT_LENGTH\x0b\x01SCRIPT_NAME/\x0b\x01REQUEST_URI/\x0c\x01DOCUMENT_URI/\r\x0fDOCUMENT_ROOT/etc/nginx/html\x0f\x08SERVER_PROTOCOLHTTP/1.1\x0e\x04REQUEST_SCHEMEhttp\x11\x07GATEWAY_INTERFACECGI/1.1\x0f\x0cSERVER_SOFTWAREnginx/1.12.0\x0b\tREMOTE_ADDR127.0.0.1\x0b\x05REMOTE_PORT37886\x0b\tSERVER_ADDR127.0.0.1\x0b\x02SERVER_PORT80\x0b\x12SERVER_NAMElocalhost.kevin.lo\x0f\x03REDIRECT_STATUS200\t\tHTTP_HOSTlocalhost\x0fDHTTP_USER_AGENTMozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0\x0b?HTTP_ACCEPTtext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\x14\x0eHTTP_ACCEPT_LANGUAGEen-US,en;q=0.5\x14\rHTTP_ACCEPT_ENCODINGgzip, deflate\x0bJHTTP_COOKIEcsrftoken=bOeYkxXdfepIfgwiNnNMeT21NznPM3y1fAR07wp8MyCJtAAbrXdiVfHZxbmuSx0l\x08\x01HTTP_DNT1\x0f\nHTTP_CONNECTIONkeep-alive\x1e\x01HTTP_UPGRADE_INSECURE_REQUESTS1\x00\x00\x01\x04\x00\x01\x00\x00\x00\x00\x01\x05\x00\x01\x00\x00\x00\x00'

And if I don't stop the browser, I land on 502 nginx Bad Gateway, and gunicorn outputs this.

[2017-07-05 21:29:04 +0200] [10135] [CRITICAL] WORKER TIMEOUT (pid:10146)

I have readed the nginx beginer's guide which helped me understand few things, but still I don't know what to do to solve this problem.


来源: stackexchange

问:
What are possible pandas basic / scalar data types?
I found the list of NumPy's scalar types: https://docs.scipy.org/doc/numpy-1.12.0/user/basics.types.html

I know that pandas adds timestamp types to these. Are there any more types? Is there a comprehensive list of pandas scalar types somewhere?

答:
Generally (and loosely) speaking, pandas columns are just labelled numpy arrays and have comparable dtypes.  The only exception I know of is the pandas categorical type.

Here's an example dtype listing from the official docs.  Not guaranteed to be exhaustive, but to the best of my knowledge it is pretty close.

```<code>In [423]: df.dtypes
Out[423]:
bool1                                   bool
bool2                                   bool
category                            category
dates                         datetime64[ns]
float64                              float64
int64                                  int64
string                                object
uint8                                  uint8
tdeltas                      timedelta64[ns]
uint64                                uint64
other_dates                   datetime64[ns]
tz_aware_dates    datetime64[ns, US/Eastern]
dtype: object
</code>```

Note that the object dtype includes strings and is basically just anything except an int, float, bool, category, or datetime/timedelta.  An object dtype is really just a holder for any generic python type and could be a list, dictionary, etc.

ContentLicense: CC BY-SA 3.0

Body:
Generally (and loosely) speaking, pandas columns are just labelled numpy arrays and have comparable dtypes.  The only exception I know of is the pandas categorical type.

Here's an example dtype listing from the official docs.  Not guaranteed to be exhaustive, but to the best of my knowledge it is pretty close.

In [423]: df.dtypes
Out[423]:
bool1                                   bool
bool2                                   bool
category                            category
dates                         datetime64[ns]
float64                              float64
int64                                  int64
string                                object
uint8                                  uint8
tdeltas                      timedelta64[ns]
uint64                                uint64
other_dates                   datetime64[ns]
tz_aware_dates    datetime64[ns, US/Eastern]
dtype: object

Note that the object dtype includes strings and is basically just anything except an int, float, bool, category, or datetime/timedelta.  An object dtype is really just a holder for any generic python type and could be a list, dictionary, etc.


问:
How can I train a naivebayes classifier incrementally?
Using Accord.NET I've created a NaiveBayes classifier. It will classify a pixel based on 6 or so sets of image processing results. My images are 5MP, so a training set of 50 images creates a very large set of training data.

6 int array per pixel * 5 million pixels * 50 images.

Instead of trying to store all that data in memory, is there a way to incrementally train the NaiveBayes classifier?  Calling Learn() multiple times overwrites the old data each time rather than adding to it.

答:
Right now is not possible to train a Naive Bayes model incrementally using Accord.NET.

However, since all that Naive Bayes is going to do is to try to fit some distributions to your data, and since your data has very few dimensions, maybe you could try to learn your model on a subsample of your data rather than all of it at once.

When you go loading images to build your training set, you can try to randomly discard x% of the pixels in each image. You can also plot the classifier accuracy for different values of x to find the best balance between memory and accuracy for your model (hint: for such a small model and this large amount of training data, I expect that it wont make that much of a difference even if you dropped 50% of your data).


问:
RatingBar and RecyclerView
I am trying to make an application that rates 8 different types of foods with simple rater and recyclerview. Pressing the FAB button just adds a random food with 0 rating. I have gotten most of it to work except the rating of the rating bar. When I scroll up or down, I lose the ratings I had. How can I store the ratings of food when I scroll up or down.

RecyclerView:

```<code>package com.mycompany.alawamhm.foodrater;

import android.content.Context;
import android.graphics.Movie;
import android.icu.text.AlphabeticIndex;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.iarcuschin.simpleratingbar.SimpleRatingBar;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.xml.transform.sax.SAXSource;

public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder>{

private Random mRandom = new Random();
private RecyclerView mRecyclerView;
final HashMap<String,Integer> defaultName;
final ArrayList<String> mNames=new ArrayList<>();

public FoodAdapter(RecyclerView rv){
    defaultName = new HashMap<>();
    defaultName.put("banana", R.drawable.banana);
    defaultName.put("broccoli", R.drawable.broccoli);
    defaultName.put("homemade bread", R.drawable.bread);
    defaultName.put("chicken", R.drawable.chicken);
    defaultName.put("chocolate", R.drawable.chocolate);
    defaultName.put("ice cream", R.drawable.icecream);
    defaultName.put("lima beans", R.drawable.limabeans);
    defaultName.put("steak", R.drawable.steak);
    for(String name : defaultName.keySet()){
        mNames.add(name);
    }
    mRecyclerView = rv;

}

public String getRandomName(){
    String[] names = new String[]{
            "banana","broccoli","homemade bread","chicken",
            "chocolate","ice cream","lima beans","steak"
    };
    return names[mRandom.nextInt(names.length)];
}

public void addName(){
    mNames.add(0,getRandomName());
    notifyItemInserted(0);
    mRecyclerView.getLayoutManager().scrollToPosition(0);
}

@Override
public FoodAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.name_view,parent,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    String name = mNames.get(position);
    holder.mNameTextView.setText(name);
    holder.mImage.setImageResource(defaultName.get(name));
    holder.rBar.setRating(0);
}

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

public void removeName(int position){
    mNames.remove(position);
    notifyItemRemoved(position);
}

class ViewHolder extends RecyclerView.ViewHolder{

    private TextView mNameTextView;
    private ImageView mImage;
    SimpleRatingBar rBar;

    public ViewHolder(View itemView) {
        super(itemView);
        mNameTextView = (TextView)itemView.findViewById(R.id.name_view);
        mImage = (ImageView)itemView.findViewById(R.id.imageView);
        rBar = (SimpleRatingBar)itemView.findViewById(R.id.ratingBar);
    }
}
</code>```

}

答: Currently the ratings bar is being set to 0 every time a view is bound to a view holder. Set a listener on the rating bar that runs a method to store the new rating value in a hashSet. Then in the adapter, instead of setting the rating bar to 0, add a helper method that iterates through the hashMap to check if a value has been stored for the food being inflated. This method should return the stored value or 0 if the food hasn't stored a value yet.</p>

Title: RatingBar and RecyclerView

Body:
I am trying to make an application that rates 8 different types of foods with simple rater and recyclerview. Pressing the FAB button just adds a random food with 0 rating. I have gotten most of it to work except the rating of the rating bar. When I scroll up or down, I lose the ratings I had. How can I store the ratings of food when I scroll up or down.

RecyclerView:

package com.mycompany.alawamhm.foodrater;

import android.content.Context;
import android.graphics.Movie;
import android.icu.text.AlphabeticIndex;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.iarcuschin.simpleratingbar.SimpleRatingBar;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.xml.transform.sax.SAXSource;

public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder>{

private Random mRandom = new Random();
private RecyclerView mRecyclerView;
final HashMap<String,Integer> defaultName;
final ArrayList<String> mNames=new ArrayList<>();

public FoodAdapter(RecyclerView rv){
    defaultName = new HashMap<>();
    defaultName.put("banana", R.drawable.banana);
    defaultName.put("broccoli", R.drawable.broccoli);
    defaultName.put("homemade bread", R.drawable.bread);
    defaultName.put("chicken", R.drawable.chicken);
    defaultName.put("chocolate", R.drawable.chocolate);
    defaultName.put("ice cream", R.drawable.icecream);
    defaultName.put("lima beans", R.drawable.limabeans);
    defaultName.put("steak", R.drawable.steak);
    for(String name : defaultName.keySet()){
        mNames.add(name);
    }
    mRecyclerView = rv;

}

public String getRandomName(){
    String[] names = new String[]{
            "banana","broccoli","homemade bread","chicken",
            "chocolate","ice cream","lima beans","steak"
    };
    return names[mRandom.nextInt(names.length)];
}

public void addName(){
    mNames.add(0,getRandomName());
    notifyItemInserted(0);
    mRecyclerView.getLayoutManager().scrollToPosition(0);
}

@Override
public FoodAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.name_view,parent,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    String name = mNames.get(position);
    holder.mNameTextView.setText(name);
    holder.mImage.setImageResource(defaultName.get(name));
    holder.rBar.setRating(0);
}

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

public void removeName(int position){
    mNames.remove(position);
    notifyItemRemoved(position);
}

class ViewHolder extends RecyclerView.ViewHolder{

    private TextView mNameTextView;
    private ImageView mImage;
    SimpleRatingBar rBar;

    public ViewHolder(View itemView) {
        super(itemView);
        mNameTextView = (TextView)itemView.findViewById(R.id.name_view);
        mImage = (ImageView)itemView.findViewById(R.id.imageView);
        rBar = (SimpleRatingBar)itemView.findViewById(R.id.ratingBar);
    }
}

}


问:
SPA client accessing ServiceStack session
I am developing a SPA in Angular 4 backed by ServiceStack based web services and wanted to enable the SPA to check if the user is already authenticated using the Redis cache client implemented in the backend against a custom auth provider instead of having them to login again. So, when the user is logged into another ServiceStack based application which also has the Redis cache client enabled and transfers over to this application's link (hosted as another app in the same domain), they don't have to sign in. Should I be passing any cookies or anything over to the new application as I transfer them over to the new application? Any pointers would be appreciated.

ServiceStack Authentication Documentation describes the concept of using HTTP headers to send session cookies. Is this something I can utilize and how and where in the life cycle of the application can I capture this information to check the user is already signed in? Any pointers would be appreciated.

Thanks

John

答:
If you have 2 different ServiceStack instances configured to use the same Redis Caching Provider and Custom Auth Provider then you would only need to send the same Session Cookies in order to be treated as authenticated in both.

(hosted as another app in the same domain)

If it's hosted in the same domain at different hosts, e.g:

```<code>domain.com/app1
domain.com/app2
</code>```

Then the Session Cookies will automatically be sent when an Ajax Request is made to either App.

However if the App's are in separate sub domains, e.g:

```<code>app1.domain.com
app2.domain.com
</code>```

They're treated as 2 different domains by default which won't be able to share cookies, but you can specify that cookies should apply to your root domain instead by configuring it in your Web.config:

```<code><system.web>
    <httpCookies domain=".domain.com" />
</system.web>
</code>```

Where your Ajax requests will send Cookies to both sub domains.

If you have Apps hosted in 2 different domains you wont be able to share cookies in which case you can try sending them as Custom HTTP Headers which if your using ServiceStack's TypeScript JsonServiceClient you can populate it with:

```<code> var client = new JsonServiceClient(baseUrl);
 client.headers.set('X-ss-id', sessionId);
</code>```

The issue then becomes allowing Ajax clients to send custom HTTP Headers across domains which you'll need to register in your CorsFeature, e.g:

```<code>Plugins.Add(new CorsFeature(
    allowOriginWhitelist: new[] { "http://source.domain.com" },
    allowCredentials: true,
    allowedHeaders: "Content-Type, Allow, Authorization, X-ss-id"));
</code>```

Note: the session Id is returned in the ss-id cookie or you can get it from the AuthenticateResponse DTO by calling /auth endpoint from an authenticated user.

Body:
If you have 2 different ServiceStack instances configured to use the same Redis Caching Provider and Custom Auth Provider then you would only need to send the same Session Cookies in order to be treated as authenticated in both.

(hosted as another app in the same domain)

If it's hosted in the same domain at different hosts, e.g:

domain.com/app1
domain.com/app2

Then the Session Cookies will automatically be sent when an Ajax Request is made to either App.

However if the App's are in separate sub domains, e.g:

app1.domain.com
app2.domain.com

They're treated as 2 different domains by default which won't be able to share cookies, but you can specify that cookies should apply to your root domain instead by configuring it in your Web.config:

<system.web>
    <httpCookies domain=".domain.com" />
</system.web>

Where your Ajax requests will send Cookies to both sub domains.

If you have Apps hosted in 2 different domains you wont be able to share cookies in which case you can try sending them as Custom HTTP Headers which if your using ServiceStack's TypeScript JsonServiceClient you can populate it with:

 var client = new JsonServiceClient(baseUrl);
 client.headers.set('X-ss-id', sessionId);

The issue then becomes allowing Ajax clients to send custom HTTP Headers across domains which you'll need to register in your CorsFeature, e.g:

Plugins.Add(new CorsFeature(
    allowOriginWhitelist: new[] { "http://source.domain.com" },
    allowCredentials: true,
    allowedHeaders: "Content-Type, Allow, Authorization, X-ss-id"));

Note: the session Id is returned in the ss-id cookie or you can get it from the AuthenticateResponse DTO by calling /auth endpoint from an authenticated user.


问:
Showing Filename Differences in List Array (Java)
I am trying to compare files and my solution works with folders that have a small amount of files in them like 10 but not folders with like over 200 filenames in them. The last part of my codes comes back NULL or Results = [ ] usually the text file(s) name is in here that shows the difference between both folders any help is appreciated. The problem is the last part of my code

```<code>package nameCompare;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// https://stackoverflow.com/questions/19662384/comparing-file-names
// http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-program-can-list-all-files-given-directory.html

public class fileNameCompare {

    public static void main(String[] args) {
                             // first directory path here
        String path1 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path1 = "C:/Users/Jonathan/Desktop/FolderA";

        // second directory path here
        String path2 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path2 = "C:/Users/Jonathan/Desktop/FolderB";

        File folder1 = new File(path1);
        int fileCount = folder1.list().length;

        File folder2 = new File(path2);
        int fileCountTwo = folder2.list().length;

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        //we'll need these to store the file names as Strings
        ArrayList<String> BeforeMM = new ArrayList<String>();
        ArrayList<String> AfterMM = new ArrayList<String>();

        //get file names from directory
        for (int i = 0; i < listOfFiles1.length; i++)
        {
            if (listOfFiles1[i].isFile())
            {
                BeforeMM.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {
            if (listOfFiles2[i].isFile())
            {
                AfterMM.add(listOfFiles2[i].getName());//seriously wow
            }
        }

            // Number of Files in each Folder or Directory
            System.out.println("Files in FolderA / BeforeMM ----> " + fileCount );
            System.out.println("Files in FolderB / AfterMM -----> " + fileCountTwo );
            System.out.println("------------------------------------");

            System.out.println( "Size/Number of Array Elements BeforeMM -----> "+BeforeMM.size() );
            System.out.println( "Size/Number of Array Elements AfterMM  -----> "+AfterMM.size() );
            System.out.println("------------------------------------");

            System.out.println("Before Media Folder Conatins----> " + BeforeMM );
            System.out.println("After Media Folder  Conatins----> " + AfterMM );
            System.out.println("------------------------------------");
            //this is where problems start
            List<String> result = AfterMM.stream().filter(elem -> !BeforeMM.contains(elem)).collect(Collectors.toList());
            System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:\n" + result);
            // Result equals Test2.txt

            /*// Remove all elements in BeforeFolder from AfterFolder
            BeforeMM.removeAll(AfterMM);
            // Show results
            System.out.println("Result: " + AfterMM);
            */

    }

}
</code>```

答:
It's much simpler than that... You can simply use removeAll():

```<code>List<String> copied = new ArrayList<>(AfterMM); //copy the list
copied.removeAll(BeforeMM);// this removes from copied everything that's in BeforeMM (if it's also in copied).
</code>```

And then to print them all you can simply do:

```<code>System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:"+copied);
</code>```

And that will print the contents of copied, which contain everything that is in AfterMM but isn't in BeforeMM

Also, as was pointed out, you are listing the same folders:

```<code>"C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
</code>```

And then your result would always be []. You'll get other results if you give path1 and path2 different values.

I don't think you can have * in a filename, but a - shouldn't cause any trouble.

Body:
I am trying to compare files and my solution works with folders that have a small amount of files in them like 10 but not folders with like over 200 filenames in them. The last part of my codes comes back NULL or Results = [ ] usually the text file(s) name is in here that shows the difference between both folders any help is appreciated. The problem is the last part of my code

package nameCompare;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// https://stackoverflow.com/questions/19662384/comparing-file-names
// http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-program-can-list-all-files-given-directory.html

public class fileNameCompare {

    public static void main(String[] args) {
                             // first directory path here
        String path1 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path1 = "C:/Users/Jonathan/Desktop/FolderA";

        // second directory path here
        String path2 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path2 = "C:/Users/Jonathan/Desktop/FolderB";

        File folder1 = new File(path1);
        int fileCount = folder1.list().length;

        File folder2 = new File(path2);
        int fileCountTwo = folder2.list().length;

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        //we'll need these to store the file names as Strings
        ArrayList<String> BeforeMM = new ArrayList<String>();
        ArrayList<String> AfterMM = new ArrayList<String>();

        //get file names from directory
        for (int i = 0; i < listOfFiles1.length; i++)
        {
            if (listOfFiles1[i].isFile())
            {
                BeforeMM.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {
            if (listOfFiles2[i].isFile())
            {
                AfterMM.add(listOfFiles2[i].getName());//seriously wow
            }
        }

            // Number of Files in each Folder or Directory
            System.out.println("Files in FolderA / BeforeMM ----> " + fileCount );
            System.out.println("Files in FolderB / AfterMM -----> " + fileCountTwo );
            System.out.println("------------------------------------");

            System.out.println( "Size/Number of Array Elements BeforeMM -----> "+BeforeMM.size() );
            System.out.println( "Size/Number of Array Elements AfterMM  -----> "+AfterMM.size() );
            System.out.println("------------------------------------");

            System.out.println("Before Media Folder Conatins----> " + BeforeMM );
            System.out.println("After Media Folder  Conatins----> " + AfterMM );
            System.out.println("------------------------------------");
            //this is where problems start
            List<String> result = AfterMM.stream().filter(elem -> !BeforeMM.contains(elem)).collect(Collectors.toList());
            System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:\n" + result);
            // Result equals Test2.txt

            /*// Remove all elements in BeforeFolder from AfterFolder
            BeforeMM.removeAll(AfterMM);
            // Show results
            System.out.println("Result: " + AfterMM);
            */

    }

}

Body:
It's much simpler than that... You can simply use removeAll():

List<String> copied = new ArrayList<>(AfterMM); //copy the list
copied.removeAll(BeforeMM);// this removes from copied everything that's in BeforeMM (if it's also in copied).

And then to print them all you can simply do:

System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:"+copied);

And that will print the contents of copied, which contain everything that is in AfterMM but isn't in BeforeMM

Also, as was pointed out, you are listing the same folders:

"C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";

And then your result would always be []. You'll get other results if you give path1 and path2 different values.

I don't think you can have * in a filename, but a - shouldn't cause any trouble.


问:
C++ parallel average matrix with OpenMP
I have this code in C++ that calculates the average of each column of a matrix. I want to parallelize the code using OpenMP.

#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

vector<double> average(const vector<vector<unsigned char>>& original){
  vector<vector<double>> result(original.size(), vector<double>(original[0].size()));
  vector<double> average(original[0].size(), 0.0);

  for (int i=0; i<original.size(); i++) {
    const vector<unsigned char>& vector = original[i];
    for (int k = 0; k < vector.size(); ++k) {
      average[k] += vector[k];
    }
  }
  for (double& val : average) {
    val /= original.size();
  }

  return average;
}
```

Adding #pragma omp parallel for before the outer for loop gets me bogus results. Do you have any pointers? I thought I would find tons of examples of this online but wasn't able to find much. This is my first time using OpenMP.

答:
Frank is right in saying that your immediate problem may be that you're using a non-atomic operation:

```<code>average[k] += vector[k];
</code>```

You can fix that by using:

```<code>#pragma omp atomic
average[k] += vector[k];
</code>```

But a larger conceptual problem is that this probably will not speed up your code. The operations you are doing a very simple and your memory (at least the rows) are contiguous.

Indeed, I have made a Minimum Working Example for your code (you should have done this for your question):

```<code>#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

vector<float> average(const vector<vector<unsigned char>>& original){
  vector<float> average(original[0].size(), 0.0);

  #pragma omp parallel for
  for (int i=0; i<original.size(); i++) {
    const vector<unsigned char>& vector = original[i];
    for (int k = 0; k < vector.size(); ++k) {
      #pragma omp atomic
      average[k] += vector[k];
    }
  }
  for (float& val : average) {
    val /= original.size();
  }

  return average;
}

int main(){
  vector<vector<unsigned char>> mat(1000);
  for(int y=0;y<mat.size();y++)
  for(int x=0;x<mat.size();x++)
    mat.at(y).emplace_back(rand()%255);

  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  double dont_optimize = 0;
  for(int i=0;i<100;i++){
    auto ret = average(mat);
    dont_optimize += ret[0];
  }
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

  std::cout<<"Time = "<<(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/100)<<std::endl;

  return 0;
}
</code>```

Compiling this with g++ -O3 temp.cpp -fopenmp enables OpenMP. Run-times on my four-core machine are consistently about 10,247 microseconds. When I disable OpenMP, run-times are about 2,561 microseconds.

Starting and managing a thread team is expensive.

But there is a real way to speed up your code: improve your memory layout.

Using a std::vector< std::vector<T> > design means that each vector<T> can be located anywhere in memory. Rather, we would like all our memory nice and contiguous. We can achieve this by using flat-array indexing, like so:

(Note that an earlier version of the below code used, e.g., mat.at(y*width+x). The range checking this implies results in a significant loss of speed versus using mat[y*width+x], as the code now does. Times have been updated appropriately.)

```<code>#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

class Matrix {
 public:
  vector<unsigned char> mat;
  int width;
  int height;
  Matrix(int width0, int height0){
    width  = width0;
    height = height0;
    for(int i=0;i<width*height;i++)
      mat.emplace_back(rand()%255);
  }
  unsigned char& operator()(int x, int y){
    return mat[y*width+x];
  }
  unsigned char operator()(int x, int y) const {
    return mat[y*width+x];
  }
  unsigned char& operator()(int i){
    return mat[i];
  }
  unsigned char operator()(int i) const {
    return mat[i];
  }
};

vector<float> average(const Matrix& original){
  vector<float> average(original.width, 0.0);

  #pragma omp parallel for
  for(int y=0;y<original.height;y++)
  for(int x=0;x<original.width;x++)
    #pragma omp atomic
    average[x] += original(x,y);

  for (float& val : average)
    val /= original.height;

  return average;
}

int main(){
  Matrix mat(1000,1000);

  std::cerr<<mat.width<<" "<<mat.height<<std::endl;

  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  double dont_optimize = 0;
  for(int i=0;i<100;i++){
    auto ret = average(mat);
    dont_optimize += ret[0];
  }
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

  std::cout<<"Time = "<<(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/100)<<std::endl;

  return 0;
}
</code>```

Note that I am also using float instead of double: you can cram twice the numbers into the same amount of space this way, which is good for caching.

This gives run-times of 292 microseconds without OpenMP and 9426 microseconds with OpenMP.

In conclusion, using OpenMP/parallelism slows down your code because the work being done in parallel takes less time than setting up the parallelism, but using a better memory layout gives a ~90% increase in speed. In addition, using the handy Matrix class I create improves your code's readability and maintainability.

Edit:

Running this on matrices that are 10,000x10,000 instead of 1,000x1,000 gives similar results. For the vector of vectors: 7,449 microseconds without OpenMP and 156,316 microseconds with OpenMP. For flat-array indexing: 32,668 miroseconds without OpenMP and 145,470 microseconds with OpenMP.

The performance may be related to the hardware instruction set available on my machine (particularly, if my machine lacks atomic instructions then OpenMP will have to simulate them with mutexes and such). Indeed, in the flat-array example compiling with -march=native gives improved, though still not-great, performance for OpenMP: 33,079 microseconds without OpenMP and 127,841 microseconds with OpenMP. I will experiment with a more powerful machine later.

Edit

While the aforementioned testing was performed on the Intel(R) Core(TM) i5 CPU M 480 @ 2.67GHz, I have compiled this code (with -O3 -march=native) on the badass Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz. The results are similar:

1000x1000, Vector of vectors, without OpenMP: 145μs

1000x1000, Vector of vectors, with OpenMP: 2,941μs

10000x10000, Vector of vectors, without OpenMP: 20,254μs

10000x10000, Vector of vectors, with OpenMP: 85,703μs

1000x1000, Flat array, without OpenMP: 139μs

1000x1000, Flat array, with OpenMP: 3,171μs

10000x10000, Flat array, without OpenMP: 18,712μs

10000x10000, Flat array, with OpenMP: 89,097μs

This confirms our earlier result: using OpenMP for this task tends to slow things down, even if your hardware is amazing. In fact, most of the speed-up between the two processors is likely due to the Xeon's large L3 cache size: at 30,720K it's 10x larger than the 3,720K cache on the i5.

Edit

Incorporating Zulan's reduction strategy from their answer below allows us to efficiently leverage parallelism:

```<code>vector<float> average(const Matrix& original){
  vector<float> average(original.width, 0.0);
  auto average_data = average.data();

  #pragma omp parallel for reduction(+ : average_data[ : original.width])
  for(int y=0;y<original.height;y++){
    for(int x=0;x<original.width;x++)
      average_data[x] += original(x,y);
  }

  for (float& val : average)
    val /= original.height;

  return average;
}
</code>```

For 24 threads, this gives 2629 microseconds on the 10,000x10,000 arrays: a 7.1x improvement over the serial version. Using Zulan's strategy on your original code (without the flat-array indexing) gives 3529 microseconds, so we're still getting a 25% speed-up by using better layouts.

Title: C++ parallel average matrix with OpenMP

Body:
I have this code in C++ that calculates the average of each column of a matrix. I want to parallelize the code using OpenMP.

#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

vector<double> average(const vector<vector<unsigned char>>& original){
  vector<vector<double>> result(original.size(), vector<double>(original[0].size()));
  vector<double> average(original[0].size(), 0.0);

  for (int i=0; i<original.size(); i++) {
    const vector<unsigned char>& vector = original[i];
    for (int k = 0; k < vector.size(); ++k) {
      average[k] += vector[k];
    }
  }
  for (double& val : average) {
    val /= original.size();
  }

  return average;
}

Adding #pragma omp parallel for before the outer for loop gets me bogus results. Do you have any pointers? I thought I would find tons of examples of this online but wasn't able to find much. This is my first time using OpenMP.

Body:
Frank is right in saying that your immediate problem may be that you're using a non-atomic operation:

average[k] += vector[k];

You can fix that by using:

#pragma omp atomic
average[k] += vector[k];

But a larger conceptual problem is that this probably will not speed up your code. The operations you are doing a very simple and your memory (at least the rows) are contiguous.

Indeed, I have made a Minimum Working Example for your code (you should have done this for your question):

#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

vector<float> average(const vector<vector<unsigned char>>& original){
  vector<float> average(original[0].size(), 0.0);

  #pragma omp parallel for
  for (int i=0; i<original.size(); i++) {
    const vector<unsigned char>& vector = original[i];
    for (int k = 0; k < vector.size(); ++k) {
      #pragma omp atomic
      average[k] += vector[k];
    }
  }
  for (float& val : average) {
    val /= original.size();
  }

  return average;
}

int main(){
  vector<vector<unsigned char>> mat(1000);
  for(int y=0;y<mat.size();y++)
  for(int x=0;x<mat.size();x++)
    mat.at(y).emplace_back(rand()%255);

  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  double dont_optimize = 0;
  for(int i=0;i<100;i++){
    auto ret = average(mat);
    dont_optimize += ret[0];
  }
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

  std::cout<<"Time = "<<(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/100)<<std::endl;

  return 0;
}

Compiling this with g++ -O3 temp.cpp -fopenmp enables OpenMP. Run-times on my four-core machine are consistently about 10,247 microseconds. When I disable OpenMP, run-times are about 2,561 microseconds.

Starting and managing a thread team is expensive.

But there is a real way to speed up your code: improve your memory layout.

Using a std::vector< std::vector<T> > design means that each vector<T> can be located anywhere in memory. Rather, we would like all our memory nice and contiguous. We can achieve this by using flat-array indexing, like so:

(Note that an earlier version of the below code used, e.g., mat.at(y*width+x). The range checking this implies results in a significant loss of speed versus using mat[y*width+x], as the code now does. Times have been updated appropriately.)

#include <vector>
#include <cstdlib>
#include <chrono>
#include <iostream>
using namespace std;

class Matrix {
 public:
  vector<unsigned char> mat;
  int width;
  int height;
  Matrix(int width0, int height0){
    width  = width0;
    height = height0;
    for(int i=0;i<width*height;i++)
      mat.emplace_back(rand()%255);
  }
  unsigned char& operator()(int x, int y){
    return mat[y*width+x];
  }
  unsigned char operator()(int x, int y) const {
    return mat[y*width+x];
  }
  unsigned char& operator()(int i){
    return mat[i];
  }
  unsigned char operator()(int i) const {
    return mat[i];
  }
};

vector<float> average(const Matrix& original){
  vector<float> average(original.width, 0.0);

  #pragma omp parallel for
  for(int y=0;y<original.height;y++)
  for(int x=0;x<original.width;x++)
    #pragma omp atomic
    average[x] += original(x,y);

  for (float& val : average)
    val /= original.height;

  return average;
}

int main(){
  Matrix mat(1000,1000);

  std::cerr<<mat.width<<" "<<mat.height<<std::endl;

  std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
  double dont_optimize = 0;
  for(int i=0;i<100;i++){
    auto ret = average(mat);
    dont_optimize += ret[0];
  }
  std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();

  std::cout<<"Time = "<<(std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()/100)<<std::endl;

  return 0;
}

Note that I am also using float instead of double: you can cram twice the numbers into the same amount of space this way, which is good for caching.

This gives run-times of 292 microseconds without OpenMP and 9426 microseconds with OpenMP.

In conclusion, using OpenMP/parallelism slows down your code because the work being done in parallel takes less time than setting up the parallelism, but using a better memory layout gives a ~90% increase in speed. In addition, using the handy Matrix class I create improves your code's readability and maintainability.

Edit:

Running this on matrices that are 10,000x10,000 instead of 1,000x1,000 gives similar results. For the vector of vectors: 7,449 microseconds without OpenMP and 156,316 microseconds with OpenMP. For flat-array indexing: 32,668 miroseconds without OpenMP and 145,470 microseconds with OpenMP.

The performance may be related to the hardware instruction set available on my machine (particularly, if my machine lacks atomic instructions then OpenMP will have to simulate them with mutexes and such). Indeed, in the flat-array example compiling with -march=native gives improved, though still not-great, performance for OpenMP: 33,079 microseconds without OpenMP and 127,841 microseconds with OpenMP. I will experiment with a more powerful machine later.

Edit

While the aforementioned testing was performed on the Intel(R) Core(TM) i5 CPU M 480 @ 2.67GHz, I have compiled this code (with -O3 -march=native) on the badass Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz. The results are similar:

1000x1000, Vector of vectors, without OpenMP: 145μs

1000x1000, Vector of vectors, with OpenMP: 2,941μs

10000x10000, Vector of vectors, without OpenMP: 20,254μs

10000x10000, Vector of vectors, with OpenMP: 85,703μs

1000x1000, Flat array, without OpenMP: 139μs

1000x1000, Flat array, with OpenMP: 3,171μs

10000x10000, Flat array, without OpenMP: 18,712μs

10000x10000, Flat array, with OpenMP: 89,097μs

This confirms our earlier result: using OpenMP for this task tends to slow things down, even if your hardware is amazing. In fact, most of the speed-up between the two processors is likely due to the Xeon's large L3 cache size: at 30,720K it's 10x larger than the 3,720K cache on the i5.

Edit

Incorporating Zulan's reduction strategy from their answer below allows us to efficiently leverage parallelism:

vector<float> average(const Matrix& original){
  vector<float> average(original.width, 0.0);
  auto average_data = average.data();

  #pragma omp parallel for reduction(+ : average_data[ : original.width])
  for(int y=0;y<original.height;y++){
    for(int x=0;x<original.width;x++)
      average_data[x] += original(x,y);
  }

  for (float& val : average)
    val /= original.height;

  return average;
}

For 24 threads, this gives 2629 microseconds on the 10,000x10,000 arrays: a 7.1x improvement over the serial version. Using Zulan's strategy on your original code (without the flat-array indexing) gives 3529 microseconds, so we're still getting a 25% speed-up by using better layouts.


问:
Shell, multiple directories format doesn't work
today I tried to do multiple directories on one line in the terminal but something is wrong with it, as the sell reads the name of the directories literally and instead of getting n directories I end up with one. I used this format:

mkdir foldername8.{2...5}

I tried also:

mkdir ./foldername8.{2...5},
though I was in the right directory and the first time.
Instead of obtaining foldername8.2, foldernamer8.3... -//-.5 I get 1 folder named foldername8.{2...5}

I tried the same without the dot after 8, it still doesn't do anything. I tried wrapping everything up from the beginning once in curly brackets, and then the same - takes it literally. How can I do it with relatively short amount of code? I'm running on Mint Cinnamon, the last version.

答:
```
 <code>
   `mkdir [directorie 1] && mkdir [directorie 2] && mkdir [directorie n]`
</code>
```


问:
JavaScript error when function called in JavaScript, not when called in HTML
So I had an idea to let the computer guess the number with JavaScript as code language. I know exactly what it must do, but it isn't doing it. The idea is (to see if it works) to get a random number between 1 and 100, when you open the webpage. Weird thing, is that if I call the function in the same JavaScript file it gives an error, but if I call the function with a HTML button, it's working totally fine! The F12-console gives the following error:

Unable to set property 'innerHTML' of undefined or null reference

I have the following code:

var guessTheNumber = function() {

// var number = prompt("Tell me a number between 1 and 100.");
var x = document.getElementById("JS1");

x.innerHTML = Math.floor((Math.random() * 100) + 1);
}

guessTheNumber();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>JS test</title>

 <script type="text/javascript" src="JavaScript.js"></script>
</head>
<body>
 <button onclick="guessTheNumber()"></button>
 <p class="test">test</p>
 <p id="JS1"></p>
</body>
</html></code>```

I tried Microsoft Edge and Google Chrome as browsers, no results. I do not know what I am doing wrong, so any help is appreciated!

答:
try like this (without jQuery):</p>

```<code>var guessTheNumber = function() {

    // var number = prompt("Tell me a number between 1 and 100.");
    var x = document.getElementById("JS1");

    x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
document.addEventListener('DOMContentLoaded', function(){
    guessTheNumber();
}, false);
</code>```

Body:
So I had an idea to let the computer guess the number with JavaScript as code language. I know exactly what it must do, but it isn't doing it. The idea is (to see if it works) to get a random number between 1 and 100, when you open the webpage. Weird thing, is that if I call the function in the same JavaScript file it gives an error, but if I call the function with a HTML button, it's working totally fine! The F12-console gives the following error:

Unable to set property 'innerHTML' of undefined or null reference

I have the following code:

var guessTheNumber = function() {

// var number = prompt("Tell me a number between 1 and 100.");
var x = document.getElementById("JS1");

x.innerHTML = Math.floor((Math.random() * 100) + 1);
}

guessTheNumber();

<!DOCTYPE html>

 <title>JS test</title>

 <button onclick="guessTheNumber()"></button>

test

I tried Microsoft Edge and Google Chrome as browsers, no results. I do not know what I am doing wrong, so any help is appreciated!

Body:
try like this (without jQuery):

var guessTheNumber = function() {

    // var number = prompt("Tell me a number between 1 and 100.");
    var x = document.getElementById("JS1");

    x.innerHTML = Math.floor((Math.random() * 100) + 1);
}
document.addEventListener('DOMContentLoaded', function(){
    guessTheNumber();
}, false);


问:
Sending E-mail using C#
I need to send email via my C# app.

I come from a VB 6 background and had a lot of bad experiences with the MAPI control.
First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still needed to click on send receive.

If I needed to send bulk html bodied emails (100 - 200), what would be the best way to do this in C#?

答:
You could use the System.Net.Mail.MailMessage class of the .NET framework.

You can find the MSDN documentation here.

Here is a simple example (code snippet):

```<code>using System.Net;
using System.Net.Mail;
using System.Net.Mime;

...
try
{

   SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");

    // set smtp-client with basicAuthentication
    mySmtpClient.UseDefaultCredentials = false;
   System.Net.NetworkCredential basicAuthenticationInfo = new
      System.Net.NetworkCredential("username", "password");
   mySmtpClient.Credentials = basicAuthenticationInfo;

   // add from,to mailaddresses
   MailAddress from = new MailAddress("test@example.com", "TestFromName");
   MailAddress to = new MailAddress("test2@example.com", "TestToName");
   MailMessage myMail = new System.Net.Mail.MailMessage(from, to);

   // add ReplyTo
   MailAddress replyTo = new MailAddress("reply@example.com");
   myMail.ReplyToList.Add(replyTo);

   // set subject and encoding
   myMail.Subject = "Test message";
   myMail.SubjectEncoding = System.Text.Encoding.UTF8;

   // set body-message and encoding
   myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
   myMail.BodyEncoding = System.Text.Encoding.UTF8;
   // text or html
   myMail.IsBodyHtml = true;

   mySmtpClient.Send(myMail);
}

catch (SmtpException ex)
{
  throw new ApplicationException
    ("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
   throw ex;
}
</code>```

OwnerDisplayName: Shaun

ContentLicense: CC BY-SA 4.0

Title: Sending E-mail using C#

LastEditorDisplayName: Can Berk Güder

Body:
You could use the System.Net.Mail.MailMessage class of the .NET framework.

You can find the MSDN documentation here.

Here is a simple example (code snippet):

using System.Net;
using System.Net.Mail;
using System.Net.Mime;

...
try
{

   SmtpClient mySmtpClient = new SmtpClient("my.smtp.exampleserver.net");

    // set smtp-client with basicAuthentication
    mySmtpClient.UseDefaultCredentials = false;
   System.Net.NetworkCredential basicAuthenticationInfo = new
      System.Net.NetworkCredential("username", "password");
   mySmtpClient.Credentials = basicAuthenticationInfo;

   // add from,to mailaddresses
   MailAddress from = new MailAddress("test@example.com", "TestFromName");
   MailAddress to = new MailAddress("test2@example.com", "TestToName");
   MailMessage myMail = new System.Net.Mail.MailMessage(from, to);

   // add ReplyTo
   MailAddress replyTo = new MailAddress("reply@example.com");
   myMail.ReplyToList.Add(replyTo);

   // set subject and encoding
   myMail.Subject = "Test message";
   myMail.SubjectEncoding = System.Text.Encoding.UTF8;

   // set body-message and encoding
   myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
   myMail.BodyEncoding = System.Text.Encoding.UTF8;
   // text or html
   myMail.IsBodyHtml = true;

   mySmtpClient.Send(myMail);
}

catch (SmtpException ex)
{
  throw new ApplicationException
    ("SmtpException has occured: " + ex.Message);
}
catch (Exception ex)
{
   throw ex;
}

OwnerDisplayName: splattne

LastEditorDisplayName: splattne


问:
Which type of path to store in MySQL database?
When I come to build a simple site using PHP and MySQL, what is the best method for storing paths of files and images?

Inserting paths to Mysql as (system path C:/----)

Inserting paths to Mysql as (HTTP path http://----)

答:
I propose you save the relative path, not the absolute one. I.e, if you have this structure:

```<code>c:/install_folder/
c:/install_folder/script.php
c:/install_folder/files/file.jpg
</code>```

Store "file.jpg" as "files/file.jpg". Thenn save "c:/install_folder/" in a configuration value somewhere in your application. That way you can easily move the application around and just update the configuration file.

ContentLicense: CC BY-SA 2.5

Body:
I propose you save the relative path, not the absolute one. I.e, if you have this structure:

c:/install_folder/
c:/install_folder/script.php
c:/install_folder/files/file.jpg

Store "file.jpg" as "files/file.jpg". Thenn save "c:/install_folder/" in a configuration value somewhere in your application. That way you can easily move the application around and just update the configuration file.


问:
how can i set an imageurl of a asp control dynamically. my image is present in a database in binary form
i have an ashx file through which i want to get the imageurl for an asp image control. the code below is an ashx file

```<code>  SqlConnection con = null;
        SqlDataReader dr = null; SqlCommand cmd = null;
        try
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["GalleriaDatabaseConnectionString"].ConnectionString);
            cmd = new SqlCommand("Select Image from tblImage where UserName='" + context.Session["uname"] + "'");
            con.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                context.Response.ContentType = "image/jpg";
                context.Response.BinaryWrite((byte[])dr["Image"]);
                dr.Close();
            }
        }**
</code>```

答:
Mention the path of your ashx file in the ImageUr Property. Like below</p>

```<code><asp:Image runat='server' Id='image' ImageUrl='imageprocessor.ashx'></asp:Image>
</code>```

Body:
i have an ashx file through which i want to get the imageurl for an asp image control. the code below is an ashx file

  SqlConnection con = null;
        SqlDataReader dr = null; SqlCommand cmd = null;
        try
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["GalleriaDatabaseConnectionString"].ConnectionString);
            cmd = new SqlCommand("Select Image from tblImage where UserName='" + context.Session["uname"] + "'");
            con.Open();
            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                context.Response.ContentType = "image/jpg";
                context.Response.BinaryWrite((byte[])dr["Image"]);
                dr.Close();
            }
        }**

Body:
Mention the path of your ashx file in the ImageUr Property. Like below

<asp:Image runat='server' Id='image' ImageUrl='imageprocessor.ashx'></asp:Image>


问:
PHP MYSQL error for android app
What am I doing wrong?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?wmsAuthSign=, n.channel_description, c.c' at line 6302

```<code>    private function get_posts() {

        include "../includes/config.php";
        $setting_qry    = "SELECT * FROM tbl_fcm_api_key where id = '1'";
        $setting_result = mysqli_query($connect, $setting_qry);
        $settings_row   = mysqli_fetch_assoc($setting_result);
        $api_key    = $settings_row['api_key'];

        if (isset($_GET['api_key'])) {

            $access_key_received = $_GET['api_key'];

            if ($access_key_received == $api_key) {

                if($this->get_request_method() != "GET") $this->response('',406);
                $limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
                $page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;

                $offset = ($page * $limit) - $limit;
                $count_total = $this->get_count_result("SELECT COUNT(DISTINCT n.id) FROM tbl_channel n");

                $query = "SELECT distinct
                            n.id AS 'channel_id',
                            n.category_id,
                            n.channel_name,
                            n.channel_image,
                            n.channel_url?wmsAuthSign=<?php echo $base64urlsignature;?>,
                            n.channel_description,

                            c.category_name

                        FROM
                            tbl_channel n,
                            tbl_category c

                        WHERE
                            n.category_id = c.cid ORDER BY n.id DESC LIMIT $limit OFFSET $offset";

                $post = $this->get_list_result($query);
                $count = count($post);
                $respon = array(
                    'status' => 'ok', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'posts' => $post
                );
                $this->response($this->json($respon), 200);

            } else {
                die ('Oops, API Key is Incorrect!');
            }
        } else {
            die ('Forbidden, API Key is Required!');
        }

    }
</code>```

答:
SOLVED: </p>

```<code>REPLACE(n.channel_url, '?wmsAuthSign=', '?wmsAuthSign=".$base64urlsignature."') as channel_url,
</code>```

<p>UNDER                             n.channel_image, </p>

Title: PHP MYSQL error for android app

Body:
What am I doing wrong?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?wmsAuthSign=, n.channel_description, c.c' at line 6302

    private function get_posts() {

        include "../includes/config.php";
        $setting_qry    = "SELECT * FROM tbl_fcm_api_key where id = '1'";
        $setting_result = mysqli_query($connect, $setting_qry);
        $settings_row   = mysqli_fetch_assoc($setting_result);
        $api_key    = $settings_row['api_key'];

        if (isset($_GET['api_key'])) {

            $access_key_received = $_GET['api_key'];

            if ($access_key_received == $api_key) {

                if($this->get_request_method() != "GET") $this->response('',406);
                $limit = isset($this->_request['count']) ? ((int)$this->_request['count']) : 10;
                $page = isset($this->_request['page']) ? ((int)$this->_request['page']) : 1;

                $offset = ($page * $limit) - $limit;
                $count_total = $this->get_count_result("SELECT COUNT(DISTINCT n.id) FROM tbl_channel n");

                $query = "SELECT distinct
                            n.id AS 'channel_id',
                            n.category_id,
                            n.channel_name,
                            n.channel_image,
                            n.channel_url?wmsAuthSign=<?php echo $base64urlsignature;?>,
                            n.channel_description,

                            c.category_name

                        FROM
                            tbl_channel n,
                            tbl_category c

                        WHERE
                            n.category_id = c.cid ORDER BY n.id DESC LIMIT $limit OFFSET $offset";

                $post = $this->get_list_result($query);
                $count = count($post);
                $respon = array(
                    'status' => 'ok', 'count' => $count, 'count_total' => $count_total, 'pages' => $page, 'posts' => $post
                );
                $this->response($this->json($respon), 200);

            } else {
                die ('Oops, API Key is Incorrect!');
            }
        } else {
            die ('Forbidden, API Key is Required!');
        }

    }

Body:
SOLVED:

REPLACE(n.channel_url, '?wmsAuthSign=', '?wmsAuthSign=".$base64urlsignature."') as channel_url,

UNDER                             n.channel_image,


问:
Having multiple output using Logstash
I am new to Logstash and I have trouble understanding how to configure the following process:

Let's say I want to have my logstash collecting Tweets and simultaneously  indexing the tweets in my ES and store the tweet in a MongoDB?

I succeed to have my log stash collecting tweets and indexing it in a ES but I don't know how to configure it to store the tweets in my mongoDB as well?

Is it possible? How to configure it?

答:
It's possible, you can configure multiple plugins in the output section of conf file:

```<code>output
{
    stdout {
        codec => rubydebug
    }

    elasticsearch {
        hosts => ["my-elasticsearch:9200"]
        index => "logs"
        document_type => "applog"
    }

    mongodb
    {
        isodate => true
        database => "metrics"
        collection => "logs"
        uri => "mongodb://127.0.0.1:27017"
    }
}
</code>```

Check logstash documentation for all available mongodb options as this may vary depending on logstash version (collection, database and uri are required).

Title: Having multiple output using Logstash

Body:
It's possible, you can configure multiple plugins in the output section of conf file:

output
{
    stdout {
        codec => rubydebug
    }

    elasticsearch {
        hosts => ["my-elasticsearch:9200"]
        index => "logs"
        document_type => "applog"
    }

    mongodb
    {
        isodate => true
        database => "metrics"
        collection => "logs"
        uri => "mongodb://127.0.0.1:27017"
    }
}

Check logstash documentation for all available mongodb options as this may vary depending on logstash version (collection, database and uri are required).


问:
Go integration with Protocol Buffers?
After a quick look at the documentation, I immediately started to think about integration with existing languages and applications and was wondering whether support would be provided for Protocol Buffers?</p>

答: Protocol buffers are now fully supported in Go.  The official Go library can be found at github.com/golang/protobuf.</p>

Title: Go integration with Protocol Buffers?


问:
How can I change the toolbar color in Swift
I'm working on an app and I'm not sure how to change the color of the bottom toolbar in swift. I would like to have it as a custom image to match my navigation bar. Does anyone have a code for that or just to change the color. Thank you</p>

答:
This also works on swift 3:</p>

```<code>UINavigationBar.appearance().barTintColor = UIColor.red
</code>```

Body:
This also works on swift 3:

UINavigationBar.appearance().barTintColor = UIColor.red


问:
Second path fragment must not be a drive or UNC name
How to read all image files in folder by  environment path folder in main folder:

```<code>   string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mainFolder");
</code>```

for example if inner folder for one file path is:

```<code>  Bitmap bmp = new Bitmap(path + "/folder/pic1.bmp");
</code>```

but I want read all files of  mainFolder/folder:

```<code>pic1.bmp
pic2.bmp
pic3.bmp
pic5.bmp
</code>```

Not sure how to do it properly:

```<code>foreach (string imageFileName in Directory.GetFiles(path, "/folder/*.bmp"))
{
    using (Bitmap bmp = new Bitmap(imageFileName))
    {
      // process
    }
}
</code>```

this way I  have: Second path fragment must not be a drive or UNC name

and  this way:

```<code>foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.bmp"))
</code>```

I got: Illegal characters in path.

答:
GetFiles will do what you need.  You could write a new method that returns a String[] of the files found.  This would allow you to use it elsewhere if required.

```<code>public String[] GetFilesFromFolder(String folder, String[] filters, bool recursiveSearch)
 {
    List<String> foundFiles= new List<String>();
    var searchingOption = recursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
    foreach (var filter in filters)
    {
       foundFiles.AddRange(Directory.GetFiles(folder, String.Format("*.{0}", filter), searchOption));
    }
    return foundFiles.ToArray();
 }
</code>```

Then to use it, just do something like below:

```<code>String folder= "PATH TO FOLDER";
var filters = new String[] { "bmp", "jpg", "jpeg", "png" };
var files = GetFilesFromFolder(folder, filters, false);
</code>```

This also gives you control over searching for any file type you like, so not just BMP, but JPG, PNG or anything else (Doc, Xls etc)

Body:
How to read all image files in folder by  environment path folder in main folder:

   string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mainFolder");

for example if inner folder for one file path is:

  Bitmap bmp = new Bitmap(path + "/folder/pic1.bmp");

but I want read all files of  mainFolder/folder:

pic1.bmp
pic2.bmp
pic3.bmp
pic5.bmp

Not sure how to do it properly:

foreach (string imageFileName in Directory.GetFiles(path, "/folder/*.bmp"))
{
    using (Bitmap bmp = new Bitmap(imageFileName))
    {
      // process
    }
}

this way I  have: Second path fragment must not be a drive or UNC name

and  this way:

foreach (string imgFileName in Directory.GetFiles(path + "/folder/*.bmp"))

I got: Illegal characters in path.

Body:
GetFiles will do what you need.  You could write a new method that returns a String[] of the files found.  This would allow you to use it elsewhere if required.

public String[] GetFilesFromFolder(String folder, String[] filters, bool recursiveSearch)
 {
    List<String> foundFiles= new List<String>();
    var searchingOption = recursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
    foreach (var filter in filters)
    {
       foundFiles.AddRange(Directory.GetFiles(folder, String.Format("*.{0}", filter), searchOption));
    }
    return foundFiles.ToArray();
 }

Then to use it, just do something like below:

String folder= "PATH TO FOLDER";
var filters = new String[] { "bmp", "jpg", "jpeg", "png" };
var files = GetFilesFromFolder(folder, filters, false);

This also gives you control over searching for any file type you like, so not just BMP, but JPG, PNG or anything else (Doc, Xls etc)


问:
Button with image and text and text bellow the image, how?
First time with cross-platform apps with xamarin, i'm working with xamarin forms in visual studio 2017 community.

I have a button with an image and text but the text needs to be below the image. currently the text is displaying to the left of the image, how can i do this?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;

namespace AppUnap
{
public class PPrincipal : ContentPage
{
    public PPrincipal()
    {
        Button btn1= new Button();
        btn1.Image = "notas.png";
        btn1.Text = "Calificaciones";
        btn1.HorizontalOptions = LayoutOptions.CenterAndExpand;

        Button btn2 = new Button();
        btn2.Image = "notas.png";
        btn2.Text = "Aula Virtual";
        btn2.HorizontalOptions = LayoutOptions.CenterAndExpand;

        Content = new StackLayout
        {
            Spacing = 0,
            VerticalOptions = LayoutOptions.CenterAndExpand,
            Children =
            {
            new StackLayout
            {
                Spacing = 0,
                Orientation = StackOrientation.Horizontal,
                Children =
                {
                    btn1,
                    btn2,
                }
            }
            }

        };
    }
}
}
</code>```

答:
You need to use ContentLayout on your button.

Here is the code I use in XAML:

```<code><Button Command="{Binding MyCommand}" ContentLayout="Top,0" Text="mytext" Image="myimage.png" />
</code>```

Top = Position of the Image

0 = spacing between image & text

You should find easily how to use the ContentLayout in C#

Body:
First time with cross-platform apps with xamarin, i'm working with xamarin forms in visual studio 2017 community.

I have a button with an image and text but the text needs to be below the image. currently the text is displaying to the left of the image, how can i do this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;

namespace AppUnap
{
public class PPrincipal : ContentPage
{
    public PPrincipal()
    {
        Button btn1= new Button();
        btn1.Image = "notas.png";
        btn1.Text = "Calificaciones";
        btn1.HorizontalOptions = LayoutOptions.CenterAndExpand;

        Button btn2 = new Button();
        btn2.Image = "notas.png";
        btn2.Text = "Aula Virtual";
        btn2.HorizontalOptions = LayoutOptions.CenterAndExpand;

        Content = new StackLayout
        {
            Spacing = 0,
            VerticalOptions = LayoutOptions.CenterAndExpand,
            Children =
            {
            new StackLayout
            {
                Spacing = 0,
                Orientation = StackOrientation.Horizontal,
                Children =
                {
                    btn1,
                    btn2,
                }
            }
            }

        };
    }
}
}

Body:
You need to use ContentLayout on your button.

Here is the code I use in XAML:

<Button Command="{Binding MyCommand}" ContentLayout="Top,0" Text="mytext" Image="myimage.png" />

Top = Position of the Image

0 = spacing between image & text

You should find easily how to use the ContentLayout in C#


问:
Get node status from system tables
I'm using DataStax c++ cassandra driver. As far as I can see there is no special functions regarding checking node status in the driver API. Nodetool utility achieves this via JMX extensions. But I suppose it will be quite painful to implement this in C++. Is there any other way to get this info (at least online/offline) preferably via querying system tables.

答:
There is a JMX to HTTP bridge called Jolokia which is loaded into any Java application as a JAR file and it exports all JMX variables through a dedicated HTTP port.

I'm using it successfully to monitor Cassandra runtime parameters with InfluxDB/Telegraf.

You can use it in your C++ app more easily as it's normal HTTP.

Title: Get node status from system tables


问:
Failed to build boost 1.64.0 b2.exe Visual Studio 2017
I was following these instructions

https://studiofreya.com/2017/04/23/building-boost-1-64-with-visual-studio-2017/

for building boost on windows 10. It would suggest we can now build boost with 2017? A change since this question

```<code>    @echo off
rem Directory to boost root
set boost_dir=C:\Program Files\boost_1_64_0

rem Number of cores to use when building boost
set cores=%NUMBER_OF_PROCESSORS%

rem What toolset to use when building boost.

rem Visual Studio 2012 -> set msvcver=msvc-11.0
rem Visual Studio 2013 -> set msvcver=msvc-12.0
rem Visual Studio 2015 -> set msvcver=msvc-14.0
rem Visual Studio 2017 -> set msvcver=msvc-14.1

set msvcver=msvc-14.1

rem Start building boost
echo Building %boost_dir% with %cores% cores using toolset %msvcver%.

cd %boost_dir%
call bootstrap.bat

rem Static libraries
b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64
b2 -j%cores% toolset=%msvcver% address-model=32 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/win32

rem Build DLLs
rem b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=shared threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64
rem b2 -j%cores% toolset=%msvcver% address-model=32 architecture=x86 link=shared threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/win32

pause
</code>```

Running from within Visual Studio 2017 command line.

Boostrap.bat seems to run fine.

The first time I ran b2.exe into, only a handful succeeded. I can see the same kinds of error again and again.

```<code>...failed compile-c-c++ bin.v2\libs\serialization\build\msvc-14.1\release\address-model-32\architecture-x86\link-static\threading-multi\xml_oarchive.obj...
compile-c-c++ bin.v2\libs\serialization\build\msvc-14.1\release\address-model-32\architecture-x86\link-static\threading-multi\codecvt_null.obj
Files\boost_1_64_0""=="" was unexpected at this time.
</code>```

Can anyone experienced interpret all the no's here? It also gives a few parsing errors

```<code>C:\Program Files\boost_1_64_0>b2.exe
Files\boost_1_64_0""=="" was unexpected at this time.
Files\boost_1_64_0""=="" was unexpected at this time.
Files\boost_1_64_0""=="" was unexpected at this time.
Performing configuration checks
- 32-bit                   : no  (cached)
- 64-bit                   : no  (cached)
- arm                      : no  (cached)
- mips1                    : no  (cached)
- power                    : no  (cached)
- sparc                    : no  (cached)
- x86                      : no  (cached)
- combined                 : no  (cached)

Building the Boost C++ Libraries.

- symlinks supported       : yes
- C++11 mutex              : no
- Boost.Config Feature Check: cxx11_auto_declarations : no
- Boost.Config Feature Check: cxx11_constexpr : no
- Boost.Config Feature Check: cxx11_defaulted_functions : no
- Boost.Config Feature Check: cxx11_final : no
- Boost.Config Feature Check: cxx11_hdr_mutex : no
- Boost.Config Feature Check: cxx11_hdr_tuple : no
- Boost.Config Feature Check: cxx11_lambdas : no
- Boost.Config Feature Check: cxx11_noexcept : no
- Boost.Config Feature Check: cxx11_nullptr : no
- Boost.Config Feature Check: cxx11_rvalue_references : no
- Boost.Config Feature Check: cxx11_template_aliases : no
- Boost.Config Feature Check: cxx11_thread_local : no
- Boost.Config Feature Check: cxx11_variadic_templates : no
- has_icu builds           : no
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
- zlib                     : no
- bzip2                    : no
- iconv (libc)             : no
- iconv (separate)         : no
- icu                      : no
- icu (lib64)              : no
- native-atomic-int32-supported : no
- message-compiler         : no
- native-syslog-supported  : no
- pthread-supports-robust-mutexes : no
- compiler-supports-visibility : no
- gcc visibility           : no
- long double support      : no

warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
    - zlib                     : no  (cached)
    - bzip2                    : no  (cached)
</code>```

Component configuration:

```<code>- atomic                   : building
- chrono                   : building
- container                : building
- context                  : building
- coroutine                : building
- coroutine2               : building
- date_time                : building
- exception                : building
- fiber                    : building
- filesystem               : building
- graph                    : building
- graph_parallel           : building
- iostreams                : building
- locale                   : building
- log                      : building
- math                     : building
- metaparse                : building
- mpi                      : building
- program_options          : building
- python                   : building
- random                   : building
- regex                    : building
- serialization            : building
- signals                  : building
- system                   : building
- test                     : building
- thread                   : building
- timer                    : building
- type_erasure             : building
- wave                     : building

...patience...
...patience...
</code>```

Everything should be written to C:\Program Files\boost_1_64_0\stage\win32\lib, but I see no files.

答:
Of course...

set boost_dir=C:\Program Files\boost_1_64_0

must have "" to avoid the break. Silly Windows.
set boost_dir="C:\Program Files\boost_1_64_0"

and we start to build!

Body:
I was following these instructions

https://studiofreya.com/2017/04/23/building-boost-1-64-with-visual-studio-2017/

for building boost on windows 10. It would suggest we can now build boost with 2017? A change since this question

    @echo off
rem Directory to boost root
set boost_dir=C:\Program Files\boost_1_64_0

rem Number of cores to use when building boost
set cores=%NUMBER_OF_PROCESSORS%

rem What toolset to use when building boost.

rem Visual Studio 2012 -> set msvcver=msvc-11.0
rem Visual Studio 2013 -> set msvcver=msvc-12.0
rem Visual Studio 2015 -> set msvcver=msvc-14.0
rem Visual Studio 2017 -> set msvcver=msvc-14.1

set msvcver=msvc-14.1

rem Start building boost
echo Building %boost_dir% with %cores% cores using toolset %msvcver%.

cd %boost_dir%
call bootstrap.bat

rem Static libraries
b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64
b2 -j%cores% toolset=%msvcver% address-model=32 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/win32

rem Build DLLs
rem b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=shared threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64
rem b2 -j%cores% toolset=%msvcver% address-model=32 architecture=x86 link=shared threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/win32

pause

Running from within Visual Studio 2017 command line.

Boostrap.bat seems to run fine.

The first time I ran b2.exe into, only a handful succeeded. I can see the same kinds of error again and again.

...failed compile-c-c++ bin.v2\libs\serialization\build\msvc-14.1\release\address-model-32\architecture-x86\link-static\threading-multi\xml_oarchive.obj...
compile-c-c++ bin.v2\libs\serialization\build\msvc-14.1\release\address-model-32\architecture-x86\link-static\threading-multi\codecvt_null.obj
Files\boost_1_64_0""=="" was unexpected at this time.

Can anyone experienced interpret all the no's here? It also gives a few parsing errors

C:\Program Files\boost_1_64_0>b2.exe
Files\boost_1_64_0""=="" was unexpected at this time.
Files\boost_1_64_0""=="" was unexpected at this time.
Files\boost_1_64_0""=="" was unexpected at this time.
Performing configuration checks
- 32-bit                   : no  (cached)
- 64-bit                   : no  (cached)
- arm                      : no  (cached)
- mips1                    : no  (cached)
- power                    : no  (cached)
- sparc                    : no  (cached)
- x86                      : no  (cached)
- combined                 : no  (cached)

Building the Boost C++ Libraries.

- symlinks supported       : yes
- C++11 mutex              : no
- Boost.Config Feature Check: cxx11_auto_declarations : no
- Boost.Config Feature Check: cxx11_constexpr : no
- Boost.Config Feature Check: cxx11_defaulted_functions : no
- Boost.Config Feature Check: cxx11_final : no
- Boost.Config Feature Check: cxx11_hdr_mutex : no
- Boost.Config Feature Check: cxx11_hdr_tuple : no
- Boost.Config Feature Check: cxx11_lambdas : no
- Boost.Config Feature Check: cxx11_noexcept : no
- Boost.Config Feature Check: cxx11_nullptr : no
- Boost.Config Feature Check: cxx11_rvalue_references : no
- Boost.Config Feature Check: cxx11_template_aliases : no
- Boost.Config Feature Check: cxx11_thread_local : no
- Boost.Config Feature Check: cxx11_variadic_templates : no
- has_icu builds           : no
warning: Graph library does not contain MPI-based parallel components.
note: to enable them, add "using mpi ;" to your user-config.jam
- zlib                     : no
- bzip2                    : no
- iconv (libc)             : no
- iconv (separate)         : no
- icu                      : no
- icu (lib64)              : no
- native-atomic-int32-supported : no
- message-compiler         : no
- native-syslog-supported  : no
- pthread-supports-robust-mutexes : no
- compiler-supports-visibility : no
- gcc visibility           : no
- long double support      : no

warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add "using mpi ;" to user-config.jam.
note: to suppress this message, pass "--without-mpi" to bjam.
note: otherwise, you can safely ignore this message.
    - zlib                     : no  (cached)
    - bzip2                    : no  (cached)

Component configuration:

- atomic                   : building
- chrono                   : building
- container                : building
- context                  : building
- coroutine                : building
- coroutine2               : building
- date_time                : building
- exception                : building
- fiber                    : building
- filesystem               : building
- graph                    : building
- graph_parallel           : building
- iostreams                : building
- locale                   : building
- log                      : building
- math                     : building
- metaparse                : building
- mpi                      : building
- program_options          : building
- python                   : building
- random                   : building
- regex                    : building
- serialization            : building
- signals                  : building
- system                   : building
- test                     : building
- thread                   : building
- timer                    : building
- type_erasure             : building
- wave                     : building

...patience...
...patience...

Everything should be written to C:\Program Files\boost_1_64_0\stage\win32\lib, but I see no files.


问:
C# express a type variable as a type
Let's say I'm working with generic function :

```<code>public interface IFoo
{
  Type Type;
  TValue Read<TValue>();
}

public class Foo : IFoo {}

var f = new Foo();
</code>```

I'd like to write :

```<code>var value = f.Read<f.Type>();
</code>```

but this gives error :

f is a variable but is used like a type

I could write conditionals :

```<code>object value;
if (f.Type == typeof(bool))
{
    value = f.Read<bool>();
}
if (f.Type == typeof(byte))
{
    value = f.Read<byte>();
}
...
</code>```

but this doesn't really work because it's verbose , may be incomplete if I don't know in advance all possible types , and value is an object instead of the type.

Is there a solution ?

答:
Although there are ways to solve this problem through reflection or with LINQ expressions, I think the root cause of your problem is in the poor design of your IFoo interface.

If all you need is an object result from a read, change the interface to this:

```<code>public interface IFoo {
    Type Type {get;}
    object Read();
}
</code>```

This would let you avoid using generics where its us needs to be "undone" to get an object.

Title: C# express a type variable as a type

Body:
Let's say I'm working with generic function :

public interface IFoo
{
  Type Type;
  TValue Read<TValue>();
}

public class Foo : IFoo {}

var f = new Foo();

I'd like to write :

var value = f.Read<f.Type>();

but this gives error :

f is a variable but is used like a type

I could write conditionals :

object value;
if (f.Type == typeof(bool))
{
    value = f.Read<bool>();
}
if (f.Type == typeof(byte))
{
    value = f.Read<byte>();
}
...

but this doesn't really work because it's verbose , may be incomplete if I don't know in advance all possible types , and value is an object instead of the type.

Is there a solution ?

Body:
Although there are ways to solve this problem through reflection or with LINQ expressions, I think the root cause of your problem is in the poor design of your IFoo interface.

If all you need is an object result from a read, change the interface to this:

public interface IFoo {
    Type Type {get;}
    object Read();
}

This would let you avoid using generics where its us needs to be "undone" to get an object.


问:
A property does not exist in type "Interface"?
I am new to Typescript. I am trying to use interface as an array type. I structure my literal object by order, though I still get this error  :

Type '{ id: number; title: string; image: string; words: string;
  description: string; }[]' is not assignable to type 'IWordList[]'.

  Type '{ id: number; title: string; image: string; words: string;
  description: string; }' is not assignable to type 'IWordList'.
      Object literal may only specify known properties, and 'id' does not exist in type 'IWordList'.

Notice that the case isn't about 'id' itself, but it is if I added any addtioal property, I get the same error

IWordList.ts

```<code>export interface IWordList{
    id : number;
    title : string;
    image : string;
    words : string;
    description : string;
}
</code>```

wordlistsdata.service.ts

```<code>import { Injectable } from '@angular/core';
import { IWordList } from './IWordlist';

@Injectable()
export class WordlistsdataService {

  constructor() { }

  private allWordLists : IWordList[] =
  [
      {
          id : 1,
          title : "Animals",
          image : "/src/app/images/wordlists/animals_background.jpg",
          words : "cat,elephant,cow,duck",
          description : "sdadasd"
      },
      {
          id : 2,
          title : "Jobs",
          image : "/src/app/images/wordlists/jobs_background.jpg",
          words : "engineer,farmer,artist,programmer",
          description : "sdadasd"
      }

    ]

  public getWordList() : IWordList[]{
    return this.allWordLists;
  }

  public getOneWordList(id : number) : string[] {
    return
  }
}
</code>```

答: I had the same error. It was showing up in my build watch but not in Linter, which detects those errors. So I decided to restart the build, and got a new error, pointing to a case where I had created an object without the property that was throwing the error (in your case "id"). Interestingly, Linter had missed that actual error. I fixed this code so that "id" was being defined, and started the build once again. This time it worked with no errors. </p>

Body:
I am new to Typescript. I am trying to use interface as an array type. I structure my literal object by order, though I still get this error  :

Type '{ id: number; title: string; image: string; words: string;
  description: string; }[]' is not assignable to type 'IWordList[]'.

  Type '{ id: number; title: string; image: string; words: string;
  description: string; }' is not assignable to type 'IWordList'.
      Object literal may only specify known properties, and 'id' does not exist in type 'IWordList'.

Notice that the case isn't about 'id' itself, but it is if I added any addtioal property, I get the same error

IWordList.ts

export interface IWordList{
    id : number;
    title : string;
    image : string;
    words : string;
    description : string;
}

wordlistsdata.service.ts

import { Injectable } from '@angular/core';
import { IWordList } from './IWordlist';

@Injectable()
export class WordlistsdataService {

  constructor() { }

  private allWordLists : IWordList[] =
  [
      {
          id : 1,
          title : "Animals",
          image : "/src/app/images/wordlists/animals_background.jpg",
          words : "cat,elephant,cow,duck",
          description : "sdadasd"
      },
      {
          id : 2,
          title : "Jobs",
          image : "/src/app/images/wordlists/jobs_background.jpg",
          words : "engineer,farmer,artist,programmer",
          description : "sdadasd"
      }

    ]

  public getWordList() : IWordList[]{
    return this.allWordLists;
  }

  public getOneWordList(id : number) : string[] {
    return
  }
}