问:
Add items within nested list within nested recyclerview in a recyclerview
I have a recyclerview and within it I am trying to add a nested recyclerview that contains a list. Here is what I am trying to make:

This is the closest solution I could find on stack overflow but they use headers instead of left-aligned titles that wrap all other nested views. How do I create a nested list within a nested recyclerview within a recyclerview?

答:
We need two RecyclerViews and two Adapters which i call inner and outer.inside ViewHolder of outer adapter put innerRecyclerView and inside onBindViewHolder of outer adapter set adapter to innerRecyclerView.i recently developed a test project like this

here is outerAdapter

```<code>public class MainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private List<Category> categories;
private List<Ads> ads_list;
private List<Products> productsList;
private int count;
private int width;

public MainAdapter(Context context, List<Category> categories, List<Ads> ads_list,List<Products> productsList,int width) {
    this.context = context;
    this.categories = categories;
    this.ads_list = ads_list;
    this.productsList=productsList;
    this.width=width;
    //Helper.logDebug("main__adapter",String.valueOf(categories.size()));
    //Helper.logDebug("main_adapter","haminjoori");
}

private class ViewHolder extends RecyclerView.ViewHolder{
    private RecyclerView recyclerView;
    private TextView tv_type,ad_tv_image_address;
    private ImageView iv_ad;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        recyclerView=itemView.findViewById(R.id.recyclerview_horizental);
        recyclerView.setNestedScrollingEnabled(false);
        tv_type=itemView.findViewById(R.id.tv_type);
        iv_ad=itemView.findViewById(R.id.iv_ad);
        ad_tv_image_address=itemView.findViewById(R.id.ad_image_address);
        //Helper.logDebug("main_adapter","haminjoori");
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view= LayoutInflater.from(context).inflate(R.layout.recycler_layout,viewGroup,false);
    //Helper.logDebug("main_adapter","haminjoori");
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
    ViewHolder holder= (ViewHolder) viewHolder;
    try {
        String banner_url=ads_list.get(i).getImage();
        holder.ad_tv_image_address.setText(banner_url);
        Picasso.get().load(context.getString(R.string.base_url_banner)+banner_url).into(holder.iv_ad);
    }catch (Exception ex){
        holder.ad_tv_image_address.setText("");
    }
    Helper.logDebug("main_adapter",holder.ad_tv_image_address.getText().toString());
    holder.tv_type.setText(categories.get(i).getName());
    SecondAdapter secondAdapter=new SecondAdapter(categories.get(i).getProducts(),context,width);
    LinearLayoutManager layoutManager=new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false);

    holder.recyclerView.setLayoutManager(layoutManager);
    holder.recyclerView.setAdapter(secondAdapter);

}

@Override
public int getItemCount() {
    return categories.size();
}
}
</code>```

and here is inner adapter

```<code>public class SecondAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private int count;
private List<Products> productsList;
private List<Category> categories;
private int width;

public SecondAdapter(List<Products> productsList, Context context,int width) {
    this.productsList = productsList;
    this.context = context;
    this.width=width;
}

private class ViewHolder extends RecyclerView.ViewHolder {
    private TextView market_price,our_price,name,unit,min_amount,image;
    private ImageView imagee;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        itemView.getLayoutParams().width=width/2;

        market_price=itemView.findViewById(R.id.product_market_price);
        our_price=itemView.findViewById(R.id.product_our_price);
        name=itemView.findViewById(R.id.fruit_name);
        unit=itemView.findViewById(R.id.fruit_unit);
        image=itemView.findViewById(R.id.product_image_url);
        imagee=itemView.findViewById(R.id.iv_rec);
        min_amount=itemView.findViewById(R.id.product_min_amount);

        Log.d("second_adapter","haminjoori");
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view= LayoutInflater.from(context).inflate(R.layout.recycler2_layout,viewGroup,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
    ViewHolder holder= (ViewHolder) viewHolder;
    Helper.logDebug("second_adapter","haminjori");

    holder.name.setText(productsList.get(i).getName());
    holder.unit.setText(productsList.get(i).getUnit());
    holder.market_price.setText(String.valueOf(productsList.get(i).getMarketPrice()));
    holder.our_price.setText(String.valueOf(productsList.get(i).getOurPrice()));
    Helper.logDebug("secondAdapter",productsList.get(i).getImage());
    String address=productsList.get(i).getImage();
    address=address.substring(6);
    holder.image.setText(address);
    String full_address=context.getString(R.string.base_url_image)+address;
    Helper.logDebug("secondAdapter",full_address);
    Picasso.get().load(full_address).into(holder.imagee);
    holder.min_amount.setText(String.valueOf(productsList.get(i).getMin_amount()));
}

@Override
public int getItemCount() {

    Helper.logDebug("second_adapter",String.valueOf(productsList.size()));
    return productsList.size();
}
}
</code>```

outer view adapter xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

  <TextView android:layout_height="wrap_content"
  android:layout_width="wrap_content" android:text="نوع میوه"
  android:layout_marginBottom="4dp" android:layout_marginTop="4dp"
  android:layout_centerHorizontal="true" style="@style/main_titles"
  android:id="@+id/tv_type"/>

  <ImageView android:layout_height="wrap_content"
  android:layout_width="wrap_content"
  android:src="@drawable/ic_keyboard_arrow_right_black_24dp"
  android:layout_alignParentRight="true"/>

  <android.support.v7.widget.RecyclerView
  android:layout_height="wrap_content" android:layout_width="match_parent"
  android:id="@+id/recyclerview_horizental"
  android:layout_below="@id/tv_type"
  app:layoutManager="android.support.v7.widget.LinearLayoutManager"
  android:orientation="horizontal"
  tools:listitem="@layout/recycler2_layout"/>

  <TextView android:layout_height="wrap_content"
  android:layout_width="wrap_content" android:id="@+id/ad_image_address"
  android:visibility="gone"/>

  <ImageView android:layout_height="80dp" android:layout_width="match_parent"
  android:id="@+id/iv_ad"
  android:layout_below="@id/recyclerview_horizental"/>

  </RelativeLayout>
</code>```

inner view adapter xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="0dp" android:layout_weight="1"
android:id="@+id/rel_layout">

<ImageView android:layout_height="200dp" android:layout_width="match_parent"
android:id="@+id/iv_rec"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/fruit_name"
android:textColor="@color/semi_black" android:textSize="14sp"
android:layout_marginRight="8dp" android:layout_below="@id/iv_rec"
android:layout_alignParentRight="true" android:text="نام میوه"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/fruit_unit"
android:textColor="@color/black_white" android:textSize="12sp"
android:layout_below="@id/iv_rec" android:text="واحد"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_market_price"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/fruit_unit" android:text="قیمت مارکت"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_our_price"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/product_market_price" android:text="قیمت ما"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_min_amount"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/product_market_price"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"
android:visibility="gone"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_image_url"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/product_market_price"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"
android:visibility="gone"/>

</RelativeLayout>

<RelativeLayout android:layout_height="wrap_content"
android:layout_width="0dp" android:layout_weight="1"
android:visibility="gone"> </RelativeLayout>

</LinearLayout>
</code>```

final result will be something like this...(this is something similar,not exactly what xml file is)

categories are outer RecyclerView and fruits are inner RecyclerView

ask me if you have problem implementating this...

Body:
We need two RecyclerViews and two Adapters which i call inner and outer.inside ViewHolder of outer adapter put innerRecyclerView and inside onBindViewHolder of outer adapter set adapter to innerRecyclerView.i recently developed a test project like this

here is outerAdapter

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

private Context context;
private List<Category> categories;
private List<Ads> ads_list;
private List<Products> productsList;
private int count;
private int width;

public MainAdapter(Context context, List<Category> categories, List<Ads> ads_list,List<Products> productsList,int width) {
    this.context = context;
    this.categories = categories;
    this.ads_list = ads_list;
    this.productsList=productsList;
    this.width=width;
    //Helper.logDebug("main__adapter",String.valueOf(categories.size()));
    //Helper.logDebug("main_adapter","haminjoori");
}

private class ViewHolder extends RecyclerView.ViewHolder{
    private RecyclerView recyclerView;
    private TextView tv_type,ad_tv_image_address;
    private ImageView iv_ad;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        recyclerView=itemView.findViewById(R.id.recyclerview_horizental);
        recyclerView.setNestedScrollingEnabled(false);
        tv_type=itemView.findViewById(R.id.tv_type);
        iv_ad=itemView.findViewById(R.id.iv_ad);
        ad_tv_image_address=itemView.findViewById(R.id.ad_image_address);
        //Helper.logDebug("main_adapter","haminjoori");
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view= LayoutInflater.from(context).inflate(R.layout.recycler_layout,viewGroup,false);
    //Helper.logDebug("main_adapter","haminjoori");
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
    ViewHolder holder= (ViewHolder) viewHolder;
    try {
        String banner_url=ads_list.get(i).getImage();
        holder.ad_tv_image_address.setText(banner_url);
        Picasso.get().load(context.getString(R.string.base_url_banner)+banner_url).into(holder.iv_ad);
    }catch (Exception ex){
        holder.ad_tv_image_address.setText("");
    }
    Helper.logDebug("main_adapter",holder.ad_tv_image_address.getText().toString());
    holder.tv_type.setText(categories.get(i).getName());
    SecondAdapter secondAdapter=new SecondAdapter(categories.get(i).getProducts(),context,width);
    LinearLayoutManager layoutManager=new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false);

    holder.recyclerView.setLayoutManager(layoutManager);
    holder.recyclerView.setAdapter(secondAdapter);

}

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

and here is inner adapter

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

private Context context;
private int count;
private List<Products> productsList;
private List<Category> categories;
private int width;

public SecondAdapter(List<Products> productsList, Context context,int width) {
    this.productsList = productsList;
    this.context = context;
    this.width=width;
}

private class ViewHolder extends RecyclerView.ViewHolder {
    private TextView market_price,our_price,name,unit,min_amount,image;
    private ImageView imagee;
    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        itemView.getLayoutParams().width=width/2;

        market_price=itemView.findViewById(R.id.product_market_price);
        our_price=itemView.findViewById(R.id.product_our_price);
        name=itemView.findViewById(R.id.fruit_name);
        unit=itemView.findViewById(R.id.fruit_unit);
        image=itemView.findViewById(R.id.product_image_url);
        imagee=itemView.findViewById(R.id.iv_rec);
        min_amount=itemView.findViewById(R.id.product_min_amount);

        Log.d("second_adapter","haminjoori");
    }
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view= LayoutInflater.from(context).inflate(R.layout.recycler2_layout,viewGroup,false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
    ViewHolder holder= (ViewHolder) viewHolder;
    Helper.logDebug("second_adapter","haminjori");

    holder.name.setText(productsList.get(i).getName());
    holder.unit.setText(productsList.get(i).getUnit());
    holder.market_price.setText(String.valueOf(productsList.get(i).getMarketPrice()));
    holder.our_price.setText(String.valueOf(productsList.get(i).getOurPrice()));
    Helper.logDebug("secondAdapter",productsList.get(i).getImage());
    String address=productsList.get(i).getImage();
    address=address.substring(6);
    holder.image.setText(address);
    String full_address=context.getString(R.string.base_url_image)+address;
    Helper.logDebug("secondAdapter",full_address);
    Picasso.get().load(full_address).into(holder.imagee);
    holder.min_amount.setText(String.valueOf(productsList.get(i).getMin_amount()));
}

@Override
public int getItemCount() {

    Helper.logDebug("second_adapter",String.valueOf(productsList.size()));
    return productsList.size();
}
}

outer view adapter xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="wrap_content" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

  <TextView android:layout_height="wrap_content"
  android:layout_width="wrap_content" android:text="نوع میوه"
  android:layout_marginBottom="4dp" android:layout_marginTop="4dp"
  android:layout_centerHorizontal="true" style="@style/main_titles"
  android:id="@+id/tv_type"/>

  <ImageView android:layout_height="wrap_content"
  android:layout_width="wrap_content"
  android:src="@drawable/ic_keyboard_arrow_right_black_24dp"
  android:layout_alignParentRight="true"/>

  <android.support.v7.widget.RecyclerView
  android:layout_height="wrap_content" android:layout_width="match_parent"
  android:id="@+id/recyclerview_horizental"
  android:layout_below="@id/tv_type"
  app:layoutManager="android.support.v7.widget.LinearLayoutManager"
  android:orientation="horizontal"
  tools:listitem="@layout/recycler2_layout"/>

  <TextView android:layout_height="wrap_content"
  android:layout_width="wrap_content" android:id="@+id/ad_image_address"
  android:visibility="gone"/>

  <ImageView android:layout_height="80dp" android:layout_width="match_parent"
  android:id="@+id/iv_ad"
  android:layout_below="@id/recyclerview_horizental"/>

  </RelativeLayout>

inner view adapter xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="0dp" android:layout_weight="1"
android:id="@+id/rel_layout">

<ImageView android:layout_height="200dp" android:layout_width="match_parent"
android:id="@+id/iv_rec"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/fruit_name"
android:textColor="@color/semi_black" android:textSize="14sp"
android:layout_marginRight="8dp" android:layout_below="@id/iv_rec"
android:layout_alignParentRight="true" android:text="نام میوه"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/fruit_unit"
android:textColor="@color/black_white" android:textSize="12sp"
android:layout_below="@id/iv_rec" android:text="واحد"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_market_price"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/fruit_unit" android:text="قیمت مارکت"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_our_price"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/product_market_price" android:text="قیمت ما"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_min_amount"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/product_market_price"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"
android:visibility="gone"/>

<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content" android:id="@+id/product_image_url"
android:textColor="@color/semi_black" android:textSize="12sp"
android:layout_below="@id/product_market_price"
android:layout_alignParentLeft="true" android:layout_marginLeft="8dp"
android:visibility="gone"/>

</RelativeLayout>

<RelativeLayout android:layout_height="wrap_content"
android:layout_width="0dp" android:layout_weight="1"
android:visibility="gone"> </RelativeLayout>

</LinearLayout>

final result will be something like this...(this is something similar,not exactly what xml file is)

categories are outer RecyclerView and fruits are inner RecyclerView

ask me if you have problem implementating this...


来源: stackexchange

问:
STDOUT and STDERR out of order
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

```<code>File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;
</code>```

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

```<code>select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
</code>```

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

```<code>sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;
</code>```

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

```<code>use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}
</code>```

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

答:
After taking hint from @mob's answer to use IO::Tie instead of File::Tee (since the latter uses fork causing out of order STDERR vs STDOUT), I modified mob's original solution a bit and it worked (almost - read on):

```<code>use IO::Tee
...
...
open (my $log, ">", $logfilename) ;
*MYSTDOUT = *STDOUT ;
*MYSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*MYSTDOUT, $log);
*STDERR = IO::Tee->new(\*MYSTDERR, $log);
</code>```

This resulted in the correct ordering on both console and in the logfile (mob's original solution using open to dup the STDOUT/STDERR didn't work - it resulted in correct order in logfile, but out of order on console. Using a typeglob alias instead of dup works for some strange reason).

However, as good as this solution sounds, it missed printing some messages from a package which I call in the logfile (though they get printed on console). My original code which had File::Tee did result in these same messages from package being shown in the logfile, so there is some voodoo going on somewhere. The specific package in question is a .so file so I have no visibility into how exactly it prints its messages.

EDIT:
I guess that the .so file is as good as an external system command printing to stdout/stderr. Since its not going through perl IO, the handles pointed to by STDOUT/STDERR typeglobs within perl will not reflect the output of external programs called from perl.
I guess the best solution would be to use a combination of this solution for messages coming from within the perl code, and using Capture::Tiny::capture as pointed out by @zdim for capturing and redirecting messages from system calls/calls going through the swig interface.

ContentLicense: CC BY-SA 4.0

Title: STDOUT and STDERR out of order

Body:
I have a perl script which writes messages to STDOUT and STDERR (via print/croak statements), but I also redirect the STDOUT and STDERR to a logfile:

File::Tee::tee STDOUT, ">>", "$logFile" ;
File::Tee::tee STDERR, ">>", "$logFile" ;

Now the output logfile has messages from STDOUT and STDERR displayed out of order. Also the actual output on terminal is also out of order. I have tried flushing the buffers (as recommended here: https://perl.plover.com/FAQs/Buffering.html) but it doesn't help:

select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;

Does anyone know what I must do to see the output in order (I also tried additionally flushing the filehandle corresponding to $logfile, but its still the same)?

EDIT:

Thanks to all of you who have replied. A lot of the discussion over this ended up in comments, so I am going to list the few things which I tried based on feedback from all of you.

I already was flushing the STDOUT and STDERR before I used File::Tee. As @jimtut suspected, File::Tee was indeed the culprit - removing it restored the ordering on console. But I did want to redirect the STDOUT and STDERR.

@mob suggested using IO::Tee instead, but I haven't fully understood how to make that work they way I want in my code.

@briandfoy pointed out that there isn't a reliable way to ensure 2 seperate filehandles are seen in the correct order in realtime and also suggested using a logging routine which is the only place which can write to STDOUT/STDERR. @zimd further pointed out that File::Tee uses fork which is the heart of the issue since 2 processes cannot guarantee any order on output.

Since the File::Tee is to blame, I attempted to remove this from the code. I updated my logger function to print to STDOUT/STDERR as well as to additionally print to $log filehandle. Further for capturing the warns in the log, I did the following:

sub warning_handler {
  my $msg = $_[0] ;
  print STDERR $msg ;
  print $log $msg if defined $log ;
}
$SIG{__WARN__} = \&warning_handler ;

This worked great for all of the code under my control. Everything was printing in order now both on console and logfile. However I realized I can't use this solution since I was also calling someone else's perl packages for some functionality and clearly I couldn't intercept the print/croak etc which wrote to STDOUT/STDERR within the 'off the shelf' package. So right now, I don't have a good solution. However I suspect if I can find someway to intercept STDOUT/STDERR within perl, I might be able to get what I need.

EDIT2:
I added my own answer which is probably the closest I got to solving the problem by modifying mob's solution of using IO::Tee instead of File::Tee, but even this misses some messages (though it fixes ordering).

EDIT3:
Finally found the 'solution'

use IO::Tee ;
use Capture::Tiny qw(capture);
...
...
select(STDERR) ;
$| = 1 ;
select(STDOUT) ;
$| = 1 ;
open (my $log, ">", $logfilename) ;
*REALSTDOUT = *STDOUT ;
*REALSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*REALSTDOUT, $log);
*STDERR = IO::Tee->new(\*REALSTDERR, $log);

# Regular Perl code here which sends output to STDOUT/STDERR
...
...
# system calls / calls to .so needs to be catpured
&log_streams(sub { &some_func_which_calls_shared_object() ; }) ;

sub log_streams {
    my ($cr, @args) = @_;  # code reference, with its arguments
    my ($out, $err, $exit) = capture { $cr->(@args) };

    if ($out) {
        print STDOUT $out;
    }
    if ($err) {
        print STDERR $err;
    }
}

The use of IO::Tee ensures all perl generated outputs to console also go to logfile, and this happens immediately thereby updating the log and console in realtime. Since IO::Tee is changing the meaning of STDOUT/STDERR filehandles to now refer to the teed handles, it can only intercept stdio from perl statements, it misses sys calls since they bypass perl's STDOUT/STDERR handles. So we capture the syscall output and then use the log_streams routine to forward it to the now aliased STDOUT/STDERR streams. This creates a delay in the system call generated output showing up in log/terminal but there is no delay for perl generated output - i.e. best of both worlds. Do note that the ordering of stderr and stdout generated by an invocation of subroutine some_func_which_calls_shared_object is not preserved since in the log_streams routine, we first print to STDOUT and then to STDERR - as long as the system call is atomic and doesn't do much in terms of interleaving stdout/stderr messages we should be ok.
Appreciate solutions from briandfoy, mob and zimd whose answers I combined to arrive at this solution! Never thought it would require to go through this detail for what seems a very simple problem.

Body:
After taking hint from @mob's answer to use IO::Tie instead of File::Tee (since the latter uses fork causing out of order STDERR vs STDOUT), I modified mob's original solution a bit and it worked (almost - read on):

use IO::Tee
...
...
open (my $log, ">", $logfilename) ;
*MYSTDOUT = *STDOUT ;
*MYSTDERR = *STDERR ;
*STDOUT = IO::Tee->new(\*MYSTDOUT, $log);
*STDERR = IO::Tee->new(\*MYSTDERR, $log);

This resulted in the correct ordering on both console and in the logfile (mob's original solution using open to dup the STDOUT/STDERR didn't work - it resulted in correct order in logfile, but out of order on console. Using a typeglob alias instead of dup works for some strange reason).

However, as good as this solution sounds, it missed printing some messages from a package which I call in the logfile (though they get printed on console). My original code which had File::Tee did result in these same messages from package being shown in the logfile, so there is some voodoo going on somewhere. The specific package in question is a .so file so I have no visibility into how exactly it prints its messages.

EDIT:
I guess that the .so file is as good as an external system command printing to stdout/stderr. Since its not going through perl IO, the handles pointed to by STDOUT/STDERR typeglobs within perl will not reflect the output of external programs called from perl.
I guess the best solution would be to use a combination of this solution for messages coming from within the perl code, and using Capture::Tiny::capture as pointed out by @zdim for capturing and redirecting messages from system calls/calls going through the swig interface.


问:
Why is reject and throw handled differently from async functions in Promise.all?
I'm given an array of promises that I'm passing to Promise.all, but I was getting Uncaught (in promise) Error and I couldn't understand why. Trying to reproduce the error I've come to the following minimal example.

```<code>Promise
  .all([
    new Promise(async () => {
      throw new Error('thrown');
    }),
  ])
  .then(results => {
    console.log('results', results);
  })
  .catch(error => {
    console.log('error', error);
  })
</code>```

Running that you will see an "Uncaught" message in your console.

The example is fixable by removing the async keyword. But, assuming I'm given the promises from a library I don't have control over, how do I make this work?

Another way to "fix" it is by rewriting it like this

```<code>Promise
  .all([
    new Promise(async (resolve, reject) => {
      reject(new Error('rejected'));
    }),
  ])
  .then(results => {
    console.log('results', results);
  })
  .catch(error => {
    console.log('error', error);
  })
</code>```

Why does this work differently from the throw version? I thought the throw would be handled as a rejection.

EDIT:

Thanks to @CertainPerformance's answer below, my example can be simplified even further, like this

```<code>Promise
  .all([
    new Promise(async () => {
      throw new Error('thrown');
    }),
  ])
  .then(() => console.log('resolve'))
  .catch(() => console.log('reject'));
</code>```

And then getting rid of Promise.all altogether like so

```<code>new Promise(async () => {
  throw new Error('thrown');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));
</code>```

And since async is pretty much only syntactic sugar around promises, the above can be rewritten like this, and still show the same behavior

new Promise(() => {
  return new Promise(() => {
    throw new Error('thrown')
  });
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));```
</div>
</div>
</p>

<p><code>throw</code> inside a promise rejects that promise, so the above can be rewritten like this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>new Promise(() => {
  return new Promise((resolve, reject) => {
    reject('instead of throw')
  });
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));</code>```

And all that does, is immediately rejects the promise, and we have an easier way to do that:

new Promise(() => {
  return new Promise.reject('instead of throw');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));```
</div>
</div>
</p>

<p>And with that I think I fully understand why things are working the way they do.</p>

<p><strong>EDIT 2:</strong></p>

<p>Here's a longer example that more realistically mimics my actual code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function textPromise() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('data from fetch');
    }, 2000);
  });
}

function fetch(ok) {
  return Promise.resolve({
    ok,
    text: textPromise(),
  });
}

async function handleResponse(response) {
  const data = response.text;

  if (!response.ok) {
    const resolvedData = await data;
    throw new Error(resolvedData);
  }

  return data;
}

function post(ok) {
  const promise = fetch(ok)
    .then(response => handleResponse(response));

  return promise;
}

const validatorPromise = new Promise(resolve => {
  post(false).then(response => {
    if (response === 'data from fetch') {
      resolve('validated OK');
    } else {
      resolve('validated NOK');
    }
  });
});

Promise
  .all([validatorPromise])
  .then(text => console.log('text', text))
  .catch(() => console.log('reject'));</code>```

That example can most certainly be simplified, and I will try to do that. But it shows the same problem I tried to show in my original example.

The only code I have control over for now is the last Promise.all stuff. I'm given an array of "validator promises", and I need to handle when something in there throws an error

EDIT 3:

And here's a simplified version of the example above, but that still retains the async function

async function handleResponse(response) {
  throw new Error('resolvedData');
}

function post() {
  return Promise.resolve('').then(handleResponse);
}

const validatorPromise = new Promise(resolve => {
  post().then(() => resolve('validated OK'));
});

validatorPromise
  .then(text => console.log('text', text))
  .catch(() => console.log('reject'));```

(The async function will be wrapped in a promise by the JS interpreter, so essentially we will still get new Promise(async ..., but it's not as obvious here)

答:
When you pass a function to new Promise, that function is called immediately with resolve and reject parameters. If the function throws synchronously (that is, the function throws before synchronously completing), the Promise will reject, without requiring the resolve or reject parameters (if used) to be called.

When the async function is invoked, it will return a rejected Promise, but it'll still return something. In contrast, a synchronous function which throws an error will not return at all; execution stops, and the Promise.all knows that since execution stopped during execution that it should look for a .catch handler and invoke it.

When neither resolve nor reject parameters are called, and the function doesn't appear to the Promise.all to throw synchronously (in this case, the async function returns a Promise, rather than failing entirely), the Promise will remain unresolved forever. That's what's happening in your first snippet, so neither the .then nor the .catch chained off the Promise.all run.

The same behavior is exhibited with a plain Promise, without the Promise.all:

// Will remain unresolved forever, because the constructor callback successfully completes
// (and returns a rejected Promise, which goes unused)
new Promise(async () => {
  throw new Error('thrown');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Will throw synchronously, and therefore reject:
new Promise(() => {
  throw new Error('thrown');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));</code>```

The reasonable thing to do is: invoke the Promise constructor with logical paths that always eventually lead to either its resolve or reject parameter being called. (Or you can throw an error, if the Promise constructor callback isn't async)

Given the new code, which can be reduced to:

const post = ok => ok ? Promise.resolve() : Promise.reject();

const validatorPromise = new Promise(resolve => {
  post(false).then(response => {
    if (response === 'data from fetch') {
      resolve('validated OK');
    } else {
      resolve('validated NOK');
    }
  });
});

Promise
  .all([validatorPromise])
  .then(text => console.log('text', text))
  .catch(() => console.log('reject'));```

The validatorPromise function is broken. It does not catch errors from post - it only works if post does not reject. If you can't change validatorPromise (nor anything it depends on), the library you're using can be considered to be broken, because it does not handle errors. Post an issue on its github, or fork the library and fix it yourself.

Body:
I'm given an array of promises that I'm passing to Promise.all, but I was getting Uncaught (in promise) Error and I couldn't understand why. Trying to reproduce the error I've come to the following minimal example.

Promise
  .all([
    new Promise(async () => {
      throw new Error('thrown');
    }),
  ])
  .then(results => {
    console.log('results', results);
  })
  .catch(error => {
    console.log('error', error);
  })

Running that you will see an "Uncaught" message in your console.

The example is fixable by removing the async keyword. But, assuming I'm given the promises from a library I don't have control over, how do I make this work?

Another way to "fix" it is by rewriting it like this

Promise
  .all([
    new Promise(async (resolve, reject) => {
      reject(new Error('rejected'));
    }),
  ])
  .then(results => {
    console.log('results', results);
  })
  .catch(error => {
    console.log('error', error);
  })

Why does this work differently from the throw version? I thought the throw would be handled as a rejection.

EDIT:

Thanks to @CertainPerformance's answer below, my example can be simplified even further, like this

Promise
  .all([
    new Promise(async () => {
      throw new Error('thrown');
    }),
  ])
  .then(() => console.log('resolve'))
  .catch(() => console.log('reject'));

And then getting rid of Promise.all altogether like so

new Promise(async () => {
  throw new Error('thrown');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));

And since async is pretty much only syntactic sugar around promises, the above can be rewritten like this, and still show the same behavior

new Promise(() => {
  return new Promise(() => {
    throw new Error('thrown')
  });
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));

throw inside a promise rejects that promise, so the above can be rewritten like this

new Promise(() => {
  return new Promise((resolve, reject) => {
    reject('instead of throw')
  });
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));

And all that does, is immediately rejects the promise, and we have an easier way to do that:

new Promise(() => {
  return new Promise.reject('instead of throw');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));

And with that I think I fully understand why things are working the way they do.

EDIT 2:

Here's a longer example that more realistically mimics my actual code

function textPromise() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('data from fetch');
    }, 2000);
  });
}

function fetch(ok) {
  return Promise.resolve({
    ok,
    text: textPromise(),
  });
}

async function handleResponse(response) {
  const data = response.text;

  if (!response.ok) {
    const resolvedData = await data;
    throw new Error(resolvedData);
  }

  return data;
}

function post(ok) {
  const promise = fetch(ok)
    .then(response => handleResponse(response));

  return promise;
}

const validatorPromise = new Promise(resolve => {
  post(false).then(response => {
    if (response === 'data from fetch') {
      resolve('validated OK');
    } else {
      resolve('validated NOK');
    }
  });
});

Promise
  .all([validatorPromise])
  .then(text => console.log('text', text))
  .catch(() => console.log('reject'));

That example can most certainly be simplified, and I will try to do that. But it shows the same problem I tried to show in my original example.

The only code I have control over for now is the last Promise.all stuff. I'm given an array of "validator promises", and I need to handle when something in there throws an error

EDIT 3:

And here's a simplified version of the example above, but that still retains the async function

async function handleResponse(response) {
  throw new Error('resolvedData');
}

function post() {
  return Promise.resolve('').then(handleResponse);
}

const validatorPromise = new Promise(resolve => {
  post().then(() => resolve('validated OK'));
});

validatorPromise
  .then(text => console.log('text', text))
  .catch(() => console.log('reject'));

(The async function will be wrapped in a promise by the JS interpreter, so essentially we will still get new Promise(async ..., but it's not as obvious here)

Body:
When you pass a function to new Promise, that function is called immediately with resolve and reject parameters. If the function throws synchronously (that is, the function throws before synchronously completing), the Promise will reject, without requiring the resolve or reject parameters (if used) to be called.

When the async function is invoked, it will return a rejected Promise, but it'll still return something. In contrast, a synchronous function which throws an error will not return at all; execution stops, and the Promise.all knows that since execution stopped during execution that it should look for a .catch handler and invoke it.

When neither resolve nor reject parameters are called, and the function doesn't appear to the Promise.all to throw synchronously (in this case, the async function returns a Promise, rather than failing entirely), the Promise will remain unresolved forever. That's what's happening in your first snippet, so neither the .then nor the .catch chained off the Promise.all run.

The same behavior is exhibited with a plain Promise, without the Promise.all:

// Will remain unresolved forever, because the constructor callback successfully completes
// (and returns a rejected Promise, which goes unused)
new Promise(async () => {
  throw new Error('thrown');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));

// Will throw synchronously, and therefore reject:
new Promise(() => {
  throw new Error('thrown');
})
  .then(() => console.log('resolved'))
  .catch(() => console.log('rejected'));

The reasonable thing to do is: invoke the Promise constructor with logical paths that always eventually lead to either its resolve or reject parameter being called. (Or you can throw an error, if the Promise constructor callback isn't async)

Given the new code, which can be reduced to:

const post = ok => ok ? Promise.resolve() : Promise.reject();

const validatorPromise = new Promise(resolve => {
  post(false).then(response => {
    if (response === 'data from fetch') {
      resolve('validated OK');
    } else {
      resolve('validated NOK');
    }
  });
});

Promise
  .all([validatorPromise])
  .then(text => console.log('text', text))
  .catch(() => console.log('reject'));

The validatorPromise function is broken. It does not catch errors from post - it only works if post does not reject. If you can't change validatorPromise (nor anything it depends on), the library you're using can be considered to be broken, because it does not handle errors. Post an issue on its github, or fork the library and fix it yourself.


问:
Javascript, jQuery, Do function after another function
I have this javascript function.

```<code><script type="text/javascript">
  $(document).ready(function () {
  $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>');
  $('#loaded').fadeIn(1500);
     $('#load').fadeOut(2000);
  });
</script>
</code>```

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

```<code>As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.
</code>```

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?

答:
Your code won't "load" the image.  All it does is add the image tag to the DOM. The browser will try to add the image once the tag is added to the DOM.

Your best bet is to add the image to the HTML code and hide it with css.  Then use jQuery's show function to show it rather than try to load the image.

An alternative would be to "preload" the image with javascript, but I don't see how that would be more efficient.

ContentLicense: CC BY-SA 3.0

Body:
I have this javascript function.

As you may see it simply runs a loading image for a tot of seconds, then shows the div and hide the loading image.
This is not good for me. I need a function that will work in this way. The logic of the code would be:

As soon as $('#load').html('<img style="display:block; margin:10px auto;background-color: #EEE;" src="<?echo $site["url"];?>images/icons/loading.gif"/>'); is running, then wait 4 seconds, and then show the #loaded DIV.

In this way the #loaded DIV will be fully loaded and it will work fine, since it is an heavy one.

In few words I must to be sure that #loaded has been fully loaded by the browser before showing it.
How can I create a function that will do that?

On document ready show the loading DIV. Then WAIT for 3-4 seconds, then make the loading disappear and the loaded DIV visible.

Is this possible?


问:
Finding the appropriate CNN Model Architecture and Parameters
I am currently creating a CNN model that classifies whether the font is Arial, Verdana, Times New Roman and Georgia. All in all there are 16 classes since I considered also detecting whether the font is regular, bold, italics or bold italics. So 4 fonts * 4 styles = 16 classes.

The data that I have used in my training are the following:

```<code> Training data set : 800 image patches of 256 * 256 dimension (50 for each class)
 Validation data set : 320 image patches of 256 * 256 dimension (20 for each class)
 Testing data set : 160 image patches of 256 * 256 dimension (10 for each class)
</code>```

Below is the sample screenshot of my data:

Below is my initial code:

```<code>import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
import itertools
import matplotlib.pyplot as plt
import pickle

image_width = 256
image_height = 256

train_path = 'font_model_data/train'
valid_path =  'font_model_data/valid'
test_path = 'font_model_data/test'

train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 160)

 imgs, labels = next(train_batches)

 #CNN model
 model = Sequential([
     Conv2D(32, (3,3), activation='relu', input_shape=(image_width, image_height, 3)),
     Flatten(),
     Dense(16, activation='softmax'),
 ])

 print(model.summary())

 model.compile(Adam(lr=.0001),loss='categorical_crossentropy', metrics=['accuracy'])
 model.fit_generator(train_batches, steps_per_epoch = 50, validation_data= valid_batches, validation_steps = 20, epochs = 1, verbose = 2)

 model_pickle = open('cnn_font_model.pickle', 'wb')
 pickle.dump(model, model_pickle)
 model_pickle.close()
 print('Training Done.')

 test_imgs, test_labels = next(test_batches)

 predictions = model.predict_generator(test_batches, steps = 160, verbose = 2)
 print(predictions)
</code>```

Can anyone suggest how will I know the right network architecture and parameters to get the optimal accuracy? How should I start tweaking my network?

答:
Before going to choose Network you need to segmentize the image tile into subtitles with characters and feed to the following architecture...</p>

```<code># Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
classifier.fit_generator(training_set,
                     steps_per_epoch = XXX,
                     epochs = XX,
                     validation_data = test_set,
                     validation_steps = XXX)
from keras.models import load_model
classifier.save('your_classifier.h5')
</code>```

Body:
I am currently creating a CNN model that classifies whether the font is Arial, Verdana, Times New Roman and Georgia. All in all there are 16 classes since I considered also detecting whether the font is regular, bold, italics or bold italics. So 4 fonts * 4 styles = 16 classes.

The data that I have used in my training are the following:

 Training data set : 800 image patches of 256 * 256 dimension (50 for each class)
 Validation data set : 320 image patches of 256 * 256 dimension (20 for each class)
 Testing data set : 160 image patches of 256 * 256 dimension (10 for each class)

Below is the sample screenshot of my data:

Below is my initial code:

import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
import itertools
import matplotlib.pyplot as plt
import pickle

image_width = 256
image_height = 256

train_path = 'font_model_data/train'
valid_path =  'font_model_data/valid'
test_path = 'font_model_data/test'

train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 160)

 imgs, labels = next(train_batches)

 #CNN model
 model = Sequential([
     Conv2D(32, (3,3), activation='relu', input_shape=(image_width, image_height, 3)),
     Flatten(),
     Dense(16, activation='softmax'),
 ])

 print(model.summary())

 model.compile(Adam(lr=.0001),loss='categorical_crossentropy', metrics=['accuracy'])
 model.fit_generator(train_batches, steps_per_epoch = 50, validation_data= valid_batches, validation_steps = 20, epochs = 1, verbose = 2)

 model_pickle = open('cnn_font_model.pickle', 'wb')
 pickle.dump(model, model_pickle)
 model_pickle.close()
 print('Training Done.')

 test_imgs, test_labels = next(test_batches)

 predictions = model.predict_generator(test_batches, steps = 160, verbose = 2)
 print(predictions)

Can anyone suggest how will I know the right network architecture and parameters to get the optimal accuracy? How should I start tweaking my network?

Body:
Before going to choose Network you need to segmentize the image tile into subtitles with characters and feed to the following architecture...

# Initialising the CNN
classifier = Sequential()

# Step 1 - Convolution
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Adding a second convolutional layer
classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening
classifier.add(Flatten())

# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
classifier.fit_generator(training_set,
                     steps_per_epoch = XXX,
                     epochs = XX,
                     validation_data = test_set,
                     validation_steps = XXX)
from keras.models import load_model
classifier.save('your_classifier.h5')


问:
'gitk' installation is not working on Linux
I have successfully Git installed and running.

```<code>git --version
git version 2.6.1
</code>```

I want to add gitk now. I entered the following command to install the gitk package, but it says no package available.

sudo yum install git-gui gitk

Returns

```<code>Loaded plugins: security
Setting up Install Process
No package git-gui available.
No package gitk available.
Nothing to do
</code>```

After that, when I type gitk on the command line, it throws the following error.

```<code>Application initialization failed: Can't find a usable tk.tcl in the following directories:
    /usr/lib/tcl8.4/tk8.4 /usr/lib/tk8.4 /local/p4clients/pkgbuild-9867w/workspace/build/TclTk/TclTk-8.4.199.32504/RHEL5_64/DEV.STD.PTHREAD/build/private/tcl/install/lib/tk8.4 /lib/tk8.4 /usr/library /library /tk8.4.12/library
This probably means that tk wasn't installed properly.

Error in startup script: invalid command name "tk_setPalette"
    while executing
"tk_setPalette background $c selectColor $selc"
    (procedure "setui" line 8)
    invoked from within
"setui $uicolor"
</code>```

Note: I tried apt-get, but it’s not working in the system. In a post I found that YUM is the correct one for my system.

Amazon Linux: apt-get: command not found

答:
I'm not sure which flavour you are trying to install gitk on. But the below is the method which I have used to install gitk on RHEL 7.

Get the endpoint release rpm from https://packages.endpoint.com/ as below

```<code>cd /tmp
wget https://packages.endpoint.com/rhel/7/os/x86_64/endpoint-repo-1.7-1.x86_64.rpm
yum localinstall endpoint-repo-1.7-1.x86_64.rpm
yum install git-gui gitk
</code>```

Change the current directory to one of your projects where the .git directory is there and type gitk and Enter:

Body:
I have successfully Git installed and running.

git --version
git version 2.6.1

I want to add gitk now. I entered the following command to install the gitk package, but it says no package available.

sudo yum install git-gui gitk

Returns

Loaded plugins: security
Setting up Install Process
No package git-gui available.
No package gitk available.
Nothing to do

After that, when I type gitk on the command line, it throws the following error.

Application initialization failed: Can't find a usable tk.tcl in the following directories:
    /usr/lib/tcl8.4/tk8.4 /usr/lib/tk8.4 /local/p4clients/pkgbuild-9867w/workspace/build/TclTk/TclTk-8.4.199.32504/RHEL5_64/DEV.STD.PTHREAD/build/private/tcl/install/lib/tk8.4 /lib/tk8.4 /usr/library /library /tk8.4.12/library
This probably means that tk wasn't installed properly.

Error in startup script: invalid command name "tk_setPalette"
    while executing
"tk_setPalette background $c selectColor $selc"
    (procedure "setui" line 8)
    invoked from within
"setui $uicolor"

Note: I tried apt-get, but it’s not working in the system. In a post I found that YUM is the correct one for my system.

Amazon Linux: apt-get: command not found

Body:
I'm not sure which flavour you are trying to install gitk on. But the below is the method which I have used to install gitk on RHEL 7.

Get the endpoint release rpm from https://packages.endpoint.com/ as below

cd /tmp
wget https://packages.endpoint.com/rhel/7/os/x86_64/endpoint-repo-1.7-1.x86_64.rpm
yum localinstall endpoint-repo-1.7-1.x86_64.rpm
yum install git-gui gitk

Change the current directory to one of your projects where the .git directory is there and type gitk and Enter:


问:
.NET Core 3.0 ILogger testing
I just migrated from .NET Core 2.2 to .NET Core 3.0 and... My tests have failed.

Below code is working in .NET Core 2.2 but is failing in .NET Core 3.0 with

Expected invocation on the mock once, but was 0 times: l => l.Log<object>(LogLevel.Error, 0, It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>())

```<code>var services = Mock.Of<IServiceCollection>();
var configurationMock = new Mock<IConfiguration>();
var loggerMock = new Mock<ILogger>();

services.AddCustomersConfiguration(configurationMock.Object, loggerMock.Object);

configurationMock.Verify(c => c.GetSection(Customers), Times.Once);
loggerMock.Verify(l => l.Log<object>(LogLevel.Error, (EventId)0, It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>()), Times.Once);
</code>```

Implementation of used method

```<code>public static void AddCustomersConfiguration(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
    logger.LogDebug($"Entering {nameof(AddCustomersConfiguration)} method.");
    var customersSection = configuration.GetSection(CustomersSectionKey);
    if (!customersSection.Exists())
    {
        logger.LogError($"There is no {CustomersSectionKey} section in configuration.");
        return;
    }
}
</code>```

That would be helpful if you would have any suggestions

答:
In addition to the accepted answer, consider strengthening the assert to include the log message

```<code>loggerMock.Verify(l => l.Log(
                LogLevel.Error,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => ((IReadOnlyList<KeyValuePair<string, object>>)o).Last().Value.ToString().Equals(expectedLogMessage)),
                null,
                (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()),
                Times.Once);
</code>```

The last item of the logged values (key: OriginalMessage) has the message that was provided to the log method.

Title: .NET Core 3.0 ILogger testing

Body:
I just migrated from .NET Core 2.2 to .NET Core 3.0 and... My tests have failed.

Below code is working in .NET Core 2.2 but is failing in .NET Core 3.0 with

Expected invocation on the mock once, but was 0 times: l => l.Log<object>(LogLevel.Error, 0, It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>())

var services = Mock.Of<IServiceCollection>();
var configurationMock = new Mock<IConfiguration>();
var loggerMock = new Mock<ILogger>();

services.AddCustomersConfiguration(configurationMock.Object, loggerMock.Object);

configurationMock.Verify(c => c.GetSection(Customers), Times.Once);
loggerMock.Verify(l => l.Log<object>(LogLevel.Error, (EventId)0, It.IsAny<object>(), null, It.IsAny<Func<object, Exception, string>>()), Times.Once);

Implementation of used method

public static void AddCustomersConfiguration(this IServiceCollection services, IConfiguration configuration, ILogger logger)
{
    logger.LogDebug($"Entering {nameof(AddCustomersConfiguration)} method.");
    var customersSection = configuration.GetSection(CustomersSectionKey);
    if (!customersSection.Exists())
    {
        logger.LogError($"There is no {CustomersSectionKey} section in configuration.");
        return;
    }
}

That would be helpful if you would have any suggestions

Body:
In addition to the accepted answer, consider strengthening the assert to include the log message

loggerMock.Verify(l => l.Log(
                LogLevel.Error,
                It.IsAny<EventId>(),
                It.Is<It.IsAnyType>((o, t) => ((IReadOnlyList<KeyValuePair<string, object>>)o).Last().Value.ToString().Equals(expectedLogMessage)),
                null,
                (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()),
                Times.Once);

The last item of the logged values (key: OriginalMessage) has the message that was provided to the log method.


问:
Calculate Price Method Not Working In Visual Studio
So I've made this form that acts as a cake shop. I have everything working perfectly except for the price. For some reason it isn't displaying properly and shows "$22.60" every time. I'm thinking there might be something wrong with the method

```<code>public virtual double CalculateCakeCost()
    {
        return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
    }
</code>```

from class "Cake" since it seems to return the cake price, but not add it up with the bracket values. The calculate cost with tax method from the class "CustomCake" also seems to be working fine. You can read the rest of the code is down below and please tell me if there is a problem, because I don't see anything wrong.

```<code>namespace Lab_OrderCake_The_Bakery_
{

public partial class frmOrderCake : Form
{
    Cake objcake;
    CustomCake objcustcake;
    Customer objcustomer;
    Order objorder;

    public frmOrderCake()
    {
        InitializeComponent();
    }

    private void btnOrder_Click(object sender, EventArgs e)
    {
        //flavour
        if (radVanilla.Checked == true)
        {
            txtRadFlavour.Text = "Vanilla";
        }
        if (radChocolate.Checked == true)
        {
            txtRadFlavour.Text = "Chocolate";
        }
        if (radBanana.Checked == true)
        {
            txtRadFlavour.Text = "Banana";
        }
        if (radLemonBerry.Checked == true)
        {
            txtRadFlavour.Text = "Lemon banana";
        }

        //layers
        if (rad1layer.Checked == true)
        {
            numRadLayers.Value = 1;
        }
        if (rad2layers.Checked == true)
        {
            numRadLayers.Value = 2;
        }
        if (rad3layers.Checked == true)
        {
            numRadLayers.Value = 3;
        }
        if (rad4layers.Checked == true)
        {
            numRadLayers.Value = 4;
        }

        //occassion
        if (radAnniversary.Checked == true)
        {
            txtRadOcc.Text = "Anniversary";
        }
        if (radBirthday.Checked == true)
        {
            txtRadOcc.Text = "Birthday";
        }
        if (radRetirement.Checked == true)
        {
            txtRadOcc.Text = "Retirement";
        }
        if (radWedding.Checked == true)
        {
            txtRadOcc.Text = "Wedding";
        }

        //size
        if (rad6inch.Checked == true)
        {
            numRadSize.Value = 6;
        }
        if (rad8inch.Checked == true)
        {
            numRadSize.Value = 8;
        }
        if (rad10inch.Checked == true)
        {
            numRadSize.Value = 10;
        }
        if (rad12inch.Checked == true)
        {
            numRadSize.Value = 12;
        }

        //design
        if (radPolka.Checked == true)
        {
            txtRadDesign.Text = "Polka Dots";

        }
        if (rad8inch.Checked == true)
        {
            txtRadDesign.Text = "Edible Images";
        }
        if (rad10inch.Checked == true)
        {
            txtRadDesign.Text = "Fondant Bow";
        }
        if (rad12inch.Checked == true)
        {
            txtRadDesign.Text = "3D Figures";
        }

        objcake = new Cake(txtRadFlavour.Text, (int)numRadLayers.Value);
        objcustomer = new Customer(txtFName.Text, txtLName.Text);
        objcustcake = new CustomCake(txtRadFlavour.Text, (int)numRadLayers.Value, txtRadOcc.Text,
(int)numRadSize.Value, txtRadDesign.Text);
        objorder = new Order();

        lblOutOrder.Text = objcustomer.ToString() + objcustcake.ToString() + objorder.ToString();

    }
}

namespace CakeClasses
{
public class Cake
{
    public int NumOfLayers { get; set; }
    public string Flavour { get; set; }
    public double Price { get; set; }

    public const double CAKE_PRICE = 20;

    public const int LAYER_PRICE = 3;

    public Cake()
    {
        Flavour = "";
        NumOfLayers = 0;
    }

    public Cake(string flavour, int numLayers)
    {
        NumOfLayers = numLayers;
        Flavour = flavour;
    }

    **public virtual double CalculateCakeCost()
    {
        return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
    }**

    public override string ToString()
    {
        return " " + Flavour + " flavoured cake with " + NumOfLayers + " layer(s)";
    }
  }
}

namespace CakeClasses
{
public class Order
{
    public Customer Customer { get; set; }
    public Cake Cake { get; set; }
    public int NumOfCakes { get; set; }

    public Order()
    {
        Customer = new Customer();
        Cake = new Cake();
        NumOfCakes = 1;
    }

    public Order(string fName, string lName, string flavour, int numLayers, string occasion, int
diameter, string design)
    {
        Customer = new Customer(fName, lName);
        Cake = new CustomCake(flavour, numLayers, occasion,diameter,design);
        NumOfCakes = 1;
    }

    public Order(string fName, string lName, string flavour, int numLayers)
    {
        Customer = new Customer(fName, lName);
        Cake = new Cake(flavour, numLayers);
        NumOfCakes = 1;
    }

    public double CalculateCostWithTax()
    {
        return Cake.CalculateCakeCost() * 1.13;
    }

    public override string ToString()
    {
        return "for the total cost of " + CalculateCostWithTax().ToString("C");
    }
}
}

namespace CakeClasses
{
public class CustomCake : Cake
{
    public string Occasion { get; set; }
    public int Size { get; set; }
    public string Design { get; set; }
    private double DesignCost { get; set; }

    public CustomCake(string flavour, int numLayers,string occasion, int diameter, string design)
        :base(flavour,numLayers)
    {
        Occasion = occasion;
        Size = diameter;
        Design = design;
         switch (Design)
         {
             case "Polka Dots":
                DesignCost = 5;
                 break;
             case "Edible Images":
                 DesignCost = 12;
                 break;
             case "Fondant Bow":
                DesignCost = 10;
                 break;
             default:
                DesignCost = 15;
                 break;
         }
    }
    public override double CalculateCakeCost()
    {
        return base.CalculateCakeCost() + Size + DesignCost;
    }
    public override string ToString()
    {
        return base.ToString() +  " with " + Design + " design for " + Occasion + " occassion and
size is " + Size + " inches " ;
    }
}
}
</code>```

答:
Try replacing following line in your code:

```<code>objorder = new Order();
</code>```

with:

```<code>objorder = new Order("First Name","Last Name",txtRadFlavour.Text, (int)numRadLayers.Value);
</code>```

Body:
So I've made this form that acts as a cake shop. I have everything working perfectly except for the price. For some reason it isn't displaying properly and shows "$22.60" every time. I'm thinking there might be something wrong with the method

public virtual double CalculateCakeCost()
    {
        return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
    }

from class "Cake" since it seems to return the cake price, but not add it up with the bracket values. The calculate cost with tax method from the class "CustomCake" also seems to be working fine. You can read the rest of the code is down below and please tell me if there is a problem, because I don't see anything wrong.

namespace Lab_OrderCake_The_Bakery_
{

public partial class frmOrderCake : Form
{
    Cake objcake;
    CustomCake objcustcake;
    Customer objcustomer;
    Order objorder;

    public frmOrderCake()
    {
        InitializeComponent();
    }

    private void btnOrder_Click(object sender, EventArgs e)
    {
        //flavour
        if (radVanilla.Checked == true)
        {
            txtRadFlavour.Text = "Vanilla";
        }
        if (radChocolate.Checked == true)
        {
            txtRadFlavour.Text = "Chocolate";
        }
        if (radBanana.Checked == true)
        {
            txtRadFlavour.Text = "Banana";
        }
        if (radLemonBerry.Checked == true)
        {
            txtRadFlavour.Text = "Lemon banana";
        }

        //layers
        if (rad1layer.Checked == true)
        {
            numRadLayers.Value = 1;
        }
        if (rad2layers.Checked == true)
        {
            numRadLayers.Value = 2;
        }
        if (rad3layers.Checked == true)
        {
            numRadLayers.Value = 3;
        }
        if (rad4layers.Checked == true)
        {
            numRadLayers.Value = 4;
        }

        //occassion
        if (radAnniversary.Checked == true)
        {
            txtRadOcc.Text = "Anniversary";
        }
        if (radBirthday.Checked == true)
        {
            txtRadOcc.Text = "Birthday";
        }
        if (radRetirement.Checked == true)
        {
            txtRadOcc.Text = "Retirement";
        }
        if (radWedding.Checked == true)
        {
            txtRadOcc.Text = "Wedding";
        }

        //size
        if (rad6inch.Checked == true)
        {
            numRadSize.Value = 6;
        }
        if (rad8inch.Checked == true)
        {
            numRadSize.Value = 8;
        }
        if (rad10inch.Checked == true)
        {
            numRadSize.Value = 10;
        }
        if (rad12inch.Checked == true)
        {
            numRadSize.Value = 12;
        }

        //design
        if (radPolka.Checked == true)
        {
            txtRadDesign.Text = "Polka Dots";

        }
        if (rad8inch.Checked == true)
        {
            txtRadDesign.Text = "Edible Images";
        }
        if (rad10inch.Checked == true)
        {
            txtRadDesign.Text = "Fondant Bow";
        }
        if (rad12inch.Checked == true)
        {
            txtRadDesign.Text = "3D Figures";
        }

        objcake = new Cake(txtRadFlavour.Text, (int)numRadLayers.Value);
        objcustomer = new Customer(txtFName.Text, txtLName.Text);
        objcustcake = new CustomCake(txtRadFlavour.Text, (int)numRadLayers.Value, txtRadOcc.Text,
(int)numRadSize.Value, txtRadDesign.Text);
        objorder = new Order();

        lblOutOrder.Text = objcustomer.ToString() + objcustcake.ToString() + objorder.ToString();

    }
}

namespace CakeClasses
{
public class Cake
{
    public int NumOfLayers { get; set; }
    public string Flavour { get; set; }
    public double Price { get; set; }

    public const double CAKE_PRICE = 20;

    public const int LAYER_PRICE = 3;

    public Cake()
    {
        Flavour = "";
        NumOfLayers = 0;
    }

    public Cake(string flavour, int numLayers)
    {
        NumOfLayers = numLayers;
        Flavour = flavour;
    }

    **public virtual double CalculateCakeCost()
    {
        return CAKE_PRICE + (LAYER_PRICE * NumOfLayers);
    }**

    public override string ToString()
    {
        return " " + Flavour + " flavoured cake with " + NumOfLayers + " layer(s)";
    }
  }
}

namespace CakeClasses
{
public class Order
{
    public Customer Customer { get; set; }
    public Cake Cake { get; set; }
    public int NumOfCakes { get; set; }

    public Order()
    {
        Customer = new Customer();
        Cake = new Cake();
        NumOfCakes = 1;
    }

    public Order(string fName, string lName, string flavour, int numLayers, string occasion, int
diameter, string design)
    {
        Customer = new Customer(fName, lName);
        Cake = new CustomCake(flavour, numLayers, occasion,diameter,design);
        NumOfCakes = 1;
    }

    public Order(string fName, string lName, string flavour, int numLayers)
    {
        Customer = new Customer(fName, lName);
        Cake = new Cake(flavour, numLayers);
        NumOfCakes = 1;
    }

    public double CalculateCostWithTax()
    {
        return Cake.CalculateCakeCost() * 1.13;
    }

    public override string ToString()
    {
        return "for the total cost of " + CalculateCostWithTax().ToString("C");
    }
}
}

namespace CakeClasses
{
public class CustomCake : Cake
{
    public string Occasion { get; set; }
    public int Size { get; set; }
    public string Design { get; set; }
    private double DesignCost { get; set; }

    public CustomCake(string flavour, int numLayers,string occasion, int diameter, string design)
        :base(flavour,numLayers)
    {
        Occasion = occasion;
        Size = diameter;
        Design = design;
         switch (Design)
         {
             case "Polka Dots":
                DesignCost = 5;
                 break;
             case "Edible Images":
                 DesignCost = 12;
                 break;
             case "Fondant Bow":
                DesignCost = 10;
                 break;
             default:
                DesignCost = 15;
                 break;
         }
    }
    public override double CalculateCakeCost()
    {
        return base.CalculateCakeCost() + Size + DesignCost;
    }
    public override string ToString()
    {
        return base.ToString() +  " with " + Design + " design for " + Occasion + " occassion and
size is " + Size + " inches " ;
    }
}
}

Body:
Try replacing following line in your code:

objorder = new Order();

with:

objorder = new Order("First Name","Last Name",txtRadFlavour.Text, (int)numRadLayers.Value);


问:
Adding a legend to ggplot2 facets with multiple lines?
I have got a problem with my ggplot for faceted multiple line plots for seven metropolitan regions in South Korea.

The structure of my csv dataset is just similar to a panel data with both cross-sectional and time series dimensions for cities over time.

Below is the format of my dataset:

```<code>Year   City    VKT index  GDP index
2012   Seoul      100      100
2013   Seoul      94       105
2014   Seoul      96       110
..............................
2012   Busan      100      100
2013   Busan      97       105
..............................
2012   Daegu     100       100
2013   Daegu     104       114
</code>```

My code is also as follows:

```<code>deccity <- read_csv("decouplingbycity.csv")

deccity %>% filter(is.na(Year) == FALSE) %>%
ggplot(deccity, mapping = aes(x=Year)) +
  geom_line(size = 1, aes(y = `GDP index`), color = "darkred") +
  geom_line(size = 1,aes(y = `VKT index`), color="steelblue", linetype="twodash")+
  labs(y="Index: 1992=100",
       title = "Decoupling by city")+
  facet_wrap(~City)
</code>```

You can see the plot I've got now. However there is a problem, and the obvious issue is that I can't see my legends for 'VKT index' and 'GDP index' variables. I would greatly appreciate if anyone could chime in and sort out another way to do this.

Kindly refer to my multi-panel plots without legend for deeper insights into what i'm looking for:

答:
This is how I've tweaked my code to get the multi-panel plots i wanted. Thanks to datanovia for the great reference materials! I've also included a legend.

```<code>dahir %>% filter(is.na(Year) == FALSE) %>%
ggplot(dahir, mapping = aes(x = Year, y = value)) +
  geom_line(size = 1.2, aes(color = variable, linetype = variable)) +
  scale_color_manual(values = c("darkred", "steelblue"))+
  labs(y="Index: 2012=100",
       title = "Decoupling by City")+
  facet_wrap (~City)
</code>```

Decoupling in metropolitan cities

Body:
I have got a problem with my ggplot for faceted multiple line plots for seven metropolitan regions in South Korea.

The structure of my csv dataset is just similar to a panel data with both cross-sectional and time series dimensions for cities over time.

Below is the format of my dataset:

Year   City    VKT index  GDP index
2012   Seoul      100      100
2013   Seoul      94       105
2014   Seoul      96       110
..............................
2012   Busan      100      100
2013   Busan      97       105
..............................
2012   Daegu     100       100
2013   Daegu     104       114

My code is also as follows:

deccity <- read_csv("decouplingbycity.csv")

deccity %>% filter(is.na(Year) == FALSE) %>%
ggplot(deccity, mapping = aes(x=Year)) +
  geom_line(size = 1, aes(y = `GDP index`), color = "darkred") +
  geom_line(size = 1,aes(y = `VKT index`), color="steelblue", linetype="twodash")+
  labs(y="Index: 1992=100",
       title = "Decoupling by city")+
  facet_wrap(~City)

You can see the plot I've got now. However there is a problem, and the obvious issue is that I can't see my legends for 'VKT index' and 'GDP index' variables. I would greatly appreciate if anyone could chime in and sort out another way to do this.

Kindly refer to my multi-panel plots without legend for deeper insights into what i'm looking for:

Body:
This is how I've tweaked my code to get the multi-panel plots i wanted. Thanks to datanovia for the great reference materials! I've also included a legend.

dahir %>% filter(is.na(Year) == FALSE) %>%
ggplot(dahir, mapping = aes(x = Year, y = value)) +
  geom_line(size = 1.2, aes(color = variable, linetype = variable)) +
  scale_color_manual(values = c("darkred", "steelblue"))+
  labs(y="Index: 2012=100",
       title = "Decoupling by City")+
  facet_wrap (~City)

Decoupling in metropolitan cities


答:
This snippet might help you

const data = require("./path/to/your/json/file");
const averageTs = data.reduce((acc, current) => acc + current.ts, 0)/data.length;
const averageCpu = data.reduce((acc, current) => acc + current.cpu, 0)/data.length;
// do the same for other values
```

Title: How to get the average of the total values from json file using nodejs


问:
Display Many To Many Relationship from Entity Model in ASP.NET GridView Control
Lets say i have two tables: Cars and BodyStyle with a many to many relationship.

In Data Entity Model it would show the two tables but in Sql it has a helper table to link since its a many to many relationship.

I want to know how is it possible to display the all the Styles related to an instance of Car inside a gridview.

so basically the gridview should look like:

ID | Make | Model | Style |

 ----------------------------------'

1 | Acura | EL | Sedan, Luxury|

2 | Acura | MDX | SUV, Luxury|

I cant seem to access the helping table through c#

Sorry I am new to c# programming.

答: Can you not add the helper table into the edm? I would start with adding that or else how would the m know of the existence of the helper table.</p>


问:
Issues understanding how to deploy Nuxtjs ( or js in general ) applications with npm
I know this might appear to be a dump question but I simply cannot understand exactly how the deployment of these javascript applications works.

So basically I am working on an announcements application that obviously needs to have good SEO and most importantly be crawled and indexed by Google. I have been reading about Nuxt and SSR and went off with it.

I watched this video https://www.youtube.com/watch?v=vlUZw1J0kwM but I still can't fully understand.

What's the difference between npm run build and npm run generate

One appears to be just an index.html and a bunch of js files (with
some kind of hashes for names) and the  other has files like (
router.js, store.js etc.. ). Also one is in a dist folder and the
other in some hidden .nuxt folder.

Which one of those are using SSR and whether either one of them can
be indexed so the announcements actually will start to appear on
google searches

Do I also take the whole code on production or only the build/generate files

答:
if you want to make ssr app you should use npm run build and nuxt will build your app otherwise if you want to deploy your code in spa mode or static (like github pages) you can use npm run generate so nuxt generate some html code for you

according to nuxtjs documentation:

nuxt build => Build your application with webpack and minify the JS & CSS (for production).

nuxt generate => Build the application and generate every route as a HTML file (used for static hosting).


问:
Why adding only multiDexEnabled works fine
Recently I've been struggling with multidexing in android and this question comes to my mind:

To enable multiDex in android project

If you only and only add this line:

```<code>// gradle build config
multiDexEnabled true
</code>```

The app will compile and works fine.

But the real solution is to:

Add multiDexEnabled true

Add the support library androidx.multidex

Override Application class.

Why adding only multiDexEnabled true works and project runs successfully? What about the other two steps remained

Am I not considering something?

BTW, my minSdkVersion is 15

答:
Enable multidex for apps with over 64K methodsHere is the link by Google itself.

When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture:

```<code>trouble writing output:
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.
</code>```

Older versions of the build system report a different error, which is an indication of the same problem:

```<code>Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536
</code>```

Both these error conditions display a common number: 65536. This number represents the total number of references that can be invoked by the code within a single Dalvik Executable (DEX) bytecode file. This page explains how to move past this limitation by enabling an app configuration known as multidex, which allows your app to build and read multiple DEX files.

About the 64K reference limit

Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the '64K reference limit'.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:

```<code>dependencies {
    def multidex_version = "2.0.1"
    implementation 'androidx.multidex:multidex:$multidex_version'
}
</code>```

If you aren't using AndroidX, add the following support library dependency instead:

```<code>implementation 'com.android.support:multidex:1.0.3'
</code>```

Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

```<code>android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}
</code>```

Depending on whether you override the Application class, perform one of the following:

If you do not override the Application class, edit your manifest file to set android:name in the  tag as follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>
</code>```

If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:

```<code>public class MyApplication extends MultiDexApplication { ... }
</code>```

Or if you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex

```<code>public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}
</code>```

Body:
Recently I've been struggling with multidexing in android and this question comes to my mind:

To enable multiDex in android project

If you only and only add this line:

// gradle build config
multiDexEnabled true

The app will compile and works fine.

But the real solution is to:

Add multiDexEnabled true

Add the support library androidx.multidex

Override Application class.

Why adding only multiDexEnabled true works and project runs successfully? What about the other two steps remained

Am I not considering something?

BTW, my minSdkVersion is 15

Body:
Enable multidex for apps with over 64K methodsHere is the link by Google itself.

When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture:

trouble writing output:
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.

Older versions of the build system report a different error, which is an indication of the same problem:

Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536

Both these error conditions display a common number: 65536. This number represents the total number of references that can be invoked by the code within a single Dalvik Executable (DEX) bytecode file. This page explains how to move past this limitation by enabling an app configuration known as multidex, which allows your app to build and read multiple DEX files.

About the 64K reference limit

Android app (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the '64K reference limit'.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 (API level 21) use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can add the multidex support library to your project:

dependencies {
    def multidex_version = "2.0.1"
    implementation 'androidx.multidex:multidex:$multidex_version'
}

If you aren't using AndroidX, add the following support library dependency instead:

implementation 'com.android.support:multidex:1.0.3'

Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

Depending on whether you override the Application class, perform one of the following:

If you do not override the Application class, edit your manifest file to set android:name in the  tag as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>

If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:

public class MyApplication extends MultiDexApplication { ... }

Or if you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex

public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}


问:
Concatenating from "int" to string in discord.py
I am trying to pull a site's status code by a discord command.
First I define the request and such

```<code>r = requests.get('redactedsiteurl')
test = r.status_code
</code>```

Then after going through and defining the command and all, I add the code to the embed

```<code>embed.description = '**Status Code:**' + r.status_code
</code>```

This draws the following error:

```<code>Traceback (most recent call last):
  File "C:\Users\jokzc\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "test2.py", line 16, in on_message
    embed.description = '**Status Code:**' + r.status_code
TypeError: can only concatenate str (not "int") to str
</code>```

Is there another method that would do what i want without concatenation? Thanks :)

答:
You can use f-strings:</p>

```<code>embed.description = f'**Status Code:**{r.status_code}'
</code>```

Body:
I am trying to pull a site's status code by a discord command.
First I define the request and such

r = requests.get('redactedsiteurl')
test = r.status_code

Then after going through and defining the command and all, I add the code to the embed

embed.description = '**Status Code:**' + r.status_code

This draws the following error:

Traceback (most recent call last):
  File "C:\Users\jokzc\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "test2.py", line 16, in on_message
    embed.description = '**Status Code:**' + r.status_code
TypeError: can only concatenate str (not "int") to str

Is there another method that would do what i want without concatenation? Thanks :)

Body:
You can use f-strings:

embed.description = f'**Status Code:**{r.status_code}'


问:
Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6
When trying to run the Example CorDapp (GitHub CorDapp) via IntelliJ, I receive the following error:

Cannot inline bytecode built with JVM target 1.8 into bytecode that is
being built with JVM target 1.6

How can I modify the IntelliJ settings so that all the bytecode is built with the same JVM target?

答:
Setting sourceCompatibility = JavaVersion.VERSION_1_8 enables desugaring, but it is currently unable to desugar all the Java 8 features that the Kotlin compiler uses.

Fix - Setting kotlinOptions.jvmTarget to JavaVersion.VERSION_1_8 in the app module Gradle would fix the issue.

Use Java 8 language features:
  https://developer.android.com/studio/write/java8-support

```<code>android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  // For Kotlin projects
  kotlinOptions {
    jvmTarget = "1.8"
  }
}
</code>```

Body:
Setting sourceCompatibility = JavaVersion.VERSION_1_8 enables desugaring, but it is currently unable to desugar all the Java 8 features that the Kotlin compiler uses.

Fix - Setting kotlinOptions.jvmTarget to JavaVersion.VERSION_1_8 in the app module Gradle would fix the issue.

Use Java 8 language features:
  https://developer.android.com/studio/write/java8-support

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
  // For Kotlin projects
  kotlinOptions {
    jvmTarget = "1.8"
  }
}


问:
Ignite create user with full privileges(Jdbc thin client)
I am stuck on creating user with full privileges.

I have created a user with name shubh. but dont know how to grant all privileges.

And want to drop the default user (user = ignite , password = ignite) privileges.

Please suggest.

答:
So guys from the above reply's I came to the conclusion .

Just change the password for default user .