问:
Error while trying to implement ClickListener in Recyclerview
I am bumbing my head on trying to implement a ClickListener in an adapter for a DialogFragment.

I am getting the error on the codeline:

holder.bind(tzmodel.get(position), listener);

Error says (bind() in ViewHolder cannot be applied). Seems it does not match the ViewHolder code.

Could somebody please assist?

The code for my timeZoneAdapter:

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

    public interface OnItemClickListener {

        void onItemClick(TimezoneModel item);
    }

    private Context c;
    private List<TimezoneModel> tzmodel;
    private final OnItemClickListener listener;

    public timeZoneAdapter(Context c, List<TimezoneModel> tzModel, OnItemClickListener listener) {

        this.c = c;
        this.tzmodel = tzModel;
        this.listener = listener;
    }

    //INITIALIE TZ
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timezonemodel, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.bind(tzmodel.get(position), listener); <-- error
    }

    @Override
    public int getItemCount() {

        return tzmodel.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView timeTxt, currenttimeTxt, regionTxt;

        public ViewHolder(View itemView) {

            super(itemView);
            timeTxt= (TextView) itemView.findViewById(R.id.timeTxt);
            currenttimeTxt= (TextView) itemView.findViewById(R.id.currentTimeTxt);
            regionTxt= (TextView) itemView.findViewById(R.id.regionTxt);
        }

        public void bind(ViewHolder viewHolder, int i, final OnItemClickListener listener) {

            viewHolder.timeTxt.setText(tzmodel.get(i).getTime());
            viewHolder.currenttimeTxt.setText(tzmodel.get(i).getCurrentTime());
            viewHolder.regionTxt.setText(tzmodel.get(i).getRegion());

            itemView.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v) {

                    listener.onItemClick((TimezoneModel) tzmodel);
                }
            });
        }
    }
}
</code>```

答:
The problem is the parameters that you put in the bind method that you define.

You define the public method bind in the ViewHolder class in this way:

public void bind(ViewHolder viewHolder, int i, final OnItemClickListener listener){

   //...

}
```

<p>You can fix your compile error change the call to : </p>

<pre class="lang-java prettyprint-override"><code>@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(holder,position, listener);
}
</code>```

I also share with you a couple of correction because if you create a public method in the ViewHolder class, you don't need to recipe the viewHolder instance because you can access with this operator:

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

    public interface OnItemClickListener {
        void onItemClick(TimezoneModel item);
    }

    private Context c;
    private List<TimezoneModel> tzmodel;
    private final OnItemClickListener listener;

    public TimeZoneAdapter(Context c, List<TimezoneModel> tzModel, OnItemClickListener listener) {
        this.c = c;
        this.tzmodel = tzModel;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(tzmodel.get(position), listener);
    }

    @Override
    public int getItemCount() {

        return tzmodel.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView timeTxt, currenttimeTxt, regionTxt;

        public ViewHolder(View itemView) {

            super(itemView);
            timeTxt= itemView.findViewById(R.id.timeTxt);
            currenttimeTxt= itemView.findViewById(R.id.currentTimeTxt);
            regionTxt= itemView.findViewById(R.id.regionTxt);
        }

        public void bind(TimezoneModel item , final OnItemClickListener listener) {

            this.timeTxt.setText(item.getTime());
            this.currenttimeTxt.setText(item.getCurrentTime());
            this.regionTxt.setText(item.getRegion());

            itemView.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v) {
                    listener.onItemClick((TimezoneModel) tzmodel);
                }
            });
        }
    }
}

```

Body:
I am bumbing my head on trying to implement a ClickListener in an adapter for a DialogFragment.

I am getting the error on the codeline:

holder.bind(tzmodel.get(position), listener);

Error says (bind() in ViewHolder cannot be applied). Seems it does not match the ViewHolder code.

Could somebody please assist?

The code for my timeZoneAdapter:

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

    public interface OnItemClickListener {

        void onItemClick(TimezoneModel item);
    }

    private Context c;
    private List<TimezoneModel> tzmodel;
    private final OnItemClickListener listener;

    public timeZoneAdapter(Context c, List<TimezoneModel> tzModel, OnItemClickListener listener) {

        this.c = c;
        this.tzmodel = tzModel;
        this.listener = listener;
    }

    //INITIALIE TZ
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.timezonemodel, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.bind(tzmodel.get(position), listener); <-- error
    }

    @Override
    public int getItemCount() {

        return tzmodel.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView timeTxt, currenttimeTxt, regionTxt;

        public ViewHolder(View itemView) {

            super(itemView);
            timeTxt= (TextView) itemView.findViewById(R.id.timeTxt);
            currenttimeTxt= (TextView) itemView.findViewById(R.id.currentTimeTxt);
            regionTxt= (TextView) itemView.findViewById(R.id.regionTxt);
        }

        public void bind(ViewHolder viewHolder, int i, final OnItemClickListener listener) {

            viewHolder.timeTxt.setText(tzmodel.get(i).getTime());
            viewHolder.currenttimeTxt.setText(tzmodel.get(i).getCurrentTime());
            viewHolder.regionTxt.setText(tzmodel.get(i).getRegion());

            itemView.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v) {

                    listener.onItemClick((TimezoneModel) tzmodel);
                }
            });
        }
    }
}

Body:
The problem is the parameters that you put in the bind method that you define.

You define the public method bind in the ViewHolder class in this way:

public void bind(ViewHolder viewHolder, int i, final OnItemClickListener listener){

   //...

}

You can fix your compile error change the call to :

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(holder,position, listener);
}

I also share with you a couple of correction because if you create a public method in the ViewHolder class, you don't need to recipe the viewHolder instance because you can access with this operator:

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

    public interface OnItemClickListener {
        void onItemClick(TimezoneModel item);
    }

    private Context c;
    private List<TimezoneModel> tzmodel;
    private final OnItemClickListener listener;

    public TimeZoneAdapter(Context c, List<TimezoneModel> tzModel, OnItemClickListener listener) {
        this.c = c;
        this.tzmodel = tzModel;
        this.listener = listener;
    }

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

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(tzmodel.get(position), listener);
    }

    @Override
    public int getItemCount() {

        return tzmodel.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        TextView timeTxt, currenttimeTxt, regionTxt;

        public ViewHolder(View itemView) {

            super(itemView);
            timeTxt= itemView.findViewById(R.id.timeTxt);
            currenttimeTxt= itemView.findViewById(R.id.currentTimeTxt);
            regionTxt= itemView.findViewById(R.id.regionTxt);
        }

        public void bind(TimezoneModel item , final OnItemClickListener listener) {

            this.timeTxt.setText(item.getTime());
            this.currenttimeTxt.setText(item.getCurrentTime());
            this.regionTxt.setText(item.getRegion());

            itemView.setOnClickListener(new View.OnClickListener() {

                @Override public void onClick(View v) {
                    listener.onItemClick((TimezoneModel) tzmodel);
                }
            });
        }
    }
}


来源: stackexchange

问:
Migrating from JobScheduler to WorkManager seems like a massive undertaking. Any advice+
I've used JobScheduler for a while now. A typical example would be:

JobScheduler triggers the onStartJob() method. This kicks off some sort of task that might include several other background processes (getting device position, making a network call, etc). I then use an interface to call back to the JobService once the task is complete or if it fails.

However, with WorkManager it seems like there is basically no way to run work asynchronously. I know WorkManager will run Workers in a separate thread but it seems like a single worker must run synchronously? If so I'll have to rework a lot of the logic in my app it seems unless I'm missing something.

Say I had a weather app and it would use the JobScheduler to run a JobService that did the following:

onStartJob() --> get device position --> make API request for local weather data -> write to database -> call jobFinished()

With WorkManager, is the intended implementation of something like this to chain multiple workers together? And if so, how do you pass data from one Worker to another? Again, seems like it would be a massive undertaking for any slightly complex app to migrate to the WorkManager API.

答:
I think what you are looking for is a ListenableWorker. It has exactly that interface. Rather than you having to call jobFinished() in the end, we do the work for you when you resolve the ListenableFuture.

https://developer.android.com/reference/androidx/work/ListenableWorker.html#startWork() is analogous to onStartJob in your case.

ContentLicense: CC BY-SA 4.0


问:
Comparing results of neural net on two subsets of features
I am running a LSTM model on a multivariate time series data set with 24 features. I have ran feature extraction using a few different methods (variance testing, random forest extraction, and Extra Tree Classifier). Different methods have resulted in a slightly different subset of features. I now want to test my LSTM model on all subsets to see which gives the best results.

My problem is that the test/train RMSE scores for my 3 models are all very similar, and every time I run my model I get slightly different answers. This question is coming from a person who is naive and still learning the intricacies of neural nets, so please help me understand: in a case like this, how do you go about determining which model is best? Can you do seeding for neural nets? Or some type of averaging over a certain amount of trials?

答:
Since you have mentioned that using the different feature extraction methods, you are only getting slightly different feature sets, so the results are also similar. Also since your LSTM model is then also getting almost similar RMSE values, the models are able to generalize well and learn similarly and extract important information from all the datasets.

The best model depends on your future data, the computation time and load of different methods and how well they will last in production. Setting a seed is not really a good idea in neural nets. The basic idea is that your model should be able to reach the optimal weights no matter how they start. If your models are always getting similar results, in most cases, it is a good thing.


问:
How can I limit a html input box so that it only accepts numeric input?
I have an html input box, but only numeric data is data. How can I enforce that?</p>

答:
```<code><input name="txtnumbersOnly"  type="text" onkeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;">
</code>```

ContentLicense: CC BY-SA 3.0


问:
Having a JSON parse error in receiving json data
Hi I am trying to send a JSON array from a POST to Spring backend.

In my Javascript:

```<code>$('#tblfilelisting tbody tr').each(function () {
        var namerecord = {
            No: $(this).find('.assignindex').text().trim(),
            Name: $(this).find('.getname').val(),
            File: $(this).find('.getfilename').text().trim(),
            Status: $(this).find('.radioname:checked').val()
        };
        nameList.push(namerecord);
    });

    var jasonData = new FormData();
    jasonData.append('arrStr', JSON.stringify(nameList));
    $.ajax({
        type: 'POST',
        url: '/api/CheckValidateBeforeSave',
        data: jasonData,
        contentType: 'application/json',
        processData: false,
        beforeSend: function () {
            //
        },
        success: function (data) {
            if (data.code != '200') {
                return false;
            }
            var get = data.jasonResult;
            for (var i = 0; i < get.length; i++) {
                appendResultResponse(get.No[i], get.Name[i], get.File[i], get.Status[i], get.Result[i]);
                appendErrorMess(get.No[i], get.hasDuplicated[i]);
            }
            $('#uploadFileConfirmation').modal('show');
        },
        error: function (err) {
            //
        },
    });
</code>```

In my REST Controller, I have:

```<code>@PostMapping(value = "/CheckValidateBeforeSave", produces = "application/json", consumes = "application/json")
    @ResponseBody
    public FileManagement CheckValidateBeforeSave(@RequestBody FileManagement fileManagement) {
        fileManagementService.checkMultipleFiles(fileManagement);
        return fileManagement;
    }
</code>```

But the error that I got was :
JSON parse error: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value

But my POST request does not have - sign:

------WebKitFormBoundaryId7kxO7B9rozEwHv
Content-Disposition: form-data; name="arrStr"

[{"No":"1","Name":"dd","File":"Test PDF 2.pdf","Status":"on"}]
------WebKitFormBoundaryId7kxO7B9rozEwHv--
line-awesome.woff2?v=1.1.   CheckValidateBeforeSave common.js   util.js AuthenticationService.Authenticate?1shttp%3A%2F%2F…zaSyBTGnKT7dt597vo9QgeQ7BFhvSRP4eiMSM&token=29026

Please help. Thanks.

答:
The reason you are getting JSON parse error is that you are not actually sending a data of JSON format. Instead, your data have FormData format.

There are two ways you can fix it.

1. You only need to send the nameList

```<code>data: JSON.stringify(nameList)
</code>```

2. You want to send it as FormData (optionally along with other data)

```<code>data:  {formdata: jasonData, var2: "other data"}
</code>```

Body:
Hi I am trying to send a JSON array from a POST to Spring backend.

In my Javascript:

$('#tblfilelisting tbody tr').each(function () {
        var namerecord = {
            No: $(this).find('.assignindex').text().trim(),
            Name: $(this).find('.getname').val(),
            File: $(this).find('.getfilename').text().trim(),
            Status: $(this).find('.radioname:checked').val()
        };
        nameList.push(namerecord);
    });

    var jasonData = new FormData();
    jasonData.append('arrStr', JSON.stringify(nameList));
    $.ajax({
        type: 'POST',
        url: '/api/CheckValidateBeforeSave',
        data: jasonData,
        contentType: 'application/json',
        processData: false,
        beforeSend: function () {
            //
        },
        success: function (data) {
            if (data.code != '200') {
                return false;
            }
            var get = data.jasonResult;
            for (var i = 0; i < get.length; i++) {
                appendResultResponse(get.No[i], get.Name[i], get.File[i], get.Status[i], get.Result[i]);
                appendErrorMess(get.No[i], get.hasDuplicated[i]);
            }
            $('#uploadFileConfirmation').modal('show');
        },
        error: function (err) {
            //
        },
    });

In my REST Controller, I have:

@PostMapping(value = "/CheckValidateBeforeSave", produces = "application/json", consumes = "application/json")
    @ResponseBody
    public FileManagement CheckValidateBeforeSave(@RequestBody FileManagement fileManagement) {
        fileManagementService.checkMultipleFiles(fileManagement);
        return fileManagement;
    }

But the error that I got was :
JSON parse error: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value

But my POST request does not have - sign:

------WebKitFormBoundaryId7kxO7B9rozEwHv
Content-Disposition: form-data; name="arrStr"

[{"No":"1","Name":"dd","File":"Test PDF 2.pdf","Status":"on"}]
------WebKitFormBoundaryId7kxO7B9rozEwHv--
line-awesome.woff2?v=1.1.   CheckValidateBeforeSave common.js   util.js AuthenticationService.Authenticate?1shttp%3A%2F%2F…zaSyBTGnKT7dt597vo9QgeQ7BFhvSRP4eiMSM&token=29026

Please help. Thanks.

Body:
The reason you are getting JSON parse error is that you are not actually sending a data of JSON format. Instead, your data have FormData format.

There are two ways you can fix it.

1. You only need to send the nameList

data: JSON.stringify(nameList)

2. You want to send it as FormData (optionally along with other data)

data:  {formdata: jasonData, var2: "other data"}


问:
Automatic Random Test Data Generation of Documents for Seeding a MongoDB Database
I'm using JSON Generator https://next.json-generator.com to seed my MongoDB database. I'm finding trouble to generate a random set (from one to six) of colors out of the predefined group.

I've succeeded to generate all of the other property values but color. I need for the availableColors key to generate a random variable number of colors out of a predefined set of six: "blue", "brown", "green",  "white", "yellow", "gray".

Here is the URL to the online generator where it is possible to real-time edit it: https://next.json-generator.com/E1g60a1pL

Here is the code:

```<code>[
  {
    'repeat(5, 10)': {
      id: '{{objectId()}}',
      name: '{{firstName()}}',
      price: '{{floating(5, 4000, 2, "$0,0.00")}}',
      availableColors: (colors) => {
               var condition = '{{integer(1, 6)}}';
               var color = [];
               for (j = 0; j < condition+1; j++)
               {color [j] = '{{random("blue", "brown", "green",  "white", "yellow", "gray")}}';}
               let unique_array = [];
               for(let i = 0;i < color.length; i++) {
                   if(unique_array.indexOf(color[i]) == -1){
                      unique_array.push(color[i]);
                }
               }
               return unique_array;
},
      weight: '{{floating(1, 4000, 2, "0.00")}}',
      inStock: '{{integer(0, 2000)}}'
    }
  }
]
</code>```

Here is the result I get:

```<code>[
  {
    "id": "5ce82b1302c9777aac5fd681",
    "name": "Blake",
    "price": "$389.53",
    "availableColors": [],
    "weight": "3753.22",
    "inStock": 449
  },
  {
    "id": "5ce82b137ab9fe24eda22714",
    "name": "Felicia",
    "price": "$3,190.01",
    "availableColors": [],
    "weight": "3797.51",
    "inStock": 1288
  },
  {
    "id": "5ce82b135414eb7550aee368",
    "name": "Bettye",
    "price": "$227.41",
    "availableColors": [],
    "weight": "2182.52",
    "inStock": 1288
  },
  {
    "id": "5ce82b13f751e63a8506fbf2",
    "name": "Mullen",
    "price": "$3,306.81",
    "availableColors": [],
    "weight": "694.51",
    "inStock": 821
  },
  {
    "id": "5ce82b130544c7c08086a6bc",
    "name": "Angelita",
    "price": "$734.90",
    "availableColors": [],
    "weight": "3.44",
    "inStock": 226
  },
  {
    "id": "5ce82b130d9e2fc4c2a21e22",
    "name": "Mcknight",
    "price": "$3,582.76",
    "availableColors": [],
    "weight": "1183.82",
    "inStock": 1917
  },
  {
    "id": "5ce82b13fb509ee9c384a096",
    "name": "Nannie",
    "price": "$3,479.29",
    "availableColors": [],
    "weight": "754.85",
    "inStock": 716
  },
  {
    "id": "5ce82b13881cb29ec7a1772b",
    "name": "Sutton",
    "price": "$1,726.83",
    "availableColors": [],
    "weight": "1382.76",
    "inStock": 1911
  },
  {
    "id": "5ce82b1386ad13bffcf0923b",
    "name": "Maria",
    "price": "$1,679.58",
    "availableColors": [],
    "weight": "1106.28",
    "inStock": 5
  },
  {
    "id": "5ce82b13fccd87dbe6451971",
    "name": "Noble",
    "price": "$309.25",
    "availableColors": [],
    "weight": "1657.83",
    "inStock": 235
  }
]
</code>```

I expect the "availableColors" of any document to be an array of one to six predefined colors. Any idea?

答:
After having studied in deep the example provided in the home page of JSON Generator, I've found how to use its keywords to get the same result. By the way, following the schema of my document, I've added the way to randomly provide or not the value for all of the properties that are not required.

Here's the URL to the online editor: https://next.json-generator.com/4k8Wd87pU

Here is the code:

```<code>[{
  'repeat(5, 10)': {
    id: '{{objectId()}}',
    name: '{{firstName()}}',
    price(tags) {
      const nRequired = tags.integer(0, 5);
      if (nRequired) {
        return tags.floating(5, 4000, 2, "$0,0.00");
      }
    },
    availableColors(tags) {
      const nRequired = tags.integer(0, 3);
      if (!nRequired) return;
      const Colors = ['blue', 'brown', 'green', 'white', 'yellow', 'gray'];
      const nColors = tags.integer(0, Colors.length - 1); // generate a random integer from 0 to 5 will be used to select the total number of colors to add as values
      const aColors = [];
      for (j = 0; j <= nColors && !aColors[j]; j++) {
        let sColor = tags.integer(0, Colors.length - 1); // generate a random integer from 0 to 5 that will be used as index to select a random color from the Colors array
        if (aColors.indexOf(Colors[sColor]) == -1) {
          aColors.push(Colors[sColor]);
        }
      }
      return aColors;
    },
    weight(tags) {
      const nRequired = tags.integer(0, 5);
      if (nRequired) {
        return tags.floating(1, 900, 2, "0.00");
      }
    },
    inStock(tags) {
      const nRequired = tags.integer(0, 2);
      if (nRequired) {
        return tags.integer(0, 2000);
      }
    }
  }
}]
</code>```

Body:
I'm using JSON Generator https://next.json-generator.com to seed my MongoDB database. I'm finding trouble to generate a random set (from one to six) of colors out of the predefined group.

I've succeeded to generate all of the other property values but color. I need for the availableColors key to generate a random variable number of colors out of a predefined set of six: "blue", "brown", "green",  "white", "yellow", "gray".

Here is the URL to the online generator where it is possible to real-time edit it: https://next.json-generator.com/E1g60a1pL

Here is the code:

[
  {
    'repeat(5, 10)': {
      id: '{{objectId()}}',
      name: '{{firstName()}}',
      price: '{{floating(5, 4000, 2, "$0,0.00")}}',
      availableColors: (colors) => {
               var condition = '{{integer(1, 6)}}';
               var color = [];
               for (j = 0; j < condition+1; j++)
               {color [j] = '{{random("blue", "brown", "green",  "white", "yellow", "gray")}}';}
               let unique_array = [];
               for(let i = 0;i < color.length; i++) {
                   if(unique_array.indexOf(color[i]) == -1){
                      unique_array.push(color[i]);
                }
               }
               return unique_array;
},
      weight: '{{floating(1, 4000, 2, "0.00")}}',
      inStock: '{{integer(0, 2000)}}'
    }
  }
]

Here is the result I get:

[
  {
    "id": "5ce82b1302c9777aac5fd681",
    "name": "Blake",
    "price": "$389.53",
    "availableColors": [],
    "weight": "3753.22",
    "inStock": 449
  },
  {
    "id": "5ce82b137ab9fe24eda22714",
    "name": "Felicia",
    "price": "$3,190.01",
    "availableColors": [],
    "weight": "3797.51",
    "inStock": 1288
  },
  {
    "id": "5ce82b135414eb7550aee368",
    "name": "Bettye",
    "price": "$227.41",
    "availableColors": [],
    "weight": "2182.52",
    "inStock": 1288
  },
  {
    "id": "5ce82b13f751e63a8506fbf2",
    "name": "Mullen",
    "price": "$3,306.81",
    "availableColors": [],
    "weight": "694.51",
    "inStock": 821
  },
  {
    "id": "5ce82b130544c7c08086a6bc",
    "name": "Angelita",
    "price": "$734.90",
    "availableColors": [],
    "weight": "3.44",
    "inStock": 226
  },
  {
    "id": "5ce82b130d9e2fc4c2a21e22",
    "name": "Mcknight",
    "price": "$3,582.76",
    "availableColors": [],
    "weight": "1183.82",
    "inStock": 1917
  },
  {
    "id": "5ce82b13fb509ee9c384a096",
    "name": "Nannie",
    "price": "$3,479.29",
    "availableColors": [],
    "weight": "754.85",
    "inStock": 716
  },
  {
    "id": "5ce82b13881cb29ec7a1772b",
    "name": "Sutton",
    "price": "$1,726.83",
    "availableColors": [],
    "weight": "1382.76",
    "inStock": 1911
  },
  {
    "id": "5ce82b1386ad13bffcf0923b",
    "name": "Maria",
    "price": "$1,679.58",
    "availableColors": [],
    "weight": "1106.28",
    "inStock": 5
  },
  {
    "id": "5ce82b13fccd87dbe6451971",
    "name": "Noble",
    "price": "$309.25",
    "availableColors": [],
    "weight": "1657.83",
    "inStock": 235
  }
]

I expect the "availableColors" of any document to be an array of one to six predefined colors. Any idea?

Body:
After having studied in deep the example provided in the home page of JSON Generator, I've found how to use its keywords to get the same result. By the way, following the schema of my document, I've added the way to randomly provide or not the value for all of the properties that are not required.

Here's the URL to the online editor: https://next.json-generator.com/4k8Wd87pU

Here is the code:

[{
  'repeat(5, 10)': {
    id: '{{objectId()}}',
    name: '{{firstName()}}',
    price(tags) {
      const nRequired = tags.integer(0, 5);
      if (nRequired) {
        return tags.floating(5, 4000, 2, "$0,0.00");
      }
    },
    availableColors(tags) {
      const nRequired = tags.integer(0, 3);
      if (!nRequired) return;
      const Colors = ['blue', 'brown', 'green', 'white', 'yellow', 'gray'];
      const nColors = tags.integer(0, Colors.length - 1); // generate a random integer from 0 to 5 will be used to select the total number of colors to add as values
      const aColors = [];
      for (j = 0; j <= nColors && !aColors[j]; j++) {
        let sColor = tags.integer(0, Colors.length - 1); // generate a random integer from 0 to 5 that will be used as index to select a random color from the Colors array
        if (aColors.indexOf(Colors[sColor]) == -1) {
          aColors.push(Colors[sColor]);
        }
      }
      return aColors;
    },
    weight(tags) {
      const nRequired = tags.integer(0, 5);
      if (nRequired) {
        return tags.floating(1, 900, 2, "0.00");
      }
    },
    inStock(tags) {
      const nRequired = tags.integer(0, 2);
      if (nRequired) {
        return tags.integer(0, 2000);
      }
    }
  }
}]


问:
how to create a generic procedure in VHDL?
I have already written code for a generic Carry Look-Ahead Adder. but I can't convert this code to be a procedure in a package. can anyone help me do it?

when I try to compile this code, it does not register n as a generic number.

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity Carry_Look_Ahead is

    Generic(n:integer:=4);

Port ( A : in STD_LOGIC_VECTOR (n-1 downto 0);
B : in STD_LOGIC_VECTOR (n-1 downto 0);
Cin : in STD_LOGIC;
S : out STD_LOGIC_VECTOR (n-1 downto 0);
Cout : out STD_LOGIC);
end Carry_Look_Ahead;

architecture Behavioral of Carry_Look_Ahead is

begin

process(A,B,Cin)

variable ci :STD_LOGIC_VECTOR(n downto 0);
variable P: STD_LOGIC_VECTOR(n-1 downto 0);
variable G: STD_LOGIC_VECTOR(n-1 downto 0);
variable si :STD_LOGIC_VECTOR(n-1 downto 0);
          begin
       ci(0) := Cin;

FOR i IN 0 TO n-1 LOOP

  P(i) := A(i) xor B(i);
  G(i) := A(i) and B(i);
  ci(i+1) := G(i) or (P(i) and G(i));
  si(i) := P(i) xor ci(i);

 END LOOP;
    S<=si;
    Cout<=ci(n);
end process;

end Behavioral;
</code>```

This is the error I get when I try to compile this code:

```<code>Unknown identifier "n".
</code>```

答:
Subprograms like procedures can have generic parameters. The syntax and usage is similar to generic entities or generic packages.</p>

```<code>procedure cla
  generic (
    constant n  : in  positive
  )
  parameter (
    signal Cin    : in  STD_LOGIC;
    signal input1 : in  STD_LOGIC_VECTOR;
    signal input2 : in  STD_LOGIC_VECTOR;
    signal Sum    : out STD_LOGIC_VECTOR;
    signal Cout   : out STD_LOGIC
  ) is
  variable c : STD_LOGIC_VECTOR(n downto 0);
  variable P : STD_LOGIC_VECTOR(n-1 downto 0);
  variable G : STD_LOGIC_VECTOR(n-1 downto 0);
  variable s : STD_LOGIC_VECTOR(n-1 downto 0);
begin
  c(0) := Cin;
  for i in 0 to n-1 loop
     P(i) := input1(i) xor input2(i);
     G(i) := input1(i) and input2(i);
     c(i+1) := G(i) or (P(i) and G(i));
     s(i) := P(i) xor c(i);
  end loop;
  Sum  <=s;
  Cout <=c(n);
end procedure;
</code>```

Body:
I have already written code for a generic Carry Look-Ahead Adder. but I can't convert this code to be a procedure in a package. can anyone help me do it?

when I try to compile this code, it does not register n as a generic number.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity Carry_Look_Ahead is

    Generic(n:integer:=4);

Port ( A : in STD_LOGIC_VECTOR (n-1 downto 0);
B : in STD_LOGIC_VECTOR (n-1 downto 0);
Cin : in STD_LOGIC;
S : out STD_LOGIC_VECTOR (n-1 downto 0);
Cout : out STD_LOGIC);
end Carry_Look_Ahead;

architecture Behavioral of Carry_Look_Ahead is

begin

process(A,B,Cin)

variable ci :STD_LOGIC_VECTOR(n downto 0);
variable P: STD_LOGIC_VECTOR(n-1 downto 0);
variable G: STD_LOGIC_VECTOR(n-1 downto 0);
variable si :STD_LOGIC_VECTOR(n-1 downto 0);
          begin
       ci(0) := Cin;

FOR i IN 0 TO n-1 LOOP

  P(i) := A(i) xor B(i);
  G(i) := A(i) and B(i);
  ci(i+1) := G(i) or (P(i) and G(i));
  si(i) := P(i) xor ci(i);

 END LOOP;
    S<=si;
    Cout<=ci(n);
end process;

end Behavioral;

This is the error I get when I try to compile this code:

Unknown identifier "n".

Body:
Subprograms like procedures can have generic parameters. The syntax and usage is similar to generic entities or generic packages.

procedure cla
  generic (
    constant n  : in  positive
  )
  parameter (
    signal Cin    : in  STD_LOGIC;
    signal input1 : in  STD_LOGIC_VECTOR;
    signal input2 : in  STD_LOGIC_VECTOR;
    signal Sum    : out STD_LOGIC_VECTOR;
    signal Cout   : out STD_LOGIC
  ) is
  variable c : STD_LOGIC_VECTOR(n downto 0);
  variable P : STD_LOGIC_VECTOR(n-1 downto 0);
  variable G : STD_LOGIC_VECTOR(n-1 downto 0);
  variable s : STD_LOGIC_VECTOR(n-1 downto 0);
begin
  c(0) := Cin;
  for i in 0 to n-1 loop
     P(i) := input1(i) xor input2(i);
     G(i) := input1(i) and input2(i);
     c(i+1) := G(i) or (P(i) and G(i));
     s(i) := P(i) xor c(i);
  end loop;
  Sum  <=s;
  Cout <=c(n);
end procedure;


问:
PHP DOM in WordPress - replace and add attribute
I try to change type attribute of input fields to number (they have hidden type by default) and add readonly="readonly", but it has no effect on output HTML. Attributes are as they were.

Function is triggered properly, because before I added encoding, it showed incorrect characters on page. I have proper CSS to format readonly inputs, so visuals are not a problem, I will also use more conditions to find only specific input tags, but for now I would like to get this code to work properly:

```<code>add_filter('the_content', 'acau_lock_input');
function acau_lock_input($content) {
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));

    foreach ($dom->getElementsByTagName('input') as $node) {
        $node->setAttribute('type', 'number');
        $node->setAttribute('readonly', 'readonly');
    }
    $newHtml = $dom->saveHtml();
    return $newHtml;
}
</code>```

答:
Nigel Ren helped me to find the problem. The solution is ridiculous, the_content filter of WordPress is simply whatever is placed in the text area of the current page as visible in the editor.

It has nothing to do with full HTML structure of output page, so while wrong encoding can break text of the whole page, $content returns only one shortcode because this is in the page editor.

To learn how to edit DOM for WordPress, including the output of all templates, check this question:

PHP DOM in WordPress - add attribute in output buffer HTML

Body:
I try to change type attribute of input fields to number (they have hidden type by default) and add readonly="readonly", but it has no effect on output HTML. Attributes are as they were.

Function is triggered properly, because before I added encoding, it showed incorrect characters on page. I have proper CSS to format readonly inputs, so visuals are not a problem, I will also use more conditions to find only specific input tags, but for now I would like to get this code to work properly:

add_filter('the_content', 'acau_lock_input');
function acau_lock_input($content) {
    $dom = new DOMDocument();
    @$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));

    foreach ($dom->getElementsByTagName('input') as $node) {
        $node->setAttribute('type', 'number');
        $node->setAttribute('readonly', 'readonly');
    }
    $newHtml = $dom->saveHtml();
    return $newHtml;
}


问:
How can I refactor this ASYNC call in my react component to make it more readable?
I want my component to fetch an array of objects from the server. Each object is a message with author, body and date. I then want to render these messages in my react component.

My react component currently fetches data from the server before mounting. It will then store this message list in the redux state.|

I'm sure there's a better way of writing this code.
1. Can I place the fetch request in either the Action or Reducer file?
2. Can I write a function in the component to make the async call?

```<code>import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// Actions
import { fetchMessages } from '../actions/actions_index.js';

class MessageList extends Component {
  constructor(props) {
    super(props)
  }

  componentWillMount() {
    fetch('https://wagon-chat.herokuapp.com/general/messages')
        .then(response => response.json(),
          error => console.log('An error occured receiving messages', error))
        .then((data) => {
          this.props.fetchMessages(data.messages);
        });
  }

  render() {
    return (
      <div className="message-list">
        {this.props.messageList.map( (message, index) => { return <Message key={index} message={message}/> })}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    messageList: state.messageList
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    { fetchMessages: fetchMessages },
    dispatch
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(MessageList);

</code>```

答:
You could use redux-thunk in an action called getMessages.

So:
(The double arrow func, is to return an action, see redux-thunk)

```<code>const getMessages = ()=>(dispatch, getState)=>{
    fetch('https://wagon-chat.herokuapp.com/general/messages')
    .then(response => response.json(),
      error => dispatch(['error', error]))
    .then((data) => {
      dispatch(data);
    })
}
</code>```

Then you've successfully reduced your component to:

```<code>componentWillMount(){
    this.props.getMessages()
}
</code>```

Body:
I want my component to fetch an array of objects from the server. Each object is a message with author, body and date. I then want to render these messages in my react component.

My react component currently fetches data from the server before mounting. It will then store this message list in the redux state.|

I'm sure there's a better way of writing this code.
1. Can I place the fetch request in either the Action or Reducer file?
2. Can I write a function in the component to make the async call?

import React, { Component } from 'react';
import Message from '../components/message.jsx';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
// Actions
import { fetchMessages } from '../actions/actions_index.js';

class MessageList extends Component {
  constructor(props) {
    super(props)
  }

  componentWillMount() {
    fetch('https://wagon-chat.herokuapp.com/general/messages')
        .then(response => response.json(),
          error => console.log('An error occured receiving messages', error))
        .then((data) => {
          this.props.fetchMessages(data.messages);
        });
  }

  render() {
    return (

        {this.props.messageList.map( (message, index) => { return <Message key={index} message={message}/> })}

    )
  }
}

function mapStateToProps(state) {
  return {
    messageList: state.messageList
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    { fetchMessages: fetchMessages },
    dispatch
  )
}

export default connect(mapStateToProps, mapDispatchToProps)(MessageList);

Body:
You could use redux-thunk in an action called getMessages.

So:
(The double arrow func, is to return an action, see redux-thunk)

const getMessages = ()=>(dispatch, getState)=>{
    fetch('https://wagon-chat.herokuapp.com/general/messages')
    .then(response => response.json(),
      error => dispatch(['error', error]))
    .then((data) => {
      dispatch(data);
    })
}

Then you've successfully reduced your component to:

componentWillMount(){
    this.props.getMessages()
}


问:
Record Video in a Service
Is it possible to record video in a service, that is without setting the setPreviewDisplay?
I tried it on a HTC Desire, however it is throwing this info in the log,

MediaRecorder Prepare Failed: -1

CameraInput No surface is available for display

Is there some additional properties to be set?

答:
I found this snippet somewhere. Not sure if it works for media recorder, but it was working reasonably well for camera.takePicture on HTC hero android 2.1-update1 (and simulator).</p>

```<code>if (camera == null) {
    Log.i(TAG, "Opening camera");
    camera = Camera.open();
}

SurfaceView view = new SurfaceView(new DummyContext()); //You'll have to create your own class extending Context
camera.setPreviewDisplay(view.getHolder());
camera.startPreview();

//wait
Log.i(TAG, "Wait for cam");
    try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    Log.e(TAG, "Woken violently");
    e.printStackTrace();
}

//take pic
Log.i(TAG, "Take pic");
camera.takePicture(shutterCallback, rawCallback, jpegCallback);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Record Video in a Service

Body:
I found this snippet somewhere. Not sure if it works for media recorder, but it was working reasonably well for camera.takePicture on HTC hero android 2.1-update1 (and simulator).

if (camera == null) {
    Log.i(TAG, "Opening camera");
    camera = Camera.open();
}

SurfaceView view = new SurfaceView(new DummyContext()); //You'll have to create your own class extending Context
camera.setPreviewDisplay(view.getHolder());
camera.startPreview();

//wait
Log.i(TAG, "Wait for cam");
    try {
    Thread.sleep(2000);
} catch (InterruptedException e) {
    Log.e(TAG, "Woken violently");
    e.printStackTrace();
}

//take pic
Log.i(TAG, "Take pic");
camera.takePicture(shutterCallback, rawCallback, jpegCallback);


问:
How to pass Data Objects from Room DB to WorkManager class
There is the dialog that saves an object to the Room database. The dialog should wait for saving to the database in order to run a special Worker class, that will retrieve this object from the database by ID and do some work with it.

But this requires synchronous code that is an anti-pattern in Room. I decided that the best option would be to run WorkManager, which will save the object to the database, and then run a special Worker class through the chain. But the problem is that I can't pass an object to save in Data.Builder, only primitive types. Only serialization variant in JSON remains. Is it possible to do without serialization? After all, the size of the serialized JSON, in theory, can exceed the limit of 10240 bytes.

Any help would be greatly appreciated!

答: You will need to pass them by reference. So if you have an Room Entity grab its key / id and pass it as an input to the Worker by using setInputData in {OneTime|Periodic}WorkRequest.Builder and you can then query for the actual Room Entity in the implementation of the Worker.


问:
Slicer to slice particular columns only in PowerBI
I'm trying to create some dynamic charts in power BI.

My data looks like this:

```<code>year    Product  exp    claim_type  clCost     clCount
2010    A    0.21               0             0
2010    A    0.85               0             0
2010    A    0.15   BI          5000          1
2010    B    1.00   BI          1000          1
2010    B    0.33               0             0
2011    B    0.96               0             0
2011    B    0.16   BI          200           1
2011    B    1.00   MD          2500          1
2011    A    1.00               0             0
2011    A    0.91   MD          6000          1
</code>```

End goal is have a chart with the x axis being "Year", and Y axis being the sum(clCount)/sum(exp) and two lines for product A,B.
But in powerBI I want to be able to filter by claim type. So I want to only select certain rows for clCount to sum up, but sum up all the rows for exp. (Per group)

So for example, with a slicer, someone can click "BI", and the resulting value for the 2010 year andproduct A would be sum(clCount) = 1 and sum(exp) = .21+.85+.15

And for product B, similarly for the 2010 year sum(clCount) = 1 and sum(exp) = 1+.33

And ofcourse the same for the 2011 year...

Now the issue is, if I put a Slicer for the variable claim_type, and choose BI, it sums up the clCount per year correctly, but the exp, it only sums it up for the rows that contain "BI" (ie for 2010 and product the exp will only be .15 instead of .21+.85+.15. I need the sum(exp) to be of the year and product as the denominator.

Any ideas on how this can be done?

答:
Seems to me Power Bi is correct, you ask it to filter on BI, so you get only the row of 0.15. for the year 2010 product A.

You think it sums up correctly on clCount but this is not the case, you get one row which has the value 1. When you change the zero values of clCount, you will see it still gives you 1 as result.

If you want your slicer to work corrcect, you need to fill in your type in all rows.

Body:
I'm trying to create some dynamic charts in power BI.

My data looks like this:

year    Product  exp    claim_type  clCost     clCount
2010    A    0.21               0             0
2010    A    0.85               0             0
2010    A    0.15   BI          5000          1
2010    B    1.00   BI          1000          1
2010    B    0.33               0             0
2011    B    0.96               0             0
2011    B    0.16   BI          200           1
2011    B    1.00   MD          2500          1
2011    A    1.00               0             0
2011    A    0.91   MD          6000          1

End goal is have a chart with the x axis being "Year", and Y axis being the sum(clCount)/sum(exp) and two lines for product A,B.
But in powerBI I want to be able to filter by claim type. So I want to only select certain rows for clCount to sum up, but sum up all the rows for exp. (Per group)

So for example, with a slicer, someone can click "BI", and the resulting value for the 2010 year andproduct A would be sum(clCount) = 1 and sum(exp) = .21+.85+.15

And for product B, similarly for the 2010 year sum(clCount) = 1 and sum(exp) = 1+.33

And ofcourse the same for the 2011 year...

Now the issue is, if I put a Slicer for the variable claim_type, and choose BI, it sums up the clCount per year correctly, but the exp, it only sums it up for the rows that contain "BI" (ie for 2010 and product the exp will only be .15 instead of .21+.85+.15. I need the sum(exp) to be of the year and product as the denominator.

Any ideas on how this can be done?


问:
Accessing previously returned value from each?
In C# I can write something like this:

int? valueForNewColumeInPreviousRecord = null;

myTable.AddColumn("New Column Name", (record) => {
                                        int newColumeValue;
                                        newColumeValue = valueForNewColumeInPreviousRecord.HasValue ?
                                                            valueForNewColumeInPreviousRecord.Value + record.SomeOtherValue :
                                                            record.SomeOtherValue;

                                        valueForNewColumeInPreviousRecord = newColumeValue;

                                        return newColumeValue;
                                    } + 42);

```

NOTE: The + 42 part, which makes it impossible to read/get/access the last returned value from any record in the table.

How would I go about doing this in Power Query?
Or is there a completely different way of doing this kind of stuff there?

I'm not interested in actually adding a new column to a table, but the actual concept of accessing previously returned/calculated data from a lambda/each, and if possible, how you can store data in a variable.

The table thing is just a great concrete example where you might want to do something like that.

答:
You can do it, but with big tables is very slow. Let's see it with a running total example.

Take a table named "Source" with a "Values" column with numbers to accumulate.

First thing to do is to add an index column.

```<code>Indexed = Table.AddIndexColumn(Source, "Index"),
</code>```

Then, and following your question, a new column named "RunTot" is added. Each value of this new column will be the number from "Values" of this row plus the previous running total ("RunTot"). The trick is the "@" symbol before this part "@Output[RunTot]{[Index]-1}", this way you are calling the previous element of the column you are constructing.

"try ... otherwise" is just a way to avoid the error you get when you pass a negative index to a list.

Last, "Table.Buffer" is a way to speed up thinks a bit.

```<code>Output = Table.Buffer(Table.AddColumn(Indexed, "RunTot", each [Values] + (try @Output[RunTot]{[Index]-1} otherwise 0)))
</code>```

But as Alexis propose, it's much better the "List.Generat" approach. This is a running total function using List.Generate:

```<code>fnListGenerateRunningTotal = (Input as list) as list =>
List.Generate(
        ()=> [Total = Input{0}, Counter = 0],
        each [Counter] < List.Count(Input),
        each [Total = Input{Counter} + [Total], Counter = [Counter] + 1],
        each [Total]
    )
</code>```

Body:
In C# I can write something like this:

int? valueForNewColumeInPreviousRecord = null;

myTable.AddColumn("New Column Name", (record) => {
                                        int newColumeValue;
                                        newColumeValue = valueForNewColumeInPreviousRecord.HasValue ?
                                                            valueForNewColumeInPreviousRecord.Value + record.SomeOtherValue :
                                                            record.SomeOtherValue;

                                        valueForNewColumeInPreviousRecord = newColumeValue;

                                        return newColumeValue;
                                    } + 42);

NOTE: The + 42 part, which makes it impossible to read/get/access the last returned value from any record in the table.

How would I go about doing this in Power Query?
Or is there a completely different way of doing this kind of stuff there?

I'm not interested in actually adding a new column to a table, but the actual concept of accessing previously returned/calculated data from a lambda/each, and if possible, how you can store data in a variable.

The table thing is just a great concrete example where you might want to do something like that.

Body:
You can do it, but with big tables is very slow. Let's see it with a running total example.

Take a table named "Source" with a "Values" column with numbers to accumulate.

First thing to do is to add an index column.

Indexed = Table.AddIndexColumn(Source, "Index"),

Then, and following your question, a new column named "RunTot" is added. Each value of this new column will be the number from "Values" of this row plus the previous running total ("RunTot"). The trick is the "@" symbol before this part "@Output[RunTot]{[Index]-1}", this way you are calling the previous element of the column you are constructing.

"try ... otherwise" is just a way to avoid the error you get when you pass a negative index to a list.

Last, "Table.Buffer" is a way to speed up thinks a bit.

Output = Table.Buffer(Table.AddColumn(Indexed, "RunTot", each [Values] + (try @Output[RunTot]{[Index]-1} otherwise 0)))

But as Alexis propose, it's much better the "List.Generat" approach. This is a running total function using List.Generate:

fnListGenerateRunningTotal = (Input as list) as list =>
List.Generate(
        ()=> [Total = Input{0}, Counter = 0],
        each [Counter] < List.Count(Input),
        each [Total = Input{Counter} + [Total], Counter = [Counter] + 1],
        each [Total]
    )


问:
How to loop around the ascii values of the alphabet in Matlab
I am new to Matlab and am having trouble using the mod function.

I am given a scrambled vector of lowercase characters and a shift value that can be positive or negative that I am supposed to add to the vector
I am supposed to use the mod function to wrap around the lowercase letters in the alphabet.
For example, if the letter is 'a' and the shift amount if 4 the letter will then become 'e'.
A negative means shifting towards 'a' in the alphabet.
 The Shift should 'wrap' around the alphabet- 'x' shifted by 7 should become 'e'.

I have tried writing conditionals using if and elseif statements but I am supposed to use the mod function instead of conditionals.

答:
mod(x,y) is the remainder of the division of x and y, having the same sign as y. Thus, given negative x, the sign is still positive. This is different from how mod is defined in other languages.

I obviously y must be the number of characters in the range a-z. x is the 0-based index to the shifted character, which should be 0 for “a”, and y-1 for “z”. You can get this by simple subtracting the ASCII value of “a”:

```<code>letter - 'a'
</code>```

Note that 'a' is a char that implicitly converts to the ASCII value of the letter in arithmetic operations.

The result of the mod operation then again returns one such index, which you can turn into a character by adding the ASCII value of “a”:

```<code>char(index + 'a')
</code>```

Putting it all together:

```<code>char(mod(letter-'a', 'z'-'a'+1) + 'a')
</code>```

Instead of letter you can use a vector of letters (char array) in that expression.

Body:
mod(x,y) is the remainder of the division of x and y, having the same sign as y. Thus, given negative x, the sign is still positive. This is different from how mod is defined in other languages.

I obviously y must be the number of characters in the range a-z. x is the 0-based index to the shifted character, which should be 0 for “a”, and y-1 for “z”. You can get this by simple subtracting the ASCII value of “a”:

letter - 'a'

Note that 'a' is a char that implicitly converts to the ASCII value of the letter in arithmetic operations.

The result of the mod operation then again returns one such index, which you can turn into a character by adding the ASCII value of “a”:

char(index + 'a')

Putting it all together:

char(mod(letter-'a', 'z'-'a'+1) + 'a')

Instead of letter you can use a vector of letters (char array) in that expression.


问:
jquery tooltip on dynamic element
I use this tooltip plugin to make the tooltip on element as

```<code>$('.showtooltip').tooltip({
            delay: 0,
            track: true,
            showURL: false,
            bodyHandler: function() {
                var tipStr = "SOME DISPLAY HTML";
                return $(tipStr);
            }
        });
</code>```

And my ajax create element dynamically.

```<code>$("<img alt='' class='showtooltip' src='image.jpg' />");
</code>```

so when this image is added to document. The tooltip doesn't display.
Then I use live() in jquery :

```<code>$(".showtooltip").live("mouseover", function() {
                $(this).tooltip({
                    delay: 0,
                    track: true,
                    showURL: false,
                    bodyHandler: function() {
                        var tipStr = "SOME DISPLAY HTML";
                        return $(tipStr);
                    }
                })
            });
</code>```

But tooltip only display after the first time mouse over the image.
How can i use tooltip on dynamic element ?

答:
I used something like this to rebind after an ajax call. It may help.

```<code>$(".showtooltip").live("mouseover",function(){
   if (!$(this).hasClass("tooledUp")){
      $(this).tooltip({
                delay: 0,
                track: true,
                showURL: false,
                bodyHandler: function() {
                    var tipStr = "SOME DISPLAY HTML";
                    return $(tipStr);
                }
      });
      $(this).tooltip().show();
      $(this).addClass("tooledUp");
   }
});
</code>```

From the forum here: http://static.flowplayer.org/tools/forum/30/37281

Title: jquery tooltip on dynamic element

Body:
I use this tooltip plugin to make the tooltip on element as

$('.showtooltip').tooltip({
            delay: 0,
            track: true,
            showURL: false,
            bodyHandler: function() {
                var tipStr = "SOME DISPLAY HTML";
                return $(tipStr);
            }
        });

And my ajax create element dynamically.

$("");

so when this image is added to document. The tooltip doesn't display.
Then I use live() in jquery :

$(".showtooltip").live("mouseover", function() {
                $(this).tooltip({
                    delay: 0,
                    track: true,
                    showURL: false,
                    bodyHandler: function() {
                        var tipStr = "SOME DISPLAY HTML";
                        return $(tipStr);
                    }
                })
            });

But tooltip only display after the first time mouse over the image.
How can i use tooltip on dynamic element ?

Body:
I used something like this to rebind after an ajax call. It may help.

$(".showtooltip").live("mouseover",function(){
   if (!$(this).hasClass("tooledUp")){
      $(this).tooltip({
                delay: 0,
                track: true,
                showURL: false,
                bodyHandler: function() {
                    var tipStr = "SOME DISPLAY HTML";
                    return $(tipStr);
                }
      });
      $(this).tooltip().show();
      $(this).addClass("tooledUp");
   }
});

From the forum here: http://static.flowplayer.org/tools/forum/30/37281


问:
How to efficiently store pairs of numbers in a set?
In my program, I need to store pairs of numbers in range [1, 10**5) in a set and look them up many times. I can add them to the set as tuples:

```<code>seen = set()
seen.add((x, y))
(x, y) in seen  # True
</code>```

but is there a more efficient way, e.g. using a numeric/string key that is a combination of two numbers?

答: AFAIK OP's way is pretty much the most efficient. Sets hash their contents and that makes lookups have constant complexity, while tuple as the inner structure is small and fast, it is not wothwhile to use a frozenset (which is hashable and therefore can be an element of a set) for just a pair of values. So unless youhave a problem with the tuples being in order (not orderless), you are good.</p>

Body:
In my program, I need to store pairs of numbers in range [1, 10**5) in a set and look them up many times. I can add them to the set as tuples:

seen = set()
seen.add((x, y))
(x, y) in seen  # True

but is there a more efficient way, e.g. using a numeric/string key that is a combination of two numbers?


问:
Maven Unable to Find AEM Archetype
I've been starting at this problem for way to long... Im working through the Adobe wknd project and I can't get pass this command and most of the work is built off of it

```<code>mvn archetype:generate \
  -DarchetypeGroupId=com.adobe.granite.archetypes \
  -DarchetypeArtifactId=aem-project-archetype \
  -DarchetypeVersion=18
</code>```

I've tried it on the VPN and off, with all possible proxy configs and still getting the same error of

```<code>Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)
</code>```

Deleting and reinstalling multiple times. Different networks and proxy configs as well Mac OS.

mvn -v returns

```<code>Maven home: /Users/dmills/Applications/apache-maven-3.6.1
Java version: 1.8.0_212, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "mac"
</code>```

Get this error

```<code>Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)
</code>```

Build is failing and I don't know where to go now

答:
In the Adobe profile the 'settings' xml tag is missing:</p>

```<code><settings
xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">

 <profiles>
     <profile>

      .....

     </profile>
   </profiles>
</settings>
</code>```

Title: Maven Unable to Find AEM Archetype

Body:
I've been starting at this problem for way to long... Im working through the Adobe wknd project and I can't get pass this command and most of the work is built off of it

mvn archetype:generate \
  -DarchetypeGroupId=com.adobe.granite.archetypes \
  -DarchetypeArtifactId=aem-project-archetype \
  -DarchetypeVersion=18

I've tried it on the VPN and off, with all possible proxy configs and still getting the same error of

Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)

Deleting and reinstalling multiple times. Different networks and proxy configs as well Mac OS.

mvn -v returns

Maven home: /Users/dmills/Applications/apache-maven-3.6.1
Java version: 1.8.0_212, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_212.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.5", arch: "x86_64", family: "mac"

Get this error

Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.1.0:generate (default-cli) on project standalone-pom: The desired archetype does not exist (com.adobe.granite.archetypes:aem-project-archetype:18)

Build is failing and I don't know where to go now

Body:
In the Adobe profile the 'settings' xml tag is missing:

<settings
xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">

 <profiles>
     <profile>

      .....

     </profile>
   </profiles>
</settings>


问:
React, Javascript - Could not find "store" in the context of "Connect(App)"
I am trying to add propTypes and mapStateToProps to App.js component for React-intl. But it says Could not find "store" in the context of "Connect(App)".

My App.js

```<code>import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import jwt_decode from "jwt-decode";
import setAuthToken from "./utils/setAuthToken";
import { setCurrentUser, logoutUser } from "./actions/authActions";
import PropTypes from "prop-types";
import { connect } from "react-redux";

import { Provider } from "react-redux";
import store from "./store";

import PrivateRoute from "./components/common/PrivateRoute";

import Navbar from "./components/layout/Navbar";
import Footer from "./components/layout/Footer";
import Register from "./components/auth/Register";
import Login from "./components/auth/Login";
import Main from "./components/main/Main";
import Account from "./components/main/Account";

import { IntlProvider } from "react-intl";
import "./App.css";

// Check for token
if (localStorage.jwtToken) {
  // Set auth token header auth
  setAuthToken(localStorage.jwtToken);
  // Decode token and get user info and exp
  const decoded = jwt_decode(localStorage.jwtToken);
  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));

  // Check for expired token
  const currentTime = Date.now() / 1000;
  if (decoded.exp < currentTime) {
    // Logout user
    store.dispatch(logoutUser());
    // TODO: Clear current Profile

    // Redirect to login
    window.location.href = "/login";
  }
}

class App extends Component {
  render() {
    const { lang } = this.props;
    return (
      <Provider store={store}>
        <Router>
          <IntlProvider locale={lang}>
            <div className="App">
              <Navbar />
              <Route exact path="/" component={Register} />
              <Route exact path="/login" component={Login} />
              <Switch>
                <PrivateRoute exact path="/dashboard" component={Main} />
                <PrivateRoute exact path="/account" component={Account} />
              </Switch>
              <Footer />
            </div>
          </IntlProvider>
        </Router>
      </Provider>
    );
  }
}

App.propTypes = {
  lang: PropTypes.string.isRequired
};

const mapStateToProps = state => ({
  lang: state.locale.lang
});

export default connect(mapStateToProps)(App);

</code>```

Says "Could not find "store" in the context of "Connect(App)". Either wrap the root component in a , or pass a custom React context provider to  and the corresponding React context consumer to Connect(App) in connect options."

答:
Try to move <Provider /> and <Router /> to index.js

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Route } from 'react-router-dom';
import App from './App';
import store from './store';

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>, document.getElementById('root'));
</code>```

App.js

```<code>class App extends Component {
  render() {
    const { lang } = this.props;
    return (
          <IntlProvider locale={lang}>
            <div className="App">
              <Navbar />
              <Route exact path="/" component={Register} />
              <Route exact path="/login" component={Login} />
              <Switch>
                <PrivateRoute exact path="/dashboard" component={Main} />
                <PrivateRoute exact path="/account" component={Account} />
              </Switch>
              <Footer />
            </div>
          </IntlProvider>
    );
  }
}
</code>```

Body:
I am trying to add propTypes and mapStateToProps to App.js component for React-intl. But it says Could not find "store" in the context of "Connect(App)".

My App.js

import React, { Component } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import jwt_decode from "jwt-decode";
import setAuthToken from "./utils/setAuthToken";
import { setCurrentUser, logoutUser } from "./actions/authActions";
import PropTypes from "prop-types";
import { connect } from "react-redux";

import { Provider } from "react-redux";
import store from "./store";

import PrivateRoute from "./components/common/PrivateRoute";

import Navbar from "./components/layout/Navbar";
import Footer from "./components/layout/Footer";
import Register from "./components/auth/Register";
import Login from "./components/auth/Login";
import Main from "./components/main/Main";
import Account from "./components/main/Account";

import { IntlProvider } from "react-intl";
import "./App.css";

// Check for token
if (localStorage.jwtToken) {
  // Set auth token header auth
  setAuthToken(localStorage.jwtToken);
  // Decode token and get user info and exp
  const decoded = jwt_decode(localStorage.jwtToken);
  // Set user and isAuthenticated
  store.dispatch(setCurrentUser(decoded));

  // Check for expired token
  const currentTime = Date.now() / 1000;
  if (decoded.exp < currentTime) {
    // Logout user
    store.dispatch(logoutUser());
    // TODO: Clear current Profile

    // Redirect to login
    window.location.href = "/login";
  }
}

class App extends Component {
  render() {
    const { lang } = this.props;
    return (
      <Provider store={store}>
        <Router>
          <IntlProvider locale={lang}>

              <Navbar />
              <Route exact path="/" component={Register} />
              <Route exact path="/login" component={Login} />
              <Switch>
                <PrivateRoute exact path="/dashboard" component={Main} />
                <PrivateRoute exact path="/account" component={Account} />
              </Switch>

          </IntlProvider>
        </Router>
      </Provider>
    );
  }
}

App.propTypes = {
  lang: PropTypes.string.isRequired
};

const mapStateToProps = state => ({
  lang: state.locale.lang
});

export default connect(mapStateToProps)(App);

Says "Could not find "store" in the context of "Connect(App)". Either wrap the root component in a , or pass a custom React context provider to  and the corresponding React context consumer to Connect(App) in connect options."

Body:
Try to move <Provider /> and <Router /> to index.js

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Route } from 'react-router-dom';
import App from './App';
import store from './store';

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store}>
      <Route component={App} />
    </Provider>
  </BrowserRouter>, document.getElementById('root'));

App.js

class App extends Component {
  render() {
    const { lang } = this.props;
    return (
          <IntlProvider locale={lang}>
            <div className="App">
              <Navbar />
              <Route exact path="/" component={Register} />
              <Route exact path="/login" component={Login} />
              <Switch>
                <PrivateRoute exact path="/dashboard" component={Main} />
                <PrivateRoute exact path="/account" component={Account} />
              </Switch>
              <Footer />
            </div>
          </IntlProvider>
    );
  }
}


问:
Please help with wordpress hide input if empty with custom field
I made a slider what i can hide if is check a check box.

I even gave it an input where you can add the folder locaton, but i cant make it to hide if the folder is empty or its not correct

this is the code

```<code><?php if(is_category(7) || is_page(11) && get_post_meta($post->ID, 'm_slider', true) == 'true' || 11 == $post->post_parent && get_post_meta($post->ID, 'm_slider', true) == 'true') {?>
<div id='slider_bg'>
</div><!-- slider_bg -->
<div id='slider_img'>
<div class="slider" >
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/1.jpg'>
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/2.jpg'>
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/3.jpg'>
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/4.jpg'>

</div>
</div>
<?php } ?>
</code>```

i tryed to give it to a variable and if its empty than hide it not working i tryed wit if(get_post_meta($post->ID, 'main_folder', true) !== '')

and that doesnt work either, could please someone give me a hint what im missin?

答:
You could try :</p>

```<code>$themeRoot = get_theme_root();
$meta = get_post_meta($post->ID, 'main_folder', true);
if ( !empty($meta) && is_dir($themeRoot . '/slider/' . $meta) )
{
    # test here if the folder is empty or not and act acordingly
    #  http://iarematt.com/php-code-to-check-if-a-directory-is-empty/
}
</code>```

Body:
I made a slider what i can hide if is check a check box.

I even gave it an input where you can add the folder locaton, but i cant make it to hide if the folder is empty or its not correct

this is the code

<?php if(is_category(7) || is_page(11) && get_post_meta($post->ID, 'm_slider', true) == 'true' || 11 == $post->post_parent && get_post_meta($post->ID, 'm_slider', true) == 'true') {?>

<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/1.jpg'>
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/2.jpg'>
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/3.jpg'>
<img src='<?php bloginfo('template_url'); ?>/slider/<?php echo get_post_meta($post->ID, 'main_folder', true); ?>/4.jpg'>

<?php } ?>

i tryed to give it to a variable and if its empty than hide it not working i tryed wit if(get_post_meta($post->ID, 'main_folder', true) !== '')

and that doesnt work either, could please someone give me a hint what im missin?

Body:
You could try :

$themeRoot = get_theme_root();
$meta = get_post_meta($post->ID, 'main_folder', true);
if ( !empty($meta) && is_dir($themeRoot . '/slider/' . $meta) )
{
    # test here if the folder is empty or not and act acordingly
    #  http://iarematt.com/php-code-to-check-if-a-directory-is-empty/
}


答:
It looks like combining numbers is the fastest method (about 2x faster than using tuples in my test):

```<code>seen = set()
seen.add(x*10**5+y)
x*10**5+y in seen  # True
</code>```

P.S. to test it I used %timeit in ipython on these two functions:

```<code>def f1():
    seen = set()
    for x in range(1000):
        for y in range(1000):
            seen.add((x, y))
            assert (x, y) in seen

def f2():
    seen = set()
    for x in range(1000):
        for y in range(1000):
            seen.add(x*10**5+y)
            assert x*10**5+y in seen
</code>```

Results:

```<code>In [2]: %timeit f1()
466 ms ± 1.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit f2()
254 ms ± 1.63 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Title: How to efficiently store pairs of numbers in a set?

Body:
It looks like combining numbers is the fastest method (about 2x faster than using tuples in my test):

seen = set()
seen.add(x*10**5+y)
x*10**5+y in seen  # True

P.S. to test it I used %timeit in ipython on these two functions:

def f1():
    seen = set()
    for x in range(1000):
        for y in range(1000):
            seen.add((x, y))
            assert (x, y) in seen

def f2():
    seen = set()
    for x in range(1000):
        for y in range(1000):
            seen.add(x*10**5+y)
            assert x*10**5+y in seen

Results:

In [2]: %timeit f1()
466 ms ± 1.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit f2()
254 ms ± 1.63 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Output HTML depending on the current time of user
I would like to do the following:

if time is between 7am-12pm (mon-sat) then output html code else output something else.

I currently have tried: (ignore the time in the code, this was just for testing purposes - I still want it to do be done for 7am-12pm)

```<code><script>
            var today = new Date()
var curHr = today.getHours()

if (curHr < 12) {
  phoneText .innerHTML="<div class='col-sm-6 col-md-3'><div class='support-box'><div class='icon green'><i class='fas fa-comments'></i></div><div class='details-holder'><div class='title'>Live Chat</div><a href='javascript:$zopim.livechat.window.show();' style='color:white;'>Start a live chat</a></div></div>";
} else if (curHr < 18) {
  phoneText .innerHTML="<div class='col-sm-6 col-md-3'><div class='support-box'><div class='icon green'><i class='fas fa-comments'></i></div><div class='details-holder'><div class='title'>Live Chat</div><a href='javascript:$zopim.livechat.window.show();' style='color:white;'>Start a live chat</a></div></div>";
} else {
  phoneText .innerHTML="<div class='col-sm-6 col-md-3'><div class='support-box'><div class='icon green'><i class='fas fa-comments'></i></div><div class='details-holder'><div class='title'>Live Chat</div><a href='javascript:$zopim.livechat.window.show();' style='color:white;'>Start a live chat</a></div></div>";
}</script>
</code>```

I then have

答:
Try this

https://jsfiddle.net/opecmshb/2/

I used curHr = 11 for example because in my jsfiddle var curHr = today.getHours() didn't work

Body:
I would like to do the following:

if time is between 7am-12pm (mon-sat) then output html code else output something else.

I currently have tried: (ignore the time in the code, this was just for testing purposes - I still want it to do be done for 7am-12pm)

I then have


问:
How do you test an HTTP server running on a Compute Engine instance without exposing it to the public?
I am using a Compute Engine as my main development machine, I would like to start testing my application, however, if I assign it an external IP address then it will be open to the public web which is a privacy concern of mine.

Assuming that I will not be accessing this instance from the same IP address  every time, how can I go about being able to test HTTP requests for the development that I am doing?

答:
You can use ssh port forwarding to set up a proxy from your laptop to the machine. If you are using Mac or Linux ssh, something like the following should work to forward port 8080 from your local machine to the VM (from the gcloud docs):

```<code>gcloud compute ssh --ssh_flag="-L 80:%INSTANCE%:80"
</code>```

Once you've set this up, you can access the server at http://localhost: 8080/ on your laptop.

Body:
You can use ssh port forwarding to set up a proxy from your laptop to the machine. If you are using Mac or Linux ssh, something like the following should work to forward port 8080 from your local machine to the VM (from the gcloud docs):

gcloud compute ssh --ssh_flag="-L 80:%INSTANCE%:80"

Once you've set this up, you can access the server at http://localhost: 8080/ on your laptop.


问:
How do I get the contents of a list as a string?
This is st[0:6], which is my list (actually it is traces).

I can get some trace by numbers, e.g. st[3], but I want to get some trace by string, for example the data for ADK.10.

I know this name (ADK), but now I don't know this index number.

The 6 Trace(s) in Stream are below:

```<code>II.AAK.00.BHZ | 2010-02-18T01:19:08.019500Z

II.AAK.10.BHZ | 2010-02-18T01:19:08.019500Z

IU.ADK.00.BHZ | 2010-02-18T01:18:31.019536Z

IU.ADK.10.BHZ | 2010-02-18T01:18:31.019536Z

IU.AFI.00.BHZ | 2010-02-18T01:23:13.023144Z

IU.AFI.10.BHZ | 2010-02-18T01:23:13.010644Z
</code>```

I tried this code below, but I'm getting an error:

tr = st['*.RSSD.00.*']

I want to get the RSSD.00 data to tr. What should I do?

答:
I don't know what do you mean by data, but you can extract it with regular expressions. Here an example:

```<code>import re

tr = "II.AAK.00.BHZ | 2010-02-18T01:19:08.019500Z"
MAGIC_REGEX = "\w{2}\.(?P<name>.*)\.(?P<value>\d+)\.\w{3}\s+\|\s+(?P<date>\S+)"
match = re.fullmatch(MAGIC_REGEX, tr)
print(match.groupdict())
</code>```

Result:

```<code>{'name': 'AAK', 'value': '00', 'date': '2010-02-18T01:19:08.019500Z'}
</code>```

groupdict() Gives a dictionary with each group, but you also have groups() which gives you a tuple.

```<code>('AAK', '00', '2010-02-18T01:19:08.019500Z')
</code>```

Body:
This is st[0:6], which is my list (actually it is traces).

I can get some trace by numbers, e.g. st[3], but I want to get some trace by string, for example the data for ADK.10.

I know this name (ADK), but now I don't know this index number.

The 6 Trace(s) in Stream are below:

II.AAK.00.BHZ | 2010-02-18T01:19:08.019500Z

II.AAK.10.BHZ | 2010-02-18T01:19:08.019500Z

IU.ADK.00.BHZ | 2010-02-18T01:18:31.019536Z

IU.ADK.10.BHZ | 2010-02-18T01:18:31.019536Z

IU.AFI.00.BHZ | 2010-02-18T01:23:13.023144Z

IU.AFI.10.BHZ | 2010-02-18T01:23:13.010644Z

I tried this code below, but I'm getting an error:

tr = st['*.RSSD.00.*']

I want to get the RSSD.00 data to tr. What should I do?

Body:
I don't know what do you mean by data, but you can extract it with regular expressions. Here an example:

import re

tr = "II.AAK.00.BHZ | 2010-02-18T01:19:08.019500Z"
MAGIC_REGEX = "\w{2}\.(?P<name>.*)\.(?P<value>\d+)\.\w{3}\s+\|\s+(?P<date>\S+)"
match = re.fullmatch(MAGIC_REGEX, tr)
print(match.groupdict())

Result:

{'name': 'AAK', 'value': '00', 'date': '2010-02-18T01:19:08.019500Z'}

groupdict() Gives a dictionary with each group, but you also have groups() which gives you a tuple.

('AAK', '00', '2010-02-18T01:19:08.019500Z')


答:
You should not use one hot encoding since you are using a random forest model. An RF model will be able to find the patterns from label encoding as well and generally RF models perform worse with one hot encoding as they might decide to lost a few days when creating a tree. Also one hot encoding introduces the curse of dimensionality in your data, which is never good.

One hot encoding is better in cases of methods like linear regression or logistic regression, where 1 i.e. Monday might get more importance then 6 i.e. Saturday as these models have a multiplication model on the backend.

Title: To One-Hot encode or not to One-Hot encode

Body:
My data set has the day of the week number (Mon = 1, Tue = 2, Wed = 3 ...)

My data look like this

WeekDay Col1 Col2 Target
1       2.2  8    126
6       3.5  4    354
1       8.0  2    322
3       7.2  4    465
7       3.2  5    404
6       3.8  3    134
1       3.6  5    455
1       5.5  8    345
6       7.0  6    442

Shall I one-hot encode WeekDay so it will look like this ?

WeekDay Col1 Col2 Target  Mo Tu We Th Fr Sa Su
1       2.2  8    126     1  0  0  0  0  0  0
6       3.5  4    354     0  0  0  0  0  1  0
1       8.0  2    322     1  0  0  0  0  0  0
3       7.2  4    465     0  0  1  0  0  0  0
7       3.2  5    404     0  0  0  0  0  0  1
6       3.8  3    134     0  0  0  0  0  1  0
1       3.6  5    455     1  0  0  0  0  0  0
1       5.5  8    345     1  0  0  0  0  0  0
6       7.0  6    442     0  0  0  0  0  1  0

I am going to use Random Forest


问:
jQuery onClick function to submit data to php "not defined"
The following button calls a jQuery function onClick.  However, the Firefox dev console says "postData is not defined."

Here is the button and the jQuery script.

```<code>    <div class="center_text_grid flex-item EMail_Pwd">

    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>

function sendReply() {
    // autoresponder
}

postData().done(sendReply);

</script>

</form><br>

<br><br><br>

<!-- ________________ -->

<script type="text/javascript">

function postData() {
    return $.ajax({
    var datastring = $("#echo_test").serialize();
    $.ajax({
       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
});
}
</code>```

Why does the console say the function postData is not defined?

Thanks for any ideas.

答:
I don't understand why you need two nested ajax calls, you really don't need them, I think. In any case, you can't declare a variable like this var datastring = $("#echo_test").serialize(); inside curly brackets, so move that line outside the ajax call.

Also take into consideration the order in which you declare/execute functions.

So, moving the script, where the function is declared, up:

```<code><div class="center_text_grid flex-item EMail_Pwd">
    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>

<script type="text/javascript">
function postData() {
    var datastring = $("#echo_test").serialize();
    return $.ajax({

       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
}
</script>
<script>
function sendReply() {
    // autoresponder
}

//also, this line is not needed for the button to work, this is just if
//you need the function to execute on page load as well
postData().done(sendReply);

</script>
</code>```

HIH

Body:
The following button calls a jQuery function onClick.  However, the Firefox dev console says "postData is not defined."

Here is the button and the jQuery script.

    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button>

function sendReply() {
    // autoresponder
}

postData().done(sendReply);

</script>

</form>

Body:
I don't understand why you need two nested ajax calls, you really don't need them, I think. In any case, you can't declare a variable like this var datastring = $("#echo_test").serialize(); inside curly brackets, so move that line outside the ajax call.

Also take into consideration the order in which you declare/execute functions.

So, moving the script, where the function is declared, up:

<div class="center_text_grid flex-item EMail_Pwd">
    <button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>

<script type="text/javascript">
function postData() {
    var datastring = $("#echo_test").serialize();
    return $.ajax({

       type: "POST",
       url: "echo_test.php",
       data: {post: datastring},
    });
}
</script>
<script>
function sendReply() {
    // autoresponder
}

//also, this line is not needed for the button to work, this is just if
//you need the function to execute on page load as well
postData().done(sendReply);

</script>

HIH


问:
Node fetch JSON data is not iterable
I am getting an error of TypeError: data.events is not iterable when using fetch to retrieve JSON data from an API.

I am pretty sure it is in my handling of the JSON in for (const event of data.events) from the below code but I am pulling short on finding a fix.

```<code>const data = fetch(url, {
    method: 'post',
    headers: new Headers({
        Authorization: 'Bearer ' + bearerToken,
       'Content-Type': 'application/json'
    })
});

for (const event of data.events) {
    let fileNode;
    try {
        fileNode = await createRemoteFileNode({
            url: logo.original.url,
            cache,
            store,
            createNode,
            createNodeId
         });
    } catch (error) {
        console.warn('error creating node', error);
    }
}
</code>```

The JSON when requested in Postman is returned as

```<code>{
    "pagination": {
        ...
    },
    "events": [
        {
            "name": "Example One",
            "logo": {
                "original": {
                    "url": "exampleURL"
                }
            }
        },
        {
            "name": "Example Two",
            "logo": {
                "original": {
                   "url": "exampleURL"
                }
            }
        }
    ],
    "location": {
        ...
    }
</code>```

}

The goal is to createRemoteFileNode for each event from logo.original.url

答:
fetch() returns a promise so data.events does not exist until the fetch promised is resolved. Edit your code this way:

```<code>fetch(url, {
    method: 'post',
    headers: new Headers({
        Authorization: 'Bearer ' + bearerToken,
       'Content-Type': 'application/json'
    })
}).then(function(data){

  for (const event of data.events) {
      let fileNode;
      try {
          fileNode = await createRemoteFileNode({
              url: logo.original.url,
              cache,
              store,
              createNode,
              createNodeId
           });
      } catch (error) {
          console.warn('error creating node', error);
      }
  }
});
</code>```

Title: Node fetch JSON data is not iterable

Body:
I am getting an error of TypeError: data.events is not iterable when using fetch to retrieve JSON data from an API.

I am pretty sure it is in my handling of the JSON in for (const event of data.events) from the below code but I am pulling short on finding a fix.

const data = fetch(url, {
    method: 'post',
    headers: new Headers({
        Authorization: 'Bearer ' + bearerToken,
       'Content-Type': 'application/json'
    })
});

for (const event of data.events) {
    let fileNode;
    try {
        fileNode = await createRemoteFileNode({
            url: logo.original.url,
            cache,
            store,
            createNode,
            createNodeId
         });
    } catch (error) {
        console.warn('error creating node', error);
    }
}

The JSON when requested in Postman is returned as

{
    "pagination": {
        ...
    },
    "events": [
        {
            "name": "Example One",
            "logo": {
                "original": {
                    "url": "exampleURL"
                }
            }
        },
        {
            "name": "Example Two",
            "logo": {
                "original": {
                   "url": "exampleURL"
                }
            }
        }
    ],
    "location": {
        ...
    }

}

The goal is to createRemoteFileNode for each event from logo.original.url

Body:
fetch() returns a promise so data.events does not exist until the fetch promised is resolved. Edit your code this way:

fetch(url, {
    method: 'post',
    headers: new Headers({
        Authorization: 'Bearer ' + bearerToken,
       'Content-Type': 'application/json'
    })
}).then(function(data){

  for (const event of data.events) {
      let fileNode;
      try {
          fileNode = await createRemoteFileNode({
              url: logo.original.url,
              cache,
              store,
              createNode,
              createNodeId
           });
      } catch (error) {
          console.warn('error creating node', error);
      }
  }
});


问:
Firebase Functions not firing for Cloud Firestore
I simply cannot see where I'm going wrong here. My Cloud Firestore is on "europe-west3", the functions are deployed to "europe-west1" (the docs tell me that this is the closest location to west3).

Structure is thus: I've got a bunch of "tickets" each of which can have a subcollection named "comments". The console thus looks like this:

The upload was successful:

The function code was taken from the official code samples
Github repo for Function samples

This is what my code looks like:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();

exports.countComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments/{commentsid}')
    .onWrite(
        async (change) => {
            const ticketsRef = change.after.ref.parent;
            const countRef = ticketsRef.parent.child('comments_count');

            let increment;
            if(change.after.exists() && !change.before.exists()) {
                increment = 1;
            } else if(!change.after.exists() && change.before.exists()) {
                increment = -1;
            } else {
                return null;
            }

            await countRef.transaction((current) => {
                return (current || 0) + increment;
            });
            console.log('Counter updated');
            return null;
        });

exports.recountComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments_count')
    .onDelete(
        async (snap) => {
            const counterRef = snap.ref;
            const collectionRef = counterRef.parent.child('comments');
            const commentsData = await collectionRef.once('value');
            return await counterRef.set(commentsData.numChildren());
        }
    )
```

<p>Now, the problem is that these functions simply do not fire. I'm not seeing anything in the logs, regardless of whether I'm pushing changes through my clients (a Flutter app) or if I'm changing things directly in the Firebase console.</p>

<p>In my desperation I've also tried to simply listen to "/tickets" as any changes below that path should also trigger - but there's nothing.</p>

<p>So. What is the obvious thing I overlooked? And, yes, I had a look at the other questions/answers but nothing jumped at me...</p>

<p>edit: </p>

<p>This would be the corrected version, probably not optimal.</p>

<pre class="lang-js prettyprint-override"><code>exports.countComments = functions.region('europe-west1').firestore.document('/tickets/{ticketId}/comments/{commentsId}')
    .onWrite(
        async (change, context) => {
            const ticketId = context.params.ticketId;
            const ticketRef = admin.firestore().collection('tickets').doc(ticketId);

            let increment;
            if(change.after.exists && !change.before.exists) {
                increment = 1;
            } else if(!change.after.exists && change.before.exists) {
                increment = -1;
            } else {
                return null;
            }
            return transaction = admin.firestore().runTransaction(t => {
                return t.get(ticketRef)
                    .then(doc => {
                        let count = (doc.data().comments_count || 0) + increment;
                        t.update(ticketRef, {comments_count: count});
                    });
            }).then(res => {
                console.log('Counter updated');
            }).catch(err => {
                console.log('Transaction error:', err);
            });
        });

</code>```

答:
Your database is Cloud Firestore, but you've written a Realtime Database trigger.  They are two completely different databases.  Follow the documentation for writing Cloud Firestore triggers instead.

Your function will start like this:

```<code>functions.region('europe-west1').firestore.document('...')
</code>```

Note "firestore" instead of "database".

Body:
I simply cannot see where I'm going wrong here. My Cloud Firestore is on "europe-west3", the functions are deployed to "europe-west1" (the docs tell me that this is the closest location to west3).

Structure is thus: I've got a bunch of "tickets" each of which can have a subcollection named "comments". The console thus looks like this:

The upload was successful:

The function code was taken from the official code samples
Github repo for Function samples

This is what my code looks like:

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp();

exports.countComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments/{commentsid}')
    .onWrite(
        async (change) => {
            const ticketsRef = change.after.ref.parent;
            const countRef = ticketsRef.parent.child('comments_count');

            let increment;
            if(change.after.exists() && !change.before.exists()) {
                increment = 1;
            } else if(!change.after.exists() && change.before.exists()) {
                increment = -1;
            } else {
                return null;
            }

            await countRef.transaction((current) => {
                return (current || 0) + increment;
            });
            console.log('Counter updated');
            return null;
        });

exports.recountComments = functions.region('europe-west1').database.ref('/tickets/{ticketId}/comments_count')
    .onDelete(
        async (snap) => {
            const counterRef = snap.ref;
            const collectionRef = counterRef.parent.child('comments');
            const commentsData = await collectionRef.once('value');
            return await counterRef.set(commentsData.numChildren());
        }
    )

Now, the problem is that these functions simply do not fire. I'm not seeing anything in the logs, regardless of whether I'm pushing changes through my clients (a Flutter app) or if I'm changing things directly in the Firebase console.

In my desperation I've also tried to simply listen to "/tickets" as any changes below that path should also trigger - but there's nothing.

So. What is the obvious thing I overlooked? And, yes, I had a look at the other questions/answers but nothing jumped at me...

edit:

This would be the corrected version, probably not optimal.

exports.countComments = functions.region('europe-west1').firestore.document('/tickets/{ticketId}/comments/{commentsId}')
    .onWrite(
        async (change, context) => {
            const ticketId = context.params.ticketId;
            const ticketRef = admin.firestore().collection('tickets').doc(ticketId);

            let increment;
            if(change.after.exists && !change.before.exists) {
                increment = 1;
            } else if(!change.after.exists && change.before.exists) {
                increment = -1;
            } else {
                return null;
            }
            return transaction = admin.firestore().runTransaction(t => {
                return t.get(ticketRef)
                    .then(doc => {
                        let count = (doc.data().comments_count || 0) + increment;
                        t.update(ticketRef, {comments_count: count});
                    });
            }).then(res => {
                console.log('Counter updated');
            }).catch(err => {
                console.log('Transaction error:', err);
            });
        });

Body:
Your database is Cloud Firestore, but you've written a Realtime Database trigger.  They are two completely different databases.  Follow the documentation for writing Cloud Firestore triggers instead.

Your function will start like this:

functions.region('europe-west1').firestore.document('...')

Note "firestore" instead of "database".


问:
Is there a way to connect to to aws environment to upload the spark output to s3 bucket when run locally using anaconda
We can do this using Dev Endpoints in aws glue but i was interested to know if it is possible to push the spark computed data(when run locally/standalone mode) to s3 using anaconda by adding spark and hadoop winutils dependences.</p>

答:
If you can get your local system to talk to the s3a connector, then yes.

But: I wouldn't use S3 as a direct destination of work on the local system because the performance would be atrocious and it'd take a lot of effort to get working.

Better to use the local FS as a destination and then upload it after. Lots of tools do that, including those which come on the aws command line app from AWS itself. You should just be able to use it to do it. And if you can do it on the command line, you can use exec() to call it in your code

```<code>aws s3 cp ~/work/generated s3://mybucket/results  --recursive
</code>```

Body:
If you can get your local system to talk to the s3a connector, then yes.

But: I wouldn't use S3 as a direct destination of work on the local system because the performance would be atrocious and it'd take a lot of effort to get working.

Better to use the local FS as a destination and then upload it after. Lots of tools do that, including those which come on the aws command line app from AWS itself. You should just be able to use it to do it. And if you can do it on the command line, you can use exec() to call it in your code

aws s3 cp ~/work/generated s3://mybucket/results  --recursive