问:
How add a new fonts on the Webview in Android?
How can I add new fonts on webview to support others languages.
I use wbeview.loadUrl(string); I wnat tis web view support the new font how to do that??</p>

答: You can try to add the .ttf of the fonts in the directory assets/, this will give the activity the possibility to use those fonts.</p>


来源: stackexchange

问:
How to archive hive tables?
Is there a way to check hive external tables which are created 90 days before and drop those tables along with underlying hdfs data.  Can this be achieved in unix script?</p>

答:
See, if the hive tables path is /path/your_hive_table_path/ as below:

```<code>hadoop --cluster your-hadoop-cluster fs -ls /path/your_hive_table_path/

drwxrwxrwx+  - h_mifi supergroup          0 2019-01-24 10:33 /path/your_hive_table_path//mifidw_car_insurance_expire_month_data
drwxrwxrwx+  - h_mifi supergroup          0 2019-01-24 10:39 /path/your_hive_table_path//mifidw_car_owner
drwxr-xr-x+  - h_mifi supergroup          0 2019-05-30 03:01 /path/your_hive_table_path//push_credit_card_mine_result_new
drwxr-xr-x+  - h_mifi supergroup          0 2019-05-30 03:41 /path/your_hive_table_path//push_live_payment_bill_mine_result_new
</code>```

We can get the table file lastest updated date as below:

```<code>hadoop --cluster your-hadoop-cluster fs -ls /path/your_hive_table_path/ | awk -F'[ ]+' '{print $6}'
2019-01-24
2019-01-24
2019-05-30
2019-05-30
</code>```

We need a loop to check every table whether is over 90 days and to execute remove and drop operations. The complete shell script is below, I have tested, it worked well, hope it would help for you.

```<code>hadoop --cluster your-hadoop-cluster fs -ls /path/your_hive_table_path/ | grep '/path/your_hive_table_path/' | while read line
do
   #Get the update date of hive table
   date_str=`echo $line | awk -F'[ ]+' '{print $6}'`
   #get the path of hive table
   table_path=`echo $line | awk -F'[ ]+' '{print $8}'`
   #Get the table name of hive table
   table_name=`echo $table_path | awk -F'/' '{print $7}' `

   today_date_stamp=`date +%s`
   table_date_stamp=`date -d $date_str +%s`
   stamp_diff=`expr $today_date_stamp - $table_date_stamp`

   #Get the diff days from now
   days_diff=`expr $stamp_diff / 86400`

   #if diff days is greater than 90, rm and drop.
   if [ $days_diff -gt 90 ];then
      #remove the hdfs file
      hadoop --cluster your-hadoop-cluster fs -rm $table_path
      #drop the hive table
      hive -e"drop table $table_name"
   fi
done
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to archive hive tables?

Body:
See, if the hive tables path is /path/your_hive_table_path/ as below:

hadoop --cluster your-hadoop-cluster fs -ls /path/your_hive_table_path/

drwxrwxrwx+  - h_mifi supergroup          0 2019-01-24 10:33 /path/your_hive_table_path//mifidw_car_insurance_expire_month_data
drwxrwxrwx+  - h_mifi supergroup          0 2019-01-24 10:39 /path/your_hive_table_path//mifidw_car_owner
drwxr-xr-x+  - h_mifi supergroup          0 2019-05-30 03:01 /path/your_hive_table_path//push_credit_card_mine_result_new
drwxr-xr-x+  - h_mifi supergroup          0 2019-05-30 03:41 /path/your_hive_table_path//push_live_payment_bill_mine_result_new

We can get the table file lastest updated date as below:

hadoop --cluster your-hadoop-cluster fs -ls /path/your_hive_table_path/ | awk -F'[ ]+' '{print $6}'
2019-01-24
2019-01-24
2019-05-30
2019-05-30

We need a loop to check every table whether is over 90 days and to execute remove and drop operations. The complete shell script is below, I have tested, it worked well, hope it would help for you.

hadoop --cluster your-hadoop-cluster fs -ls /path/your_hive_table_path/ | grep '/path/your_hive_table_path/' | while read line
do
   #Get the update date of hive table
   date_str=`echo $line | awk -F'[ ]+' '{print $6}'`
   #get the path of hive table
   table_path=`echo $line | awk -F'[ ]+' '{print $8}'`
   #Get the table name of hive table
   table_name=`echo $table_path | awk -F'/' '{print $7}' `

   today_date_stamp=`date +%s`
   table_date_stamp=`date -d $date_str +%s`
   stamp_diff=`expr $today_date_stamp - $table_date_stamp`

   #Get the diff days from now
   days_diff=`expr $stamp_diff / 86400`

   #if diff days is greater than 90, rm and drop.
   if [ $days_diff -gt 90 ];then
      #remove the hdfs file
      hadoop --cluster your-hadoop-cluster fs -rm $table_path
      #drop the hive table
      hive -e"drop table $table_name"
   fi
done


问:
handle errors with try on fable
This code works correctly

require(fable)
it <-  tsibbledata::global_economy %>%
    filter(Country == "Italy")
fm0 <-  model(.data = it,
    ARIMA(log(GDP) ~ Population),
    ETS(log(GDP)))
```

<p>Next one is not expected to  work </p>

<pre class="lang-r prettyprint-override"><code>fm1 <-  model(.data = it,
    ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1)),
    ETS(log(GDP)))
</code>```

Clearly it does not work because of  ARIMA model. ETS works fine

I could do:

fm2 <-  try(
    model(.data = it,
    ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1)),
    ETS(log(GDP))))
```

<p>But this will make both models to fail </p>

<p>I would like something like</p>

<pre class="lang-r prettyprint-override"><code>fm3 <-  try(
    model(.data = it,
    try(ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1))),
    ETS(log(GDP))))
</code>```

so that fm3 contains the correct results for ETS and an object of class 'try-error' for ARIMA

Possibly modifying fablelite:::estimate so  that it can handle errors could be a solution?

Any help would be very much appreciated

答:
Great suggestion, this is a feature that we've been thinking about for a little while now (https://github.com/tidyverts/fable/issues/74).

I've added a .safely argument to the model() argument which will return formatted warnings and return a null_model() rather than error (https://github.com/tidyverts/fablelite/commit/1c7dccd7e48211125cf566bcce9ba8c9fc4e47ce).

A null_model() is a model without estimation, and all model methods (forecast(), accuracy(), etc.) will give appropriately structured NA values.

I've set .safely=TRUE as default, so the above code now gives:

library(fable)
library(tidyverse)
it <-  tsibbledata::global_economy %>%
  filter(Country == "Italy")
fm1 <-  model(.data = it,
              ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1)),
              ETS(log(GDP)))
#> Warning: 1 error encountered for ARIMA(log(GDP) ~ Population + pdq(3, 1, 7) + PDQ(5, 1, 1))
#> [1] There are no ARIMA models to choose from after imposing the `order_constraint`, please consider allowing more models.
fm1
#> # A mable: 1 x 3
#> # Key:     Country [1]
#>   Country `ARIMA(log(GDP) ~ Population + pdq(3, 1, 7) + PD… `ETS(log(GDP))`
#>   <fct>   <model>                                           <model>
#> 1 Italy   <NULL model>                                      <ETS(M,Ad,N)>
```

Created on 2019-05-30 by the reprex package (v0.2.1)

Title: handle errors with try on fable

Body:
This code works correctly

require(fable)
it <-  tsibbledata::global_economy %>%
    filter(Country == "Italy")
fm0 <-  model(.data = it,
    ARIMA(log(GDP) ~ Population),
    ETS(log(GDP)))

Next one is not expected to  work

fm1 <-  model(.data = it,
    ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1)),
    ETS(log(GDP)))

Clearly it does not work because of  ARIMA model. ETS works fine

I could do:

fm2 <-  try(
    model(.data = it,
    ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1)),
    ETS(log(GDP))))

But this will make both models to fail

I would like something like

fm3 <-  try(
    model(.data = it,
    try(ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1))),
    ETS(log(GDP))))

so that fm3 contains the correct results for ETS and an object of class 'try-error' for ARIMA

Possibly modifying fablelite:::estimate so  that it can handle errors could be a solution?

Any help would be very much appreciated

Body:
Great suggestion, this is a feature that we've been thinking about for a little while now (https://github.com/tidyverts/fable/issues/74).

I've added a .safely argument to the model() argument which will return formatted warnings and return a null_model() rather than error (https://github.com/tidyverts/fablelite/commit/1c7dccd7e48211125cf566bcce9ba8c9fc4e47ce).

A null_model() is a model without estimation, and all model methods (forecast(), accuracy(), etc.) will give appropriately structured NA values.

I've set .safely=TRUE as default, so the above code now gives:

library(fable)
library(tidyverse)
it <-  tsibbledata::global_economy %>%
  filter(Country == "Italy")
fm1 <-  model(.data = it,
              ARIMA(log(GDP) ~ Population + pdq(3,1,7) +PDQ(5,1,1)),
              ETS(log(GDP)))
#> Warning: 1 error encountered for ARIMA(log(GDP) ~ Population + pdq(3, 1, 7) + PDQ(5, 1, 1))
#> [1] There are no ARIMA models to choose from after imposing the `order_constraint`, please consider allowing more models.
fm1
#> # A mable: 1 x 3
#> # Key:     Country [1]
#>   Country `ARIMA(log(GDP) ~ Population + pdq(3, 1, 7) + PD… `ETS(log(GDP))`
#>   <fct>   <model>                                           <model>
#> 1 Italy   <NULL model>                                      <ETS(M,Ad,N)>

Created on 2019-05-30 by the reprex package (v0.2.1)


问:
The argparse code snippet only print part log
I have a code for testing argparse module function:

```<code>import argparse

parser = argparse.ArgumentParser()
parser.description='give me two number, I will return the product'
parser.add_argument("-a","--ParA", help="I am A",type=int)
parser.add_argument("-b","--ParB", help="I am B",type=int)
args = parser.parse_args()
if args.ParA:
    print("A is: ",args.ParA)
if args.ParB:
    print("B is:",args.ParB)
if args.ParA and args.ParB:
    print("the product is: ",args.ParA*args.ParB)

print('over.')
</code>```

but when I run it in my PyCharm, there only print the over.

答:
PyCharm will not pass arguments to scripts when you run them. And you have defined both your arguments to be optional.

You need to edit your run configuration to pass the arguments - if you want to run from pycharm.

Go to test1 (Top right corner) -> Edit Configurations -> Parameters (text box)

And add your arguments there.

```<code>-a 3 -b 2
</code>```

Then save the config, and run it.

Body:
I have a code for testing argparse module function:

import argparse

parser = argparse.ArgumentParser()
parser.description='give me two number, I will return the product'
parser.add_argument("-a","--ParA", help="I am A",type=int)
parser.add_argument("-b","--ParB", help="I am B",type=int)
args = parser.parse_args()
if args.ParA:
    print("A is: ",args.ParA)
if args.ParB:
    print("B is:",args.ParB)
if args.ParA and args.ParB:
    print("the product is: ",args.ParA*args.ParB)

print('over.')

but when I run it in my PyCharm, there only print the over.

Body:
PyCharm will not pass arguments to scripts when you run them. And you have defined both your arguments to be optional.

You need to edit your run configuration to pass the arguments - if you want to run from pycharm.

Go to test1 (Top right corner) -> Edit Configurations -> Parameters (text box)

And add your arguments there.

-a 3 -b 2

Then save the config, and run it.


问:
My App connected to firebase don't setup the recyclerView when you initialize the activity
I have really strange problem with my app, it's a TabLayout with 3 fragments the 1st and the 3rd has a RecyclerView which is filled with the Firebase Database, but you can't see the information until you click on the 1st and 3rd tab, I don't know if I'm explaining well, when you start the activity and you are in the 1st Fragment nothing is showed, you can go to the 2nd and then 1st and still nothing showed but once you go to the 3rd and then go back to the 1st the 1st and 3rd recyclerview are filled, which can be the problem, here is my code:

These are my 2 fragments:

```<code>public class FragGastos extends Fragment implements View.OnClickListener, AdapterDinero.OnItemClickListener{

private static final String TAG = "SDSADSDS";
private Button btAdd;
private FirebaseAuth auth = FirebaseAuth.getInstance();
private GastosService gastosService;
private ArrayList<Dinero> dineros;
private RecyclerView recyclerView;
private AdapterDinero adapter;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_gastos_layout, container, false);
    FirebaseUser user = auth.getCurrentUser();
    gastosService = GastosService.getInstance(user.getDisplayName());
    dineros = gastosService.getDineros();
    adapter = new AdapterDinero(getContext());
    adapter.setOnItemClickListener(this);
    recyclerView = view.findViewById(R.id.rv_Gastos);
    adapter.setDineros(dineros);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
    btAdd = view.findViewById(R.id.bt_add_gasto);
    btAdd.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View v) {
    Intent intent = new Intent(getActivity(), AddActivity.class);
    startActivity(intent);
}

@Override
public void onItemClick(View view, int position) {
    Intent intent = new Intent(getActivity(), DetalleActivity.class);
    Log.w(TAG, "HA PETADO AQUI");
    intent.putExtra("objDinero", dineros.get(position));
    startActivity(intent);
}
}

public class FragIngresos extends Fragment implements View.OnClickListener {

private Button btAdd;
private FirebaseAuth auth;
private IngresosService ingresosService;
private ArrayList<Dinero> dineros;
private RecyclerView recyclerView;
private AdapterDinero adapter;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_ingresos_layout, container, false);
    auth = FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    ingresosService = IngresosService.getInstance(user.getDisplayName());
    dineros = ingresosService.getDineros();
    adapter = new AdapterDinero(getContext());
    recyclerView = view.findViewById(R.id.rvIngresos);
    recyclerView.setAdapter(adapter);
    adapter.setDineros(dineros);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
    btAdd = view.findViewById(R.id.bt_add_gasto);
    btAdd.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View v) {
    Intent intent = new Intent(getActivity(), AddActivity.class);
    startActivity(intent);
}
}
</code>```

Here is the adapter which is the same for both fragments:

```<code>public class AdapterDinero extends RecyclerView.Adapter<AdapterDinero.DineroViewHolder> {

public interface OnItemClickListener
{
     void onItemClick(View view, int position);
}

private ArrayList<Dinero> dineros;
private Context context;
private OnItemClickListener onItemClickListener;

public void setOnItemClickListener(OnItemClickListener onItemClickListener)
{
    this.onItemClickListener = onItemClickListener;
}

public AdapterDinero(Context context) {
    this.context = context;
}
public void setDineros(ArrayList<Dinero> dineros) {
    this.dineros = dineros;
    notifyDataSetChanged();
}

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

@Override
public void onBindViewHolder(@NonNull final DineroViewHolder dineroViewHolder, final int i) {
    Dinero dinero = dineros.get(i);
    dineroViewHolder.AsignarDatos(dinero);
}

@Override
public int getItemCount() {
    if(dineros != null){
        return dineros.size();
    }
    else{
        return 0;
    }
}

public class DineroViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private TextView tvTitulo, tvDinero;
    public DineroViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitulo = itemView.findViewById(R.id.tv_itemDinero_titulo);
        tvDinero = itemView.findViewById(R.id.tv_itemDinero_Precio);
        itemView.setOnClickListener(this);
    }

    public void AsignarDatos(Dinero dinero){
        String total = String.valueOf(dinero.getTotal())+ "€";
        tvDinero.setText(total);
        tvTitulo.setText(dinero.getNombre());
    }

    @Override
    public void onClick(View v) {
        if ( onItemClickListener != null ){
            onItemClickListener.onItemClick(this.itemView, this.getAdapterPosition() );
        }
    }
}
</code>```

}

And finally I have 2 classes to fill the fragments:

```<code>public class GastosService {

private ArrayList<Dinero> dineros;
public static GastosService gastosService;

public static GastosService getInstance(String username){
    if(gastosService == null){
        gastosService = new GastosService(username);
    }
    return  gastosService;
}

private GastosService(String userName){
    FirebaseRead firebaseOperation = new FirebaseRead();
    firebaseOperation.getGastos(userName, new FirebaseRead.GastosLoaded() {
        @Override
        public void gastosIsLoaded(ArrayList<Dinero> gastos) {
            dineros = gastos;
        }
    });
}

public ArrayList<Dinero> getDineros() {
    return dineros;
}

public Dinero getDinero(int i){
    return dineros.get(i);
}
}

public class IngresosService {

private ArrayList<Dinero> dineros;
public static IngresosService ingresosService;

public static IngresosService getInstance(String username){
    if(ingresosService == null){
        ingresosService = new IngresosService(username);
    }
    return  ingresosService;
}

private IngresosService(String userName){
    FirebaseRead firebaseOperation = new FirebaseRead();
    firebaseOperation.getIngresos(userName, new FirebaseRead.IngresosIsLoaded() {
        @Override
        public void ingresosIsLoaded(ArrayList<Dinero> ingresos) {
            dineros = ingresos;
        }
    });
}

public ArrayList<Dinero> getDineros() {
    return dineros;
}

public Dinero getDinero(int i){
    return dineros.get(i);
}
}
</code>```

And here is the function of a class which gets the reading of the database:

```<code>public class FirebaseRead {
private static final String TAG1 = "Operacion de lectura";
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private ArrayList<Dinero> beneficio;
private ArrayList<Dinero> gastos;
float total;
public interface GastosLoaded{
    void gastosIsLoaded(ArrayList<Dinero> gastos);
}
public interface IngresosIsLoaded{
    void ingresosIsLoaded(ArrayList<Dinero> ingresos);

  public void getGastos(String user, GastosLoaded gLoaded ){
    gastos = new ArrayList<>();
    final GastosLoaded gastosLoaded = gLoaded;
    DatabaseReference ref = database.getReference().child("Users").child(user).child("Gastos");

    ref.addValueEventListener(new ValueEventListener() {
        @Override

        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            gastos.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String nombreAux = ds.child("nombre").getValue().toString();
                String descAux = ds.child("descripcion").getValue().toString();
                String fecha = ds.child("fecha").getValue().toString();
                int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
                Dinero dinero = new Dinero(nombreAux, descAux,precioAux, fecha);
                dinero.setId(ds.getKey());
                gastos.add(dinero);
            }
            gastos = ordenaDinero(gastos);
            gastosLoaded.gastosIsLoaded(gastos);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

public void getIngresos(String user, IngresosIsLoaded iLoaded){
    beneficio = new ArrayList<>();
    final IngresosIsLoaded ingresosIsLoaded = iLoaded;
    DatabaseReference ref = database.getReference().child("Users").child(user).child("Ingresos");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            beneficio.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String nombreAux = ds.child("nombre").getValue().toString();
                String descAux = ds.child("descripcion").getValue().toString();
                String fecha = ds.child("fecha").getValue().toString();
                int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
                Dinero dinero = new Dinero(nombreAux, descAux,precioAux, fecha);
                dinero.setId(ds.getKey());
                beneficio.add(dinero);
            }
            beneficio = ordenaDinero(beneficio);
            ingresosIsLoaded.ingresosIsLoaded(beneficio);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

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

I know it's a lot of code but I have trying to find a solution a lot of time, and nothing wokrs, please help!

答:
```<code>dineros = ingresosService.getDineros();
adapter = new AdapterDinero(getContext());
recyclerView = view.findViewById(R.id.rvIngresos);
recyclerView.setAdapter(adapter); // after
adapter.setDineros(dineros); // 1st
</code>```

Did you notifyDataChange() in your AdapterDinero?

Maybe we can see if this work first:

call adapter.setDineros(dineros); first

and then recyclerView.setAdapter(adapter);

remember to notifyDataChange() every time you update your content.

Update:

The RecyclerView has no content usually because its dataSet is empty. I suggest put some log to see what happened.

Since you uploaded your adapter, I found this

```<code>public void setDineros(ArrayList<Dinero> dineros) {
  this.dineros = dineros; << not good.
  notifyDataSetChanged();
}
</code>```

There's a little misunderstanding about notifyDataSetChanged(), It means the ORIGINAL dataset(arrayList) has been changed.

Your adapter only remembers the reference to the first node of the original ArrayList, you passed a new DataSet in, but the original arrayList did not know anything.

The correct way is arrayList.add()/remove()/clear()/addAll() and then notify(), that's how we modify the ORIGINAL dataSet.

for example:

```<code>public void setDineros(ArrayList<Dinero> dineros) {
    this.dineros.clear()
    this.dineros.addAll(dineros)
    notifyDataSetChanged();
}
</code>```

You should not replace whole arrayList because that new arrayList is not the original arrayList.

Body:
I have really strange problem with my app, it's a TabLayout with 3 fragments the 1st and the 3rd has a RecyclerView which is filled with the Firebase Database, but you can't see the information until you click on the 1st and 3rd tab, I don't know if I'm explaining well, when you start the activity and you are in the 1st Fragment nothing is showed, you can go to the 2nd and then 1st and still nothing showed but once you go to the 3rd and then go back to the 1st the 1st and 3rd recyclerview are filled, which can be the problem, here is my code:

These are my 2 fragments:

public class FragGastos extends Fragment implements View.OnClickListener, AdapterDinero.OnItemClickListener{

private static final String TAG = "SDSADSDS";
private Button btAdd;
private FirebaseAuth auth = FirebaseAuth.getInstance();
private GastosService gastosService;
private ArrayList<Dinero> dineros;
private RecyclerView recyclerView;
private AdapterDinero adapter;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_gastos_layout, container, false);
    FirebaseUser user = auth.getCurrentUser();
    gastosService = GastosService.getInstance(user.getDisplayName());
    dineros = gastosService.getDineros();
    adapter = new AdapterDinero(getContext());
    adapter.setOnItemClickListener(this);
    recyclerView = view.findViewById(R.id.rv_Gastos);
    adapter.setDineros(dineros);
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
    btAdd = view.findViewById(R.id.bt_add_gasto);
    btAdd.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View v) {
    Intent intent = new Intent(getActivity(), AddActivity.class);
    startActivity(intent);
}

@Override
public void onItemClick(View view, int position) {
    Intent intent = new Intent(getActivity(), DetalleActivity.class);
    Log.w(TAG, "HA PETADO AQUI");
    intent.putExtra("objDinero", dineros.get(position));
    startActivity(intent);
}
}

public class FragIngresos extends Fragment implements View.OnClickListener {

private Button btAdd;
private FirebaseAuth auth;
private IngresosService ingresosService;
private ArrayList<Dinero> dineros;
private RecyclerView recyclerView;
private AdapterDinero adapter;

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_ingresos_layout, container, false);
    auth = FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    ingresosService = IngresosService.getInstance(user.getDisplayName());
    dineros = ingresosService.getDineros();
    adapter = new AdapterDinero(getContext());
    recyclerView = view.findViewById(R.id.rvIngresos);
    recyclerView.setAdapter(adapter);
    adapter.setDineros(dineros);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
    btAdd = view.findViewById(R.id.bt_add_gasto);
    btAdd.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View v) {
    Intent intent = new Intent(getActivity(), AddActivity.class);
    startActivity(intent);
}
}

Here is the adapter which is the same for both fragments:

public class AdapterDinero extends RecyclerView.Adapter<AdapterDinero.DineroViewHolder> {

public interface OnItemClickListener
{
     void onItemClick(View view, int position);
}

private ArrayList<Dinero> dineros;
private Context context;
private OnItemClickListener onItemClickListener;

public void setOnItemClickListener(OnItemClickListener onItemClickListener)
{
    this.onItemClickListener = onItemClickListener;
}

public AdapterDinero(Context context) {
    this.context = context;
}
public void setDineros(ArrayList<Dinero> dineros) {
    this.dineros = dineros;
    notifyDataSetChanged();
}

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

@Override
public void onBindViewHolder(@NonNull final DineroViewHolder dineroViewHolder, final int i) {
    Dinero dinero = dineros.get(i);
    dineroViewHolder.AsignarDatos(dinero);
}

@Override
public int getItemCount() {
    if(dineros != null){
        return dineros.size();
    }
    else{
        return 0;
    }
}

public class DineroViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private TextView tvTitulo, tvDinero;
    public DineroViewHolder(@NonNull View itemView) {
        super(itemView);
        tvTitulo = itemView.findViewById(R.id.tv_itemDinero_titulo);
        tvDinero = itemView.findViewById(R.id.tv_itemDinero_Precio);
        itemView.setOnClickListener(this);
    }

    public void AsignarDatos(Dinero dinero){
        String total = String.valueOf(dinero.getTotal())+ "€";
        tvDinero.setText(total);
        tvTitulo.setText(dinero.getNombre());
    }

    @Override
    public void onClick(View v) {
        if ( onItemClickListener != null ){
            onItemClickListener.onItemClick(this.itemView, this.getAdapterPosition() );
        }
    }
}

}

And finally I have 2 classes to fill the fragments:

public class GastosService {

private ArrayList<Dinero> dineros;
public static GastosService gastosService;

public static GastosService getInstance(String username){
    if(gastosService == null){
        gastosService = new GastosService(username);
    }
    return  gastosService;
}

private GastosService(String userName){
    FirebaseRead firebaseOperation = new FirebaseRead();
    firebaseOperation.getGastos(userName, new FirebaseRead.GastosLoaded() {
        @Override
        public void gastosIsLoaded(ArrayList<Dinero> gastos) {
            dineros = gastos;
        }
    });
}

public ArrayList<Dinero> getDineros() {
    return dineros;
}

public Dinero getDinero(int i){
    return dineros.get(i);
}
}

public class IngresosService {

private ArrayList<Dinero> dineros;
public static IngresosService ingresosService;

public static IngresosService getInstance(String username){
    if(ingresosService == null){
        ingresosService = new IngresosService(username);
    }
    return  ingresosService;
}

private IngresosService(String userName){
    FirebaseRead firebaseOperation = new FirebaseRead();
    firebaseOperation.getIngresos(userName, new FirebaseRead.IngresosIsLoaded() {
        @Override
        public void ingresosIsLoaded(ArrayList<Dinero> ingresos) {
            dineros = ingresos;
        }
    });
}

public ArrayList<Dinero> getDineros() {
    return dineros;
}

public Dinero getDinero(int i){
    return dineros.get(i);
}
}

And here is the function of a class which gets the reading of the database:

public class FirebaseRead {
private static final String TAG1 = "Operacion de lectura";
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private ArrayList<Dinero> beneficio;
private ArrayList<Dinero> gastos;
float total;
public interface GastosLoaded{
    void gastosIsLoaded(ArrayList<Dinero> gastos);
}
public interface IngresosIsLoaded{
    void ingresosIsLoaded(ArrayList<Dinero> ingresos);

  public void getGastos(String user, GastosLoaded gLoaded ){
    gastos = new ArrayList<>();
    final GastosLoaded gastosLoaded = gLoaded;
    DatabaseReference ref = database.getReference().child("Users").child(user).child("Gastos");

    ref.addValueEventListener(new ValueEventListener() {
        @Override

        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            gastos.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String nombreAux = ds.child("nombre").getValue().toString();
                String descAux = ds.child("descripcion").getValue().toString();
                String fecha = ds.child("fecha").getValue().toString();
                int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
                Dinero dinero = new Dinero(nombreAux, descAux,precioAux, fecha);
                dinero.setId(ds.getKey());
                gastos.add(dinero);
            }
            gastos = ordenaDinero(gastos);
            gastosLoaded.gastosIsLoaded(gastos);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

public void getIngresos(String user, IngresosIsLoaded iLoaded){
    beneficio = new ArrayList<>();
    final IngresosIsLoaded ingresosIsLoaded = iLoaded;
    DatabaseReference ref = database.getReference().child("Users").child(user).child("Ingresos");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            beneficio.clear();
            for(DataSnapshot ds : dataSnapshot.getChildren()){
                String nombreAux = ds.child("nombre").getValue().toString();
                String descAux = ds.child("descripcion").getValue().toString();
                String fecha = ds.child("fecha").getValue().toString();
                int precioAux = Integer.parseInt(ds.child("total").getValue().toString());
                Dinero dinero = new Dinero(nombreAux, descAux,precioAux, fecha);
                dinero.setId(ds.getKey());
                beneficio.add(dinero);
            }
            beneficio = ordenaDinero(beneficio);
            ingresosIsLoaded.ingresosIsLoaded(beneficio);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

I know it's a lot of code but I have trying to find a solution a lot of time, and nothing wokrs, please help!

Body:
dineros = ingresosService.getDineros();
adapter = new AdapterDinero(getContext());
recyclerView = view.findViewById(R.id.rvIngresos);
recyclerView.setAdapter(adapter); // after
adapter.setDineros(dineros); // 1st

Did you notifyDataChange() in your AdapterDinero?

Maybe we can see if this work first:

call adapter.setDineros(dineros); first

and then recyclerView.setAdapter(adapter);

remember to notifyDataChange() every time you update your content.

Update:

The RecyclerView has no content usually because its dataSet is empty. I suggest put some log to see what happened.

Since you uploaded your adapter, I found this

public void setDineros(ArrayList<Dinero> dineros) {
  this.dineros = dineros; << not good.
  notifyDataSetChanged();
}

There's a little misunderstanding about notifyDataSetChanged(), It means the ORIGINAL dataset(arrayList) has been changed.

Your adapter only remembers the reference to the first node of the original ArrayList, you passed a new DataSet in, but the original arrayList did not know anything.

The correct way is arrayList.add()/remove()/clear()/addAll() and then notify(), that's how we modify the ORIGINAL dataSet.

for example:

public void setDineros(ArrayList<Dinero> dineros) {
    this.dineros.clear()
    this.dineros.addAll(dineros)
    notifyDataSetChanged();
}

You should not replace whole arrayList because that new arrayList is not the original arrayList.


问:
How to copy the contents of a set to a two dimensional array in Java?
The idea is to have a two dimensional array NxN where all the elements (numbers from 0 to N*N) are in random positions. To generate the random numbers I used:

```<code> // Creates a set so we avoid repetition of generated numbers
        Set<Integer> generatedNumbers = new LinkedHashSet<Integer>();
        while (generatedNumbers.size() < numberOfElements){
            Integer next = rng.nextInt(numberOfElements) ;
            generatedNumbers.add(next);
        }
</code>```

Now I need to copy the elements to a two dimensional array. Basically, something like this:

```<code>   for (Integer number: generatedNumbers){
            // Here I'd like to have:
           // 1st iteration: board[0][0] = number
          // 2nd iteration: board[0][1] = number
          // ...
          // last iteration: board[3][3] = number
        }
</code>```

where:

```<code>board = new int[boardSize][boardSize];
</code>```

with boardSize = 4 for this particular case.
Btw, if there's a better way to achieve the same but using a different method, I'd be happy to read it.

答:
Instead of iterating the set on the outside of the loop, consider doing it in reverse. Something along the lines of</p>

```<code>Iterator iter = generatedNumbers.iterator()
for (...) {
     for (...) {
          if (iter.hasNext()) arr[i][j] = iter.next()
          else ...
     }
}
</code>```

Body:
The idea is to have a two dimensional array NxN where all the elements (numbers from 0 to N*N) are in random positions. To generate the random numbers I used:

 // Creates a set so we avoid repetition of generated numbers
        Set<Integer> generatedNumbers = new LinkedHashSet<Integer>();
        while (generatedNumbers.size() < numberOfElements){
            Integer next = rng.nextInt(numberOfElements) ;
            generatedNumbers.add(next);
        }

Now I need to copy the elements to a two dimensional array. Basically, something like this:

   for (Integer number: generatedNumbers){
            // Here I'd like to have:
           // 1st iteration: board[0][0] = number
          // 2nd iteration: board[0][1] = number
          // ...
          // last iteration: board[3][3] = number
        }

where:

board = new int[boardSize][boardSize];

with boardSize = 4 for this particular case.
Btw, if there's a better way to achieve the same but using a different method, I'd be happy to read it.

Body:
Instead of iterating the set on the outside of the loop, consider doing it in reverse. Something along the lines of

Iterator iter = generatedNumbers.iterator()
for (...) {
     for (...) {
          if (iter.hasNext()) arr[i][j] = iter.next()
          else ...
     }
}


问:
Continuously run bash script in Azure Container
I need to run a bash script continuously for indefinite time inside a docker container in Azure via Azure Container Instance service (ACI). My bash script has a while loop that keeps it running and Azure container has OnFailure Property to restart container if fails.

I see that after running Container for about 2 days, Container status is Running. However, the bash script that was running in foreground and sending logs in azure container console seems to be died and no longer sending logs to console. I also see it's not doing what it supposed to do.

How can I reliably keep this bash script running for indefinite time in Azure container?

The bash script which has internal while loop runs as below:

```<code>Commands
bash
my-while-loop-script.sh
</code>```

答:
To solve this issue, I replaced while loop inside my-while-loop-script.sh with a crond to execute a python application as a cron job. below is the line that executes a cron inside my-while-loop-script.sh. this line will execute my-cron.cron contents show below:

```<code>./busybox crond -f
</code>```

To achieve that, I used busybox 1.30.1 tools. To install busybox in your docker:

```<code>ADD busybox-1.30.1/ /busybox
WORKDIR /busybox
RUN make defconfig
RUN make
</code>```

And, you also need to add cron settings to crontabs dir.

```<code>RUN mkdir -p /var/spool/cron/crontabs/
# Copy cron settings
ADD my-cron.cron /var/spool/cron/crontabs/root
</code>```

Sample my-cron.cron looks like just a normal cron file:

```<code>* * * * * python my-app.py
</code>```

Body:
I need to run a bash script continuously for indefinite time inside a docker container in Azure via Azure Container Instance service (ACI). My bash script has a while loop that keeps it running and Azure container has OnFailure Property to restart container if fails.

I see that after running Container for about 2 days, Container status is Running. However, the bash script that was running in foreground and sending logs in azure container console seems to be died and no longer sending logs to console. I also see it's not doing what it supposed to do.

How can I reliably keep this bash script running for indefinite time in Azure container?

The bash script which has internal while loop runs as below:

Commands
bash
my-while-loop-script.sh

Body:
To solve this issue, I replaced while loop inside my-while-loop-script.sh with a crond to execute a python application as a cron job. below is the line that executes a cron inside my-while-loop-script.sh. this line will execute my-cron.cron contents show below:

./busybox crond -f

To achieve that, I used busybox 1.30.1 tools. To install busybox in your docker:

ADD busybox-1.30.1/ /busybox
WORKDIR /busybox
RUN make defconfig
RUN make

And, you also need to add cron settings to crontabs dir.

RUN mkdir -p /var/spool/cron/crontabs/
# Copy cron settings
ADD my-cron.cron /var/spool/cron/crontabs/root

Sample my-cron.cron looks like just a normal cron file:

* * * * * python my-app.py


问:
How to validate a WPF application Azure Token in a Web API in Server machine
I have a WPF application, it will authenticate with Azure AD and return a Token. While calling the methods Web API, we are passing this token to server machine. In server we need to validate the token is valid or not. Can you please help me for the validation code in server machine </p>

```<code>                string aadInstance = service.SelectSingleNode("AADInstance").InnerText;
                string tenant = service.SelectSingleNode("Tenant").InnerText;
                string clientId = service.SelectSingleNode("ClientId").InnerText;
                string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
                authContext = new AuthenticationContext(authority, new FileCache());
                Uri redirectUri = new Uri(service.SelectSingleNode("RedirectUri").InnerText);
                string resourceId = service.SelectSingleNode("ResourceId").InnerText;
                AuthenticationResult result = null;
             try
            {
                result = await authContext.AcquireTokenSilentAsync(resourceId, clientId);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    result = await authContext.AcquireTokenAsync(resourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
                }
            }
            tocken = result.AccessToken;
</code>```

答:
Its seems you are trying to validate your token from your back end code.

Once you get your token your can use System.IdentityModel.Tokens.Jwt nuget package to validate your token. To do that

Go nuget package manager and  browse for System.IdentityModel.Tokens.Jwt add this reference to your project. See the screen shot below:

Add Following Reference:

using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
```

<p>Once you set the package set the following code:</p>

<p><strong>Token Validation Method:</strong></p>

<pre class="lang-cs prettyprint-override"><code>private  bool ValidateToken(string yourToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            IPrincipal principal = tokenHandler.ValidateToken(yourToken, validationParameters, out validatedToken);
            return true;
        }
</code>```

Your Token Validation Param:

static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

private static TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters()
            {
                ValidateLifetime = false, // Because there is no expiration in the generated token
                ValidateAudience = false, // Because there is no audiance in the generated token
                ValidateIssuer = false,   // Because there is no issuer in the generated token
                ValidIssuer = "Sample",
                ValidAudience = "Sample",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) // The same key as the one that generate the token
            };
        }
```

Note: hook up all the reference and test. for more details you could refer here. If you sill have any query feel free to share.
  Thanks and happy coding!

Body:
I have a WPF application, it will authenticate with Azure AD and return a Token. While calling the methods Web API, we are passing this token to server machine. In server we need to validate the token is valid or not. Can you please help me for the validation code in server machine

                string aadInstance = service.SelectSingleNode("AADInstance").InnerText;
                string tenant = service.SelectSingleNode("Tenant").InnerText;
                string clientId = service.SelectSingleNode("ClientId").InnerText;
                string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
                authContext = new AuthenticationContext(authority, new FileCache());
                Uri redirectUri = new Uri(service.SelectSingleNode("RedirectUri").InnerText);
                string resourceId = service.SelectSingleNode("ResourceId").InnerText;
                AuthenticationResult result = null;
             try
            {
                result = await authContext.AcquireTokenSilentAsync(resourceId, clientId);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    result = await authContext.AcquireTokenAsync(resourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
                }
            }
            tocken = result.AccessToken;

Body:
Its seems you are trying to validate your token from your back end code.

Once you get your token your can use System.IdentityModel.Tokens.Jwt nuget package to validate your token. To do that

Go nuget package manager and  browse for System.IdentityModel.Tokens.Jwt add this reference to your project. See the screen shot below:

Add Following Reference:

using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

Once you set the package set the following code:

Token Validation Method:

private  bool ValidateToken(string yourToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            IPrincipal principal = tokenHandler.ValidateToken(yourToken, validationParameters, out validatedToken);
            return true;
        }

Your Token Validation Param:

static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

private static TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters()
            {
                ValidateLifetime = false, // Because there is no expiration in the generated token
                ValidateAudience = false, // Because there is no audiance in the generated token
                ValidateIssuer = false,   // Because there is no issuer in the generated token
                ValidIssuer = "Sample",
                ValidAudience = "Sample",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) // The same key as the one that generate the token
            };
        }

Note: hook up all the reference and test. for more details you could refer here. If you sill have any query feel free to share.
  Thanks and happy coding!


问:
Merging multiple data frames with lapply function and files RDS RData
Good evening, I want to replicate the function that appears in this blog https://www.r-bloggers.com/how-to-perform-merges-joins-on-two-or-more-data-frames-with-base-r-tidyverse-and-data-table/ Merging multiple data frames

```<code>flightsList <- readRDS(url(paste0(dataurl, "r006/nycflights13-list.rds")))
lapply(flightsList, function(x) c(toString(dim(x)), toString(names(x)))).
</code>```

I have tried in many ways but I could not merge tables of diferents dims.

```<code>atencionesList <- serialize(list("iatencion","iatencion_apo", "iatencion_dia", "iatencion_ins", "iatencion_med", "iatencion_ser",
                    "iatencion_smi", "padron_nominado"), NULL)

atencionesList <- readRDS(paste0("~/GitHub/salud2018/Lima2019/Anelima/atenciones1.RDS"))
lapply(atencionesList, function(x) c(toString(dim(x)), toString(names(x))))
</code>```

```<code>#****************************
atencionesList <- load(paste0("~/GitHub/salud2018/Lima2019/Anelima/atenciones.RData"))
lapply(atencionesList, function(x) c(toString(dim(x)), toString(names(x))))
#**********************************************

 multiFull <- merge(merge(merge(merge(merge(merge(merge(
+ atencionesList[[1L]],
+ atencionesList[[2L]], all = TRUE),
+ atencionesList[[3L]], all = TRUE),
+ atencionesList[[4L]], all = TRUE),
+ atencionesList[[5L]], all = TRUE),
+ atencionesList[[6L]], all = TRUE),
+ atencionesList[[7L]], all = TRUE),
+ atencionesList[[8L]], all = TRUE)
</code>```

Unlike the example of the blog with the data of flights to me I do not leave a single dataframe that relate one to several the table attentions with the others by dni, date and other variables that are in the table.

答:
I was able to make changes in the database,convert tibble in data.table, for example. As you can see I did the task to be able to merge multiple tibbles with the merge function, now the problem is lack of memory as you can see in the attached code.

```<code>setwd("~/GitHub/salud2018/Lima2019/Anelima")

iatencion <- read_delim("F:/data sis/iatencion.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
      iatencion_med <- read_delim("F:/data sis/iatencion_med.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_ins <- read_delim("F:/data sis/iatencion_ins.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_ser <- read_delim("F:/data sis/iatencion_ser.txt", "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_apo <- read_delim("F:/data sis/iatencion_apo.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_dia <- read_delim("F:/data sis/iatencion_dia.txt",  "|", col_names = TRUE,escape_double = TRUE, trim_ws = TRUE)
    iatencion_smi <- read_delim("F:/data sis/iatencion_smi.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    padron_nominado <- read_delim("F:/data sis/padron_nominado.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)

save(iatencion,iatencion_med, iatencion_ins, iatencion_ser,iatencion_apo, iatencion_dia,
     iatencion_smi, padron_nominado, file = "atenciones1.RData")

 load("~/GitHub/salud2018/Lima2019/Anelima/atenciones1.RData")

 setwd("~/GitHub/salud2018/Lima2019/Anelima")

        iatencion_med <- rename(iatencion_med, ate_idnumreg = amed_numregate)
        iatencion_ins <- rename(iatencion_ins, ate_idnumreg = ains_NumRegate)
        iatencion_ser <- rename(iatencion_ser, ate_idnumreg = ASER_NUMREGATE)
        iatencion_apo <- rename(iatencion_apo, ate_idnumreg = aapo_NUMREGATE)
        iatencion_dia <- rename(iatencion_dia, ate_idnumreg = adia_numregate)
        iatencion_smi <- rename(iatencion_smi, ate_idnumreg = asmi_numregate)

     iatencion <- as.data.table(iatencion); str(iatencion)
     iatencion_med <- as.data.table(iatencion_med);str(iatencion_med)
     iatencion_ins <- as.data.table(iatencion_ins);str(iatencion_ins)
     iatencion_ser <- as.data.table(iatencion_ser);str(iatencion_ser)

    iatencion_apo <- as.data.table(iatencion_apo);str(iatencion_apo )
    iatencion_dia <- as.data.table(iatencion_dia);str(iatencion_dia)
    iatencion_smi <- as.data.table(iatencion_smi);str(iatencion_smi)

    iatencion <- as.data.table(iatencion); str(iatencion)

Classes ‘data.table’ and 'data.frame':  1046739 obs. of  47 variables:
 $ dni_mod                 : chr  "82879909" "35766109" "37182709" "58953509" ...
 $ ate_disa                : chr  "350" "080" "035" "210" ...
 $ ate_ideess              : chr  "150101A109" "070103A101" "150125A304" "150118A101" ...
 $ ate_edad                : num  0 1 0 0 0 0 0 2 0 1 ...
 $ ate_idgrupoEtareo       : chr  "01" "01" "01" "01" ...
 $ ate_idsexo              : num  1 1 1 0 1 1 0 0 1 1 ...
 $ ate_codate              : num  2 3 1 3 1 1 1 1 1 1 ...
 $ ate_esgestante          : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ate_historiaclinica     : chr  "1078561" "201839089" "120542" "2577739" ...
 $ ate_fecatencion         : POSIXct, format: "2018-10-24 08:05:00" "2018-07-16 16:36:00" ...
 $ ate_horatencion         : 'hms' num  NA 16:36:00 11:30:00 11:50:00 ...
  ..- attr(*, "units")= chr "secs"
 $ ate_idEESSrefirio       : chr  "150135A101" NA NA NA ...
 $ ate_nrohojareferencia   : chr  "58246" NA NA NA ...
 $ ate_idServicio          : chr  "071" "062" "056" "062" ...
 $ ate_idlugar             : num  1 1 1 1 1 1 1 1 1 1 ...
 $ ate_codDestino          : num  2 2 1 1 2 1 2 1 2 2 ...
 $ ate_fecinghosp          : POSIXct, format: NA "2018-07-16" ...
 $ ate_fecaltahosp         : POSIXct, format: NA "2018-07-16" ...
 $ ate_ideesscontrarefiere : chr  NA NA NA NA ...
 $ ate_numhojacontrarefiere: chr  NA NA NA NA ...
 $ ate_idTipoPersonalSalud : num  1 1 1 1 6 1 6 10 6 13 ...
 $ ate_fecParto            : logi  NA NA NA NA NA NA ...
 $ ate_idubigeo            : chr  NA "150101" "150125" "150728" ...
 $ ate_periodo             : num  2018 2018 2018 2018 2018 ...
 $ ate_mes                 : chr  "11" "11" "11" "11" ...
 $ ate_tipoTraslado        : logi  NA NA NA NA NA NA ...
 $ ate_tipoTrasnporte      : logi  NA NA NA NA NA NA ...
 $ ate_UE                  : chr  "0149" "1318" "1684" "1138" ...
 $ ate_tipDig              : num  1 3 3 3 3 3 3 3 3 3 ...
 $ ate_fecNac              : POSIXct, format: "2018-10-07" "2017-03-30" ...
 $ ate_idCategoriaEESS     : chr  "07" "06" "04" "06" ...
 $ ate_TipoPerSalud        : chr  "01" "01" "01" "01" ...
 $ ate_grupoRiesgo         : chr  "150117" "150101" "150125" "150728" ...
 $ ate_esNatimuerto        : chr  "N" "N" "N" "N" ...
 $ ate_capita              : chr  "N" "N" "N" "N" ...
 $ ate_estado_observacion  : num  2 2 2 2 2 2 2 2 2 2 ...
 $ ate_grupofocalizado     : chr  "038" "012" "040" "024" ...
 $ ate_codDiag1            : chr  "Z138" "R509" "D509" "R509" ...
 $ ate_tipoDocPersonalSalud: num  1 1 1 1 1 1 1 1 1 1 ...
 $ PERS_D_FECNACIMIENTO    : POSIXct, format: "2018-10-07" "2017-03-30" ...
 $ PERS_V_SEXO             : num  1 1 1 0 1 1 0 0 1 1 ...
 $ PERS_V_UBIGEORESID      : num  150117 150101 150125 150728 150132 ...
 $ PERS_V_IDEESSADSCRIP    : chr  "150117A315" "150101A207" "150125A304" "0000017816" ...
 $ PERSD_FECFALLECIMIENTO  : POSIXct, format: NA NA ...
 $ EDAD_ANIOS              : num  0 1 0 1 0 1 0 2 0 1 ...
 $ EDAD_MESES              : num  2 21 8 12 6 12 10 30 3 17 ...
 $ ate_idnumreg            : num  6.09e+08 6.17e+08 6.16e+08 6.19e+08 6.16e+08 ...
 - attr(*, "problems")=Classes ‘tbl_df’, ‘tbl’ and 'data.frame':        72 obs. of  5 variables:
  ..$ row     : int  2480 2480 2480 2480 2480 2480 2480 2480 2480 2480 ...
  ..$ col     : chr  "ate_fecatencion" "ate_horatencion" "ate_fecinghosp" "ate_fecParto" ...
  ..$ expected: chr  "date like " "time like " "date like " "1/0/T/F/TRUE/FALSE" ...
  ..$ actual  : chr  "179435" "2018-04-12 14:00:00.0000000" "2" "5" ...
  ..$ file    : chr  "'F:/data sis/iatencion.txt'" "'F:/data sis/iatencion.txt'" "'F:/data sis/iatencion.txt'" "'F:/data sis/iatencion.txt'" ...
 - attr(*, "spec")=
  .. cols(
  ..   dni_mod = col_character(),
  ..   ate_disa = col_character(),
  ..   ate_ideess = col_character(),
  ..   ate_edad = col_double(),
  ..   ate_idgrupoEtareo = col_character(),
  ..   ate_idsexo = col_double(),
  ..   ate_codate = col_double(),
  ..   ate_esgestante = col_double(),
  ..   ate_historiaclinica = col_character(),
  ..   ate_fecatencion = col_datetime(format = ""),
  ..   ate_horatencion = col_time(format = ""),
  ..   ate_idEESSrefirio = col_character(),
  ..   ate_nrohojareferencia = col_character(),
  ..   ate_idServicio = col_character(),
  ..   ate_idlugar = col_double(),
  ..   ate_codDestino = col_double(),
  ..   ate_fecinghosp = col_datetime(format = ""),
  ..   ate_fecaltahosp = col_datetime(format = ""),
  ..   ate_ideesscontrarefiere = col_character(),
  ..   ate_numhojacontrarefiere = col_character(),
  ..   ate_idTipoPersonalSalud = col_double(),
  ..   ate_fecParto = col_logical(),
  ..   ate_idubigeo = col_character(),
  ..   ate_periodo = col_double(),
  ..   ate_mes = col_character(),
  ..   ate_tipoTraslado = col_logical(),
  ..   ate_tipoTrasnporte = col_logical(),
  ..   ate_UE = col_character(),
  ..   ate_tipDig = col_double(),
  ..   ate_fecNac = col_datetime(format = ""),
  ..   ate_idCategoriaEESS = col_character(),
  ..   ate_TipoPerSalud = col_character(),
  ..   ate_grupoRiesgo = col_character(),
  ..   ate_esNatimuerto = col_character(),
  ..   ate_capita = col_character(),
  ..   ate_estado_observacion = col_double(),
  ..   ate_grupofocalizado = col_character(),
  ..   ate_codDiag1 = col_character(),
  ..   ate_tipoDocPersonalSalud = col_double(),
  ..   PERS_D_FECNACIMIENTO = col_datetime(format = ""),
  ..   PERS_V_SEXO = col_double(),
  ..   PERS_V_UBIGEORESID = col_double(),
  ..   PERS_V_IDEESSADSCRIP = col_character(),
  ..   PERSD_FECFALLECIMIENTO = col_datetime(format = ""),
  ..   EDAD_ANIOS = col_double(),
  ..   EDAD_MESES = col_double(),
  ..   ate_idnumreg = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_med <- as.data.table(iatencion_med);str(iatencion_med)
Classes ‘data.table’ and 'data.frame':  833976 obs. of  6 variables:
 $ amed_CodMed            : chr  "08013" "04024" "04831" "03519" ...
 $ amed_inrodia           : num  1 1 1 1 2 1 1 2 2 1 ...
 $ amed_icantprescrita    : num  3 1 36 1 30 2 2 1 30 3 ...
 $ amed_icantentregada    : num  3 1 36 1 30 2 2 1 30 3 ...
 $ amed_icantaprobadaODSIS: num  NA NA NA NA NA NA NA NA NA NA ...
 $ ate_idnumreg           : num  5.60e+08 5.59e+08 5.57e+08 5.59e+08 5.60e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   amed_CodMed = col_character(),
  ..   amed_inrodia = col_double(),
  ..   amed_icantprescrita = col_double(),
  ..   amed_icantentregada = col_double(),
  ..   amed_icantaprobadaODSIS = col_double(),
  ..   amed_numregate = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
     iatencion_ins <- as.data.table(iatencion_ins);str(iatencion_ins)
Classes ‘data.table’ and 'data.frame':  499411 obs. of  6 variables:
 $ ains_inrodia               : num  1 3 3 3 2 1 1 1 1 1 ...
 $ ains_CodIns                : num  10355 15287 10554 19875 11370 ...
 $ ains_icantprescrita        : num  2 1 1 21 20 20 20 2 1 1 ...
 $ ains_icantentregada        : num  2 1 1 21 20 20 20 2 1 1 ...
 $ ains_icantidadaprobadaODSIS: num  NA NA NA NA NA NA NA NA NA NA ...
 $ ate_idnumreg               : num  5.55e+08 5.55e+08 5.55e+08 5.55e+08 5.55e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   ains_inrodia = col_double(),
  ..   ains_CodIns = col_double(),
  ..   ains_icantprescrita = col_double(),
  ..   ains_icantentregada = col_double(),
  ..   ains_icantidadaprobadaODSIS = col_double(),
  ..   ains_NumRegate = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_ser <- as.data.table(iatencion_ser);str(iatencion_ser)
Classes ‘data.table’ and 'data.frame':  146999 obs. of  5 variables:
 $ ASER_IDSERVICIO      : chr  "016" "007" "022" "016" ...
 $ aser_finalidad       : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ASER_CAPITA          : chr  NA NA NA NA ...
 $ ASER_IDFINANCIAMIENTO: num  1 1 1 1 1 1 1 1 1 1 ...
 $ ate_idnumreg         : num  5.59e+08 5.59e+08 5.59e+08 5.59e+08 5.60e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   ASER_IDSERVICIO = col_character(),
  ..   aser_finalidad = col_double(),
  ..   ASER_CAPITA = col_character(),
  ..   ASER_IDFINANCIAMIENTO = col_double(),
  ..   ASER_NUMREGATE = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_apo <- as.data.table(iatencion_apo);str(iatencion_apo )
Classes ‘data.table’ and 'data.frame':  1668345 obs. of  6 variables:
 $ aapo_CodApo        : chr  "90782" "97782" "99209" "99403" ...
 $ aapo_inrodia       : num  1 1 1 1 1 1 1 1 1 1 ...
 $ aapo_icantproced   : num  1 1 1 1 1 1 1 1 1 1 ...
 $ aapo_icantejecutada: num  1 1 1 1 1 1 1 1 1 1 ...
 $ aapo_Resultado     : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ate_idnumreg       : num  6.19e+08 6.16e+08 6.21e+08 6.19e+08 6.19e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   aapo_CodApo = col_character(),
  ..   aapo_inrodia = col_double(),
  ..   aapo_icantproced = col_double(),
  ..   aapo_icantejecutada = col_double(),
  ..   aapo_Resultado = col_double(),
  ..   aapo_NUMREGATE = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_dia <- as.data.table(iatencion_dia);str(iatencion_dia)
Classes ‘data.table’ and 'data.frame':  1436328 obs. of  5 variables:
 $ adia_iNroDia  : num  3 2 1 2 1 1 1 1 1 1 ...
 $ adia_CodDia   : chr  "J304" "J980" "J459" "Z108" ...
 $ adia_TipoDia  : num  1 1 1 1 4 4 1 1 1 1 ...
 $ adia_numregDia: num  NA NA NA NA NA ...
 $ ate_idnumreg  : num  5.56e+08 5.56e+08 5.56e+08 5.56e+08 5.56e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   adia_iNroDia = col_double(),
  ..   adia_CodDia = col_character(),
  ..   adia_TipoDia = col_double(),
  ..   adia_numregDia = col_double(),
  ..   adia_numregate = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_smi <- as.data.table(iatencion_smi);str(iatencion_smi)
Classes ‘data.table’ and 'data.frame':  4700512 obs. of  3 variables:
 $ ate_idnumreg: num  5.70e+08 5.72e+08 5.72e+08 5.72e+08 5.94e+08 ...
 $ asmi_codsmi : chr  "307" "124" "307" "004" ...
 $ asmi_Numero : chr  "1" "2" "1" "76.0" ...
 - attr(*, "spec")=
  .. cols(
  ..   asmi_numregate = col_double(),
  ..   asmi_codsmi = col_character(),
  ..   asmi_Numero = col_character()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>

    setkey(iatencion, ate_idnumreg)
    setkey(iatencion_med, ate_idnumreg)
    setkey(iatencion_ins, ate_idnumreg)
    setkey(iatencion_ser, ate_idnumreg)
    setkey(iatencion_apo, ate_idnumreg)
    setkey(iatencion_dia, ate_idnumreg)
    setkey(iatencion_smi, ate_idnumreg)

    mylist <- list(iatencion, iatencion_med, iatencion_ins, iatencion_ser, iatencion_apo, iatencion_dia, iatencion_smi)

    lapply(mylist, function(x) c(toString(dim(x)), toString(names(x))))

      multiFull <- merge(merge(merge(merge(merge(merge(
      mylist[[1L]],
      mylist[[2L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[3L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[4L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[5L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[6L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[7L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE)
</code>```

Error: can not locate a vector of size 30.4 Mb

Now my problem apparently is lack of memory, although my pc has these features:

```<code>    sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=Spanish_Chile.1252  LC_CTYPE=Spanish_Chile.1252
[3] LC_MONETARY=Spanish_Chile.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Chile.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] data.table_1.12.2 forcats_0.4.0     stringr_1.4.0     dplyr_0.8.1
 [5] purrr_0.3.2       readr_1.3.1       tidyr_0.8.3       tibble_2.1.1
 [9] ggplot2_3.1.1     tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1       pillar_1.4.0     compiler_3.6.0   cellranger_1.1.0
 [5] plyr_1.8.4       tools_3.6.0      jsonlite_1.6     lubridate_1.7.4
 [9] gtable_0.3.0     nlme_3.1-139     lattice_0.20-38  pkgconfig_2.0.2
[13] rlang_0.3.4      cli_1.1.0        rstudioapi_0.10  haven_2.1.0
[17] withr_2.1.2      xml2_1.2.0       httr_1.4.0       generics_0.0.2
[21] hms_0.4.2        grid_3.6.0       tidyselect_0.2.5 glue_1.3.1
[25] R6_2.4.0         readxl_1.3.1     modelr_0.1.4     magrittr_1.5
[29] backports_1.1.4  scales_1.0.0     rvest_0.3.4      assertthat_0.2.1
[33] colorspace_1.4-1 stringi_1.4.3    lazyeval_0.2.2   munsell_0.5.0
[37] broom_0.5.2      crayon_1.3.4
</code>```

Body:
Good evening, I want to replicate the function that appears in this blog https://www.r-bloggers.com/how-to-perform-merges-joins-on-two-or-more-data-frames-with-base-r-tidyverse-and-data-table/ Merging multiple data frames

flightsList <- readRDS(url(paste0(dataurl, "r006/nycflights13-list.rds")))
lapply(flightsList, function(x) c(toString(dim(x)), toString(names(x)))).

I have tried in many ways but I could not merge tables of diferents dims.

atencionesList <- serialize(list("iatencion","iatencion_apo", "iatencion_dia", "iatencion_ins", "iatencion_med", "iatencion_ser",
                    "iatencion_smi", "padron_nominado"), NULL)

atencionesList <- readRDS(paste0("~/GitHub/salud2018/Lima2019/Anelima/atenciones1.RDS"))
lapply(atencionesList, function(x) c(toString(dim(x)), toString(names(x))))

#****************************
atencionesList <- load(paste0("~/GitHub/salud2018/Lima2019/Anelima/atenciones.RData"))
lapply(atencionesList, function(x) c(toString(dim(x)), toString(names(x))))
#**********************************************

 multiFull <- merge(merge(merge(merge(merge(merge(merge(
+ atencionesList[[1L]],
+ atencionesList[[2L]], all = TRUE),
+ atencionesList[[3L]], all = TRUE),
+ atencionesList[[4L]], all = TRUE),
+ atencionesList[[5L]], all = TRUE),
+ atencionesList[[6L]], all = TRUE),
+ atencionesList[[7L]], all = TRUE),
+ atencionesList[[8L]], all = TRUE)

Unlike the example of the blog with the data of flights to me I do not leave a single dataframe that relate one to several the table attentions with the others by dni, date and other variables that are in the table.

Body:
I was able to make changes in the database,convert tibble in data.table, for example. As you can see I did the task to be able to merge multiple tibbles with the merge function, now the problem is lack of memory as you can see in the attached code.

setwd("~/GitHub/salud2018/Lima2019/Anelima")

iatencion <- read_delim("F:/data sis/iatencion.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
      iatencion_med <- read_delim("F:/data sis/iatencion_med.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_ins <- read_delim("F:/data sis/iatencion_ins.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_ser <- read_delim("F:/data sis/iatencion_ser.txt", "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_apo <- read_delim("F:/data sis/iatencion_apo.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    iatencion_dia <- read_delim("F:/data sis/iatencion_dia.txt",  "|", col_names = TRUE,escape_double = TRUE, trim_ws = TRUE)
    iatencion_smi <- read_delim("F:/data sis/iatencion_smi.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)
    padron_nominado <- read_delim("F:/data sis/padron_nominado.txt",  "|",col_names = TRUE, escape_double = TRUE, trim_ws = TRUE)

save(iatencion,iatencion_med, iatencion_ins, iatencion_ser,iatencion_apo, iatencion_dia,
     iatencion_smi, padron_nominado, file = "atenciones1.RData")

 load("~/GitHub/salud2018/Lima2019/Anelima/atenciones1.RData")

 setwd("~/GitHub/salud2018/Lima2019/Anelima")

        iatencion_med <- rename(iatencion_med, ate_idnumreg = amed_numregate)
        iatencion_ins <- rename(iatencion_ins, ate_idnumreg = ains_NumRegate)
        iatencion_ser <- rename(iatencion_ser, ate_idnumreg = ASER_NUMREGATE)
        iatencion_apo <- rename(iatencion_apo, ate_idnumreg = aapo_NUMREGATE)
        iatencion_dia <- rename(iatencion_dia, ate_idnumreg = adia_numregate)
        iatencion_smi <- rename(iatencion_smi, ate_idnumreg = asmi_numregate)

     iatencion <- as.data.table(iatencion); str(iatencion)
     iatencion_med <- as.data.table(iatencion_med);str(iatencion_med)
     iatencion_ins <- as.data.table(iatencion_ins);str(iatencion_ins)
     iatencion_ser <- as.data.table(iatencion_ser);str(iatencion_ser)

    iatencion_apo <- as.data.table(iatencion_apo);str(iatencion_apo )
    iatencion_dia <- as.data.table(iatencion_dia);str(iatencion_dia)
    iatencion_smi <- as.data.table(iatencion_smi);str(iatencion_smi)

    iatencion <- as.data.table(iatencion); str(iatencion)

Classes ‘data.table’ and 'data.frame':  1046739 obs. of  47 variables:
 $ dni_mod                 : chr  "82879909" "35766109" "37182709" "58953509" ...
 $ ate_disa                : chr  "350" "080" "035" "210" ...
 $ ate_ideess              : chr  "150101A109" "070103A101" "150125A304" "150118A101" ...
 $ ate_edad                : num  0 1 0 0 0 0 0 2 0 1 ...
 $ ate_idgrupoEtareo       : chr  "01" "01" "01" "01" ...
 $ ate_idsexo              : num  1 1 1 0 1 1 0 0 1 1 ...
 $ ate_codate              : num  2 3 1 3 1 1 1 1 1 1 ...
 $ ate_esgestante          : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ate_historiaclinica     : chr  "1078561" "201839089" "120542" "2577739" ...
 $ ate_fecatencion         : POSIXct, format: "2018-10-24 08:05:00" "2018-07-16 16:36:00" ...
 $ ate_horatencion         : 'hms' num  NA 16:36:00 11:30:00 11:50:00 ...
  ..- attr(*, "units")= chr "secs"
 $ ate_idEESSrefirio       : chr  "150135A101" NA NA NA ...
 $ ate_nrohojareferencia   : chr  "58246" NA NA NA ...
 $ ate_idServicio          : chr  "071" "062" "056" "062" ...
 $ ate_idlugar             : num  1 1 1 1 1 1 1 1 1 1 ...
 $ ate_codDestino          : num  2 2 1 1 2 1 2 1 2 2 ...
 $ ate_fecinghosp          : POSIXct, format: NA "2018-07-16" ...
 $ ate_fecaltahosp         : POSIXct, format: NA "2018-07-16" ...
 $ ate_ideesscontrarefiere : chr  NA NA NA NA ...
 $ ate_numhojacontrarefiere: chr  NA NA NA NA ...
 $ ate_idTipoPersonalSalud : num  1 1 1 1 6 1 6 10 6 13 ...
 $ ate_fecParto            : logi  NA NA NA NA NA NA ...
 $ ate_idubigeo            : chr  NA "150101" "150125" "150728" ...
 $ ate_periodo             : num  2018 2018 2018 2018 2018 ...
 $ ate_mes                 : chr  "11" "11" "11" "11" ...
 $ ate_tipoTraslado        : logi  NA NA NA NA NA NA ...
 $ ate_tipoTrasnporte      : logi  NA NA NA NA NA NA ...
 $ ate_UE                  : chr  "0149" "1318" "1684" "1138" ...
 $ ate_tipDig              : num  1 3 3 3 3 3 3 3 3 3 ...
 $ ate_fecNac              : POSIXct, format: "2018-10-07" "2017-03-30" ...
 $ ate_idCategoriaEESS     : chr  "07" "06" "04" "06" ...
 $ ate_TipoPerSalud        : chr  "01" "01" "01" "01" ...
 $ ate_grupoRiesgo         : chr  "150117" "150101" "150125" "150728" ...
 $ ate_esNatimuerto        : chr  "N" "N" "N" "N" ...
 $ ate_capita              : chr  "N" "N" "N" "N" ...
 $ ate_estado_observacion  : num  2 2 2 2 2 2 2 2 2 2 ...
 $ ate_grupofocalizado     : chr  "038" "012" "040" "024" ...
 $ ate_codDiag1            : chr  "Z138" "R509" "D509" "R509" ...
 $ ate_tipoDocPersonalSalud: num  1 1 1 1 1 1 1 1 1 1 ...
 $ PERS_D_FECNACIMIENTO    : POSIXct, format: "2018-10-07" "2017-03-30" ...
 $ PERS_V_SEXO             : num  1 1 1 0 1 1 0 0 1 1 ...
 $ PERS_V_UBIGEORESID      : num  150117 150101 150125 150728 150132 ...
 $ PERS_V_IDEESSADSCRIP    : chr  "150117A315" "150101A207" "150125A304" "0000017816" ...
 $ PERSD_FECFALLECIMIENTO  : POSIXct, format: NA NA ...
 $ EDAD_ANIOS              : num  0 1 0 1 0 1 0 2 0 1 ...
 $ EDAD_MESES              : num  2 21 8 12 6 12 10 30 3 17 ...
 $ ate_idnumreg            : num  6.09e+08 6.17e+08 6.16e+08 6.19e+08 6.16e+08 ...
 - attr(*, "problems")=Classes ‘tbl_df’, ‘tbl’ and 'data.frame':        72 obs. of  5 variables:
  ..$ row     : int  2480 2480 2480 2480 2480 2480 2480 2480 2480 2480 ...
  ..$ col     : chr  "ate_fecatencion" "ate_horatencion" "ate_fecinghosp" "ate_fecParto" ...
  ..$ expected: chr  "date like " "time like " "date like " "1/0/T/F/TRUE/FALSE" ...
  ..$ actual  : chr  "179435" "2018-04-12 14:00:00.0000000" "2" "5" ...
  ..$ file    : chr  "'F:/data sis/iatencion.txt'" "'F:/data sis/iatencion.txt'" "'F:/data sis/iatencion.txt'" "'F:/data sis/iatencion.txt'" ...
 - attr(*, "spec")=
  .. cols(
  ..   dni_mod = col_character(),
  ..   ate_disa = col_character(),
  ..   ate_ideess = col_character(),
  ..   ate_edad = col_double(),
  ..   ate_idgrupoEtareo = col_character(),
  ..   ate_idsexo = col_double(),
  ..   ate_codate = col_double(),
  ..   ate_esgestante = col_double(),
  ..   ate_historiaclinica = col_character(),
  ..   ate_fecatencion = col_datetime(format = ""),
  ..   ate_horatencion = col_time(format = ""),
  ..   ate_idEESSrefirio = col_character(),
  ..   ate_nrohojareferencia = col_character(),
  ..   ate_idServicio = col_character(),
  ..   ate_idlugar = col_double(),
  ..   ate_codDestino = col_double(),
  ..   ate_fecinghosp = col_datetime(format = ""),
  ..   ate_fecaltahosp = col_datetime(format = ""),
  ..   ate_ideesscontrarefiere = col_character(),
  ..   ate_numhojacontrarefiere = col_character(),
  ..   ate_idTipoPersonalSalud = col_double(),
  ..   ate_fecParto = col_logical(),
  ..   ate_idubigeo = col_character(),
  ..   ate_periodo = col_double(),
  ..   ate_mes = col_character(),
  ..   ate_tipoTraslado = col_logical(),
  ..   ate_tipoTrasnporte = col_logical(),
  ..   ate_UE = col_character(),
  ..   ate_tipDig = col_double(),
  ..   ate_fecNac = col_datetime(format = ""),
  ..   ate_idCategoriaEESS = col_character(),
  ..   ate_TipoPerSalud = col_character(),
  ..   ate_grupoRiesgo = col_character(),
  ..   ate_esNatimuerto = col_character(),
  ..   ate_capita = col_character(),
  ..   ate_estado_observacion = col_double(),
  ..   ate_grupofocalizado = col_character(),
  ..   ate_codDiag1 = col_character(),
  ..   ate_tipoDocPersonalSalud = col_double(),
  ..   PERS_D_FECNACIMIENTO = col_datetime(format = ""),
  ..   PERS_V_SEXO = col_double(),
  ..   PERS_V_UBIGEORESID = col_double(),
  ..   PERS_V_IDEESSADSCRIP = col_character(),
  ..   PERSD_FECFALLECIMIENTO = col_datetime(format = ""),
  ..   EDAD_ANIOS = col_double(),
  ..   EDAD_MESES = col_double(),
  ..   ate_idnumreg = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_med <- as.data.table(iatencion_med);str(iatencion_med)
Classes ‘data.table’ and 'data.frame':  833976 obs. of  6 variables:
 $ amed_CodMed            : chr  "08013" "04024" "04831" "03519" ...
 $ amed_inrodia           : num  1 1 1 1 2 1 1 2 2 1 ...
 $ amed_icantprescrita    : num  3 1 36 1 30 2 2 1 30 3 ...
 $ amed_icantentregada    : num  3 1 36 1 30 2 2 1 30 3 ...
 $ amed_icantaprobadaODSIS: num  NA NA NA NA NA NA NA NA NA NA ...
 $ ate_idnumreg           : num  5.60e+08 5.59e+08 5.57e+08 5.59e+08 5.60e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   amed_CodMed = col_character(),
  ..   amed_inrodia = col_double(),
  ..   amed_icantprescrita = col_double(),
  ..   amed_icantentregada = col_double(),
  ..   amed_icantaprobadaODSIS = col_double(),
  ..   amed_numregate = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
     iatencion_ins <- as.data.table(iatencion_ins);str(iatencion_ins)
Classes ‘data.table’ and 'data.frame':  499411 obs. of  6 variables:
 $ ains_inrodia               : num  1 3 3 3 2 1 1 1 1 1 ...
 $ ains_CodIns                : num  10355 15287 10554 19875 11370 ...
 $ ains_icantprescrita        : num  2 1 1 21 20 20 20 2 1 1 ...
 $ ains_icantentregada        : num  2 1 1 21 20 20 20 2 1 1 ...
 $ ains_icantidadaprobadaODSIS: num  NA NA NA NA NA NA NA NA NA NA ...
 $ ate_idnumreg               : num  5.55e+08 5.55e+08 5.55e+08 5.55e+08 5.55e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   ains_inrodia = col_double(),
  ..   ains_CodIns = col_double(),
  ..   ains_icantprescrita = col_double(),
  ..   ains_icantentregada = col_double(),
  ..   ains_icantidadaprobadaODSIS = col_double(),
  ..   ains_NumRegate = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_ser <- as.data.table(iatencion_ser);str(iatencion_ser)
Classes ‘data.table’ and 'data.frame':  146999 obs. of  5 variables:
 $ ASER_IDSERVICIO      : chr  "016" "007" "022" "016" ...
 $ aser_finalidad       : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ASER_CAPITA          : chr  NA NA NA NA ...
 $ ASER_IDFINANCIAMIENTO: num  1 1 1 1 1 1 1 1 1 1 ...
 $ ate_idnumreg         : num  5.59e+08 5.59e+08 5.59e+08 5.59e+08 5.60e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   ASER_IDSERVICIO = col_character(),
  ..   aser_finalidad = col_double(),
  ..   ASER_CAPITA = col_character(),
  ..   ASER_IDFINANCIAMIENTO = col_double(),
  ..   ASER_NUMREGATE = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_apo <- as.data.table(iatencion_apo);str(iatencion_apo )
Classes ‘data.table’ and 'data.frame':  1668345 obs. of  6 variables:
 $ aapo_CodApo        : chr  "90782" "97782" "99209" "99403" ...
 $ aapo_inrodia       : num  1 1 1 1 1 1 1 1 1 1 ...
 $ aapo_icantproced   : num  1 1 1 1 1 1 1 1 1 1 ...
 $ aapo_icantejecutada: num  1 1 1 1 1 1 1 1 1 1 ...
 $ aapo_Resultado     : num  0 0 0 0 0 0 0 0 0 0 ...
 $ ate_idnumreg       : num  6.19e+08 6.16e+08 6.21e+08 6.19e+08 6.19e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   aapo_CodApo = col_character(),
  ..   aapo_inrodia = col_double(),
  ..   aapo_icantproced = col_double(),
  ..   aapo_icantejecutada = col_double(),
  ..   aapo_Resultado = col_double(),
  ..   aapo_NUMREGATE = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_dia <- as.data.table(iatencion_dia);str(iatencion_dia)
Classes ‘data.table’ and 'data.frame':  1436328 obs. of  5 variables:
 $ adia_iNroDia  : num  3 2 1 2 1 1 1 1 1 1 ...
 $ adia_CodDia   : chr  "J304" "J980" "J459" "Z108" ...
 $ adia_TipoDia  : num  1 1 1 1 4 4 1 1 1 1 ...
 $ adia_numregDia: num  NA NA NA NA NA ...
 $ ate_idnumreg  : num  5.56e+08 5.56e+08 5.56e+08 5.56e+08 5.56e+08 ...
 - attr(*, "spec")=
  .. cols(
  ..   adia_iNroDia = col_double(),
  ..   adia_CodDia = col_character(),
  ..   adia_TipoDia = col_double(),
  ..   adia_numregDia = col_double(),
  ..   adia_numregate = col_double()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>
    iatencion_smi <- as.data.table(iatencion_smi);str(iatencion_smi)
Classes ‘data.table’ and 'data.frame':  4700512 obs. of  3 variables:
 $ ate_idnumreg: num  5.70e+08 5.72e+08 5.72e+08 5.72e+08 5.94e+08 ...
 $ asmi_codsmi : chr  "307" "124" "307" "004" ...
 $ asmi_Numero : chr  "1" "2" "1" "76.0" ...
 - attr(*, "spec")=
  .. cols(
  ..   asmi_numregate = col_double(),
  ..   asmi_codsmi = col_character(),
  ..   asmi_Numero = col_character()
  .. )
 - attr(*, ".internal.selfref")=<externalptr>

    setkey(iatencion, ate_idnumreg)
    setkey(iatencion_med, ate_idnumreg)
    setkey(iatencion_ins, ate_idnumreg)
    setkey(iatencion_ser, ate_idnumreg)
    setkey(iatencion_apo, ate_idnumreg)
    setkey(iatencion_dia, ate_idnumreg)
    setkey(iatencion_smi, ate_idnumreg)

    mylist <- list(iatencion, iatencion_med, iatencion_ins, iatencion_ser, iatencion_apo, iatencion_dia, iatencion_smi)

    lapply(mylist, function(x) c(toString(dim(x)), toString(names(x))))

      multiFull <- merge(merge(merge(merge(merge(merge(
      mylist[[1L]],
      mylist[[2L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[3L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[4L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[5L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[6L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE),
      mylist[[7L]],  by=.EACHI, allow.cartesian=TRUE, all = TRUE)

Error: can not locate a vector of size 30.4 Mb

Now my problem apparently is lack of memory, although my pc has these features:

    sessionInfo()
R version 3.6.0 (2019-04-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 17763)

Matrix products: default

locale:
[1] LC_COLLATE=Spanish_Chile.1252  LC_CTYPE=Spanish_Chile.1252
[3] LC_MONETARY=Spanish_Chile.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Chile.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] data.table_1.12.2 forcats_0.4.0     stringr_1.4.0     dplyr_0.8.1
 [5] purrr_0.3.2       readr_1.3.1       tidyr_0.8.3       tibble_2.1.1
 [9] ggplot2_3.1.1     tidyverse_1.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1       pillar_1.4.0     compiler_3.6.0   cellranger_1.1.0
 [5] plyr_1.8.4       tools_3.6.0      jsonlite_1.6     lubridate_1.7.4
 [9] gtable_0.3.0     nlme_3.1-139     lattice_0.20-38  pkgconfig_2.0.2
[13] rlang_0.3.4      cli_1.1.0        rstudioapi_0.10  haven_2.1.0
[17] withr_2.1.2      xml2_1.2.0       httr_1.4.0       generics_0.0.2
[21] hms_0.4.2        grid_3.6.0       tidyselect_0.2.5 glue_1.3.1
[25] R6_2.4.0         readxl_1.3.1     modelr_0.1.4     magrittr_1.5
[29] backports_1.1.4  scales_1.0.0     rvest_0.3.4      assertthat_0.2.1
[33] colorspace_1.4-1 stringi_1.4.3    lazyeval_0.2.2   munsell_0.5.0
[37] broom_0.5.2      crayon_1.3.4


问:
Only numbers are missing Weasyprint PDF
That's it, I'm on Mac Mojave with weasyprint-44, python 3.6, and Cairo etc. versions match. The PDF renders nicely otherwise - symbols and letters are fine - just no numbers?

So weird.

Can anyone point me in the right direction?

答:
I am on Mac (Mojave 10.14.5) and have the same problem. I managed to fix it by defining a different font family for print. In my case, I use:

```<code>font-family: "Open Sans", Calibri, Candara, Arial, sans-serif;
</code>```

everything prints out nicely.

Title: Only numbers are missing Weasyprint PDF

Body:
I am on Mac (Mojave 10.14.5) and have the same problem. I managed to fix it by defining a different font family for print. In my case, I use:

font-family: "Open Sans", Calibri, Candara, Arial, sans-serif;

everything prints out nicely.


问:
How do I send a packet in AutoIt?
I'd like to send a some packet to modbus/tcp device to control it.
I do success in python as follow:

```<code>sdata = struct.pack('BBBBBBBBBBBBBBB',0x00,0x00,0x00,0x00,0x00,0x09,0x01,0x10,0x00,0x08,0x00,0x01,0x02,0x00,0x01)
sock.send(sdata)
</code>```

And it works well;

But now I don't know how to do like this in Autoit.

I try to do like this:

```<code>$szData = Binary("0x00,0x00,0x00,0x00,0x00,0x09,0x01,0x10,0x00,0x08,0x00,0x01,0x02,0x00,0x01");
TCPSend($ConnectedSocket, $szData)
</code>```

But this does not work like above python source.

答:
AutoIt is not Python. The AutoIt Binary function does not work the same as struct.pack in Python. AutoIt expects input like this:

```<code>$szData = Binary("0x000000000009011000080001020001")
</code>```

If you still want to input your data like this: "0x00,0x00,0x00,0x00" then you will have to invent your own Binary function. A simple "hack" is:

```<code>Func _Binary($s)
   $b = StringReplace($s, ",0x", "") ; Replaces ,0x with empty string
   Return Binary($b)
EndFunc
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I send a packet in AutoIt?

Body:
I'd like to send a some packet to modbus/tcp device to control it.
I do success in python as follow:

sdata = struct.pack('BBBBBBBBBBBBBBB',0x00,0x00,0x00,0x00,0x00,0x09,0x01,0x10,0x00,0x08,0x00,0x01,0x02,0x00,0x01)
sock.send(sdata)

And it works well;

But now I don't know how to do like this in Autoit.

I try to do like this:

$szData = Binary("0x00,0x00,0x00,0x00,0x00,0x09,0x01,0x10,0x00,0x08,0x00,0x01,0x02,0x00,0x01");
TCPSend($ConnectedSocket, $szData)

But this does not work like above python source.

Body:
AutoIt is not Python. The AutoIt Binary function does not work the same as struct.pack in Python. AutoIt expects input like this:

$szData = Binary("0x000000000009011000080001020001")

If you still want to input your data like this: "0x00,0x00,0x00,0x00" then you will have to invent your own Binary function. A simple "hack" is:

Func _Binary($s)
   $b = StringReplace($s, ",0x", "") ; Replaces ,0x with empty string
   Return Binary($b)
EndFunc


问:
Flutter Row: align left and right, share remaining space
Here's an image of what I'd like to achieve. Basically I want the left and right widgets to grow as much as possible until they'd both need to wrap, in which case each should take 50%. In most cases only one of the left or right widgets will be long enough to wrap - rarely both. </p>

<p>I've tried some of the suggestions from this question and this question but haven't had any luck. </p>

答:
```<code>ListTile(
  title: Text("The quick brown fox jumps over the lazy dog", maxLines: 2),
  trailing: Text("The quick brown", maxLines: 2),
);
</code>```

Body:
Here's an image of what I'd like to achieve. Basically I want the left and right widgets to grow as much as possible until they'd both need to wrap, in which case each should take 50%. In most cases only one of the left or right widgets will be long enough to wrap - rarely both.

I've tried some of the suggestions from this question and this question but haven't had any luck.


问:
Python control "with" context manager with conditional
Can Python2.7 use a conditional to control a "with" context manager?  My scenario is that if a gzipped file exists, I want to append to it, and if it does not exist, I want to write to a new file.  The pseudo code is:

```<code>with gzip.open(outfile, 'a+') if os.isfile(outfile) else with open(outfile, 'w') as outhandle:
</code>```

Or...

```<code>if os.isfile(outfile):
    with gzip.open(outfile, 'a+') as outhandle:
        # do stuff
else:
    with open(outfile, 'w') as outhandle:
        # do the same stuff
</code>```

I don't want to repeat the "do stuff" since it will be the same between them.  But how can I use a conditional to control the with context?

答:
Remember that functions can also be assigned to variables</p>

```<code>if os.isfile(outfile):
    open_function = gzip.open
    mode = 'a+'
else:
    open_function = open
    mode = 'w'

with open_function(outfile, mode) as outhandle:
    # do stuff
</code>```

Body:
Can Python2.7 use a conditional to control a "with" context manager?  My scenario is that if a gzipped file exists, I want to append to it, and if it does not exist, I want to write to a new file.  The pseudo code is:

with gzip.open(outfile, 'a+') if os.isfile(outfile) else with open(outfile, 'w') as outhandle:

Or...

if os.isfile(outfile):
    with gzip.open(outfile, 'a+') as outhandle:
        # do stuff
else:
    with open(outfile, 'w') as outhandle:
        # do the same stuff

I don't want to repeat the "do stuff" since it will be the same between them.  But how can I use a conditional to control the with context?

Body:
Remember that functions can also be assigned to variables

if os.isfile(outfile):
    open_function = gzip.open
    mode = 'a+'
else:
    open_function = open
    mode = 'w'

with open_function(outfile, mode) as outhandle:
    # do stuff


问:
2 errors in my javascript random number-guessing game
This is the first app I have ever written.  I have seen a million random number-generating games here, javascript and otherwise, but none had the problems I'm having.  I apologize for my ignorance, but when I know what I'm doing wrong, this will go a long way toward my understanding of javascript and coding in general. I'm just playing in the browser console as of now.

I've done this with a for loop, but I wanted to try another option and use a decrement counter.  I've tried using the if/else stuff from the inner function inside the while loop.  The code looks right to me.

```<code>const guessingGame = (tries) => {
    const answer = Math.floor(Math.random() * 11)
    let guess = null
    let status = "playing"
    function makeGuess() {
        if (guess === answer) {
            status = "won"
        } else if (tries === 0) {
            status = "lost"
        } else {
            tries--
            if (tries === 1) {
                console.log(tries + ' guess left')
            } else {
                console.log(tries + ' guesses left')
            }
        }
    }
    while (status === "playing") {
        if (!guess) {
            guess = prompt('Guess a number between 1 and 10')
            makeGuess()
        } else if (guess > answer) {
            guess = prompt('Lower')
            makeGuess()
        } else if (guess < answer) {
            guess = prompt('Higher')
            makeGuess()
        } else {
            break
        }
    }
    console.log("Game Over.  You " + status + "!  The answer was " + answer + ".")
}
</code>```

This game should invoke/launch with one argument, the number of tries allowed.  If I correctly guess the answer, the console log at the end should include status = "won".  But when I win, it includes status = "playing".

When I guess wrong "tries" number of times, I should lose.  But when I see "0 guesses left" in the console, the game gives one more guess, and I can take it, effectively making tries -1, I think.  When I make one additional wrong guess, status correctly changes to "lost" and the final console message is correct.

答:
The result of prompt is a string; thus, guess is a string. The result of Math.floor is a number, so answer is a number.

> and < are coercing operators: if one of the operands is a number, the other is converted into the number, as well. This means guess < answer and guess > answer work as you hope it does.

However, you've apparently heard people say "never use ==, always use ===" and taken it to heart. The reason for the saying is == is also a coercing operator, and as a consequence sometimes things that don't look equal end up being equal. However, here you actually needed to use the coercing ==, because 1 == '1' (even though 1 and '1' are different types), but the strict 1 === '1' ends up being false!

Thus, you first check if guess is strictly equal to answer. Since their types are different, it is impossible, so you move on. You check if guess is above the answer, then you check whether it is below the answer, both of those return false as well. The only remaining option is to break from the loop - and "winner" never gets printed.

Beside this, your biggest problem is actually logic. The placement of different tests and actions is somewhat questionable. For example, one would expect that testing whether guess is equal to the answer would be right next to the test to see if it is bigger or smaller. The test for tries would be most at home right at the while loop; but you have an infinite loop, and an independent test for tries. You enter the first guess with a unique prompt, but it is inside an infinite loop, despite the fact it can only ever happen once. You have a function called makeGuess, but the function does two or three different things, none of which is actually making a guess.

Rather than start working on code right away, then fixing problems as they pop up, try to imagine first what the flow would be. How would a human do it? Then write code.

Here's the basic idea for the same game:

```<code>answer = imagineAnswer()
guess = askForFirstGuess()
status = "lost"
while (--tries) {
  if (guess > answer) {
    guess = askForHigherGuess()
  } else if (guess < answer) {
    guess = askForLowerGuess()
  } else {
    status = "won"
    break
  }
}
reportGameEnd(status)
</code>```

Body:
This is the first app I have ever written.  I have seen a million random number-generating games here, javascript and otherwise, but none had the problems I'm having.  I apologize for my ignorance, but when I know what I'm doing wrong, this will go a long way toward my understanding of javascript and coding in general. I'm just playing in the browser console as of now.

I've done this with a for loop, but I wanted to try another option and use a decrement counter.  I've tried using the if/else stuff from the inner function inside the while loop.  The code looks right to me.

const guessingGame = (tries) => {
    const answer = Math.floor(Math.random() * 11)
    let guess = null
    let status = "playing"
    function makeGuess() {
        if (guess === answer) {
            status = "won"
        } else if (tries === 0) {
            status = "lost"
        } else {
            tries--
            if (tries === 1) {
                console.log(tries + ' guess left')
            } else {
                console.log(tries + ' guesses left')
            }
        }
    }
    while (status === "playing") {
        if (!guess) {
            guess = prompt('Guess a number between 1 and 10')
            makeGuess()
        } else if (guess > answer) {
            guess = prompt('Lower')
            makeGuess()
        } else if (guess < answer) {
            guess = prompt('Higher')
            makeGuess()
        } else {
            break
        }
    }
    console.log("Game Over.  You " + status + "!  The answer was " + answer + ".")
}

This game should invoke/launch with one argument, the number of tries allowed.  If I correctly guess the answer, the console log at the end should include status = "won".  But when I win, it includes status = "playing".

When I guess wrong "tries" number of times, I should lose.  But when I see "0 guesses left" in the console, the game gives one more guess, and I can take it, effectively making tries -1, I think.  When I make one additional wrong guess, status correctly changes to "lost" and the final console message is correct.

Body:
The result of prompt is a string; thus, guess is a string. The result of Math.floor is a number, so answer is a number.

> and < are coercing operators: if one of the operands is a number, the other is converted into the number, as well. This means guess < answer and guess > answer work as you hope it does.

However, you've apparently heard people say "never use ==, always use ===" and taken it to heart. The reason for the saying is == is also a coercing operator, and as a consequence sometimes things that don't look equal end up being equal. However, here you actually needed to use the coercing ==, because 1 == '1' (even though 1 and '1' are different types), but the strict 1 === '1' ends up being false!

Thus, you first check if guess is strictly equal to answer. Since their types are different, it is impossible, so you move on. You check if guess is above the answer, then you check whether it is below the answer, both of those return false as well. The only remaining option is to break from the loop - and "winner" never gets printed.

Beside this, your biggest problem is actually logic. The placement of different tests and actions is somewhat questionable. For example, one would expect that testing whether guess is equal to the answer would be right next to the test to see if it is bigger or smaller. The test for tries would be most at home right at the while loop; but you have an infinite loop, and an independent test for tries. You enter the first guess with a unique prompt, but it is inside an infinite loop, despite the fact it can only ever happen once. You have a function called makeGuess, but the function does two or three different things, none of which is actually making a guess.

Rather than start working on code right away, then fixing problems as they pop up, try to imagine first what the flow would be. How would a human do it? Then write code.

Here's the basic idea for the same game:

answer = imagineAnswer()
guess = askForFirstGuess()
status = "lost"
while (--tries) {
  if (guess > answer) {
    guess = askForHigherGuess()
  } else if (guess < answer) {
    guess = askForLowerGuess()
  } else {
    status = "won"
    break
  }
}
reportGameEnd(status)


答:
You checked tries === 0 before tries--, that's why you get 0 guesses left. You should decrement before checking.

The guess is actually a string not a number, so guess === answer never true. The next iteration after you guessed correctly, it falls into else{break} with the status still playing. You either want Number(guess) === answer or just guess == answer.

By Math.floor(Math.random() * 11) you are actually generating 0-10. You want Math.floor(Math.random() * 10) + 1 for 1-10. Just remember Math.floor(Math.random() * n) gives you n possible outcomes, which happens to be an integer in the range [0,n). Then do whatever calculation you want to map it to your desire output value.

const guessingGame = (tries) => {
    const answer = Math.floor(Math.random() * 10) + 1
    let guess = null
    let status = "playing"
    function makeGuess() {
        tries--;
        if (guess === answer) {
            status = "won"
        } else if (tries === 0) {
            status = "lost"
        } else {

            if (tries === 1) {
                console.log(tries + ' guess left')
            } else {
                console.log(tries + ' guesses left')
            }
        }
    }
    while (status === "playing") {
        if (!guess) {
            guess = Number(prompt('Guess a number between 1 and 10'))
            makeGuess()
        } else if (guess > answer) {
            guess = Number(prompt('Lower'))
            makeGuess()
        } else if (guess < answer) {
            guess = Number(prompt('Higher'))
            makeGuess()
        } else {
            break
        }
    }
    console.log("Game Over.  You " + status + "!  The answer was " + answer + ".")
}
guessingGame(5);```

Title: 2 errors in my javascript random number-guessing game