问:
Foreign key in Ajax POST request in Django
I have some problems with my web app . I need to specify user in my Ajax request. When I try to add new item I get an error:

TypeError: Field 'id' expected a number but got . Is the any solutions ?
Here is my code:

views.py

```<code>if request.method == 'POST':
    if request.is_ajax():
        form = AddTask(request.POST)
        if form.is_valid():
            form.cleaned_data
            form.save()
            user_membership = User.objects.get(id=request.user.id)
            expence_object = model_to_dict(Task.objects.get(pk=user_membership))
            return JsonResponse({'error': False, 'data': expence_object})
</code>```

models.py

```<code>class Task(models.Model):
    title=models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.now,blank=True)
    is_published=models.BooleanField(default=True)
    usertask=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,  null=True, blank=True)
</code>```

Ajax form

```<code>        $('#taskpost').submit(function (e) {
                // console.log("Creating the book");
                e.preventDefault();
                // get the form data
                var formData = {

                    'title': $('#id_title').val(),
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    contentType: 'application/x-www-form-urlencoded',
                    encode: true,
                };
                $.ajax({
                    type: 'POST',
                    url: 'create/',
                    data: formData,
                    dataType: 'json',
                }).done(function (data) {
</code>```

答:
You're getting those errors because you're not handling things correctly in your views. First of all, when creating your Task object, you're saving it without setting an usertask value, therefore null is set.

On the other hand, when trying to fetch the just-created object here Task.objects.get(pk=user_membership) you're doing this wrong because you're passing an User instance to the parameter pk. It should be an integer.

Furthermore, for what I see, what you're trying to accomplish here: expence_object = model_to_dict(Task.objects.get(pk=user_membership)) is to get the just-created model, but that's totally unnecessary in your case and also you're doing it wrong. Please, try the following code instead:

```<code>form = AddTask(request.POST)
    if form.is_valid():
        # form.cleaned_data  <-- This line is unnecessary here too
        obj = form.save(commit=False) # Prevent saving before assigning usertask
        obj.usertask = request.user
        obj.save()
        expence_object = model_to_dict(obj)
        return JsonResponse({'error': False, 'data': expence_object})
</code>```

When you save a form that is based on a model, it returns the saved instance of the model. So there's no need to save it to the database and then make a new query to get it back. Just assign it to a variable (obj in this case) and do all the other things you need to do.

Body:
I have some problems with my web app . I need to specify user in my Ajax request. When I try to add new item I get an error:

TypeError: Field 'id' expected a number but got . Is the any solutions ?
Here is my code:

views.py

if request.method == 'POST':
    if request.is_ajax():
        form = AddTask(request.POST)
        if form.is_valid():
            form.cleaned_data
            form.save()
            user_membership = User.objects.get(id=request.user.id)
            expence_object = model_to_dict(Task.objects.get(pk=user_membership))
            return JsonResponse({'error': False, 'data': expence_object})

models.py

class Task(models.Model):
    title=models.CharField(max_length=200)
    date = models.DateTimeField(default=datetime.now,blank=True)
    is_published=models.BooleanField(default=True)
    usertask=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,  null=True, blank=True)

Ajax form

        $('#taskpost').submit(function (e) {
                // console.log("Creating the book");
                e.preventDefault();
                // get the form data
                var formData = {

                    'title': $('#id_title').val(),
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    contentType: 'application/x-www-form-urlencoded',
                    encode: true,
                };
                $.ajax({
                    type: 'POST',
                    url: 'create/',
                    data: formData,
                    dataType: 'json',
                }).done(function (data) {

Body:
You're getting those errors because you're not handling things correctly in your views. First of all, when creating your Task object, you're saving it without setting an usertask value, therefore null is set.

On the other hand, when trying to fetch the just-created object here Task.objects.get(pk=user_membership) you're doing this wrong because you're passing an User instance to the parameter pk. It should be an integer.

Furthermore, for what I see, what you're trying to accomplish here: expence_object = model_to_dict(Task.objects.get(pk=user_membership)) is to get the just-created model, but that's totally unnecessary in your case and also you're doing it wrong. Please, try the following code instead:

form = AddTask(request.POST)
    if form.is_valid():
        # form.cleaned_data  <-- This line is unnecessary here too
        obj = form.save(commit=False) # Prevent saving before assigning usertask
        obj.usertask = request.user
        obj.save()
        expence_object = model_to_dict(obj)
        return JsonResponse({'error': False, 'data': expence_object})

When you save a form that is based on a model, it returns the saved instance of the model. So there's no need to save it to the database and then make a new query to get it back. Just assign it to a variable (obj in this case) and do all the other things you need to do.


来源: stackexchange

问:
What is MediaMetadataRetriever.BitmapParams params in getFramesAtIndex()?
I am trying to retrieve all the frames from a video. For that I am using getFramesAtIndex() in MediaMetadataRetriever.

I am not sure about the third parameter in the function, which is MediaMetadataRetriever.BitmapParams params.
Can you explain the third parameter with an example. I tried to look in Android documentation, but there are no examples.

答:
The method MediaMetadataRetriever.getFramesAtIndex() is overloaded. If you don't have specific requirements for image quality, then you could use the two-arguments version of the method:

```<code>public List<Bitmap> getFramesAtIndex (int frameIndex,
                int numFrames)
</code>```

which requires no BitmapParams. This is choice provides the simplest code as possible. There are two reasons why you might want to use the three-arguments version of the method:

Specific image quality requirements

Efficiency, as the doc says:

If the caller intends to retrieve more than one consecutive video frames, this method is preferred over getFrameAtIndex(int, android.media.MediaMetadataRetriever.BitmapParams) for efficiency

To answer your question, the simplest usage of the three-arguments version is

```<code>getFramesAtIndex (myFrameIndex,
                myNumFrames,
                new MediaMetadataRetriever.BitmapParams());
</code>```

because, if you look at the doc of BitmapParams, the default constructor

Creates a default BitmapParams object. By default, it uses Bitmap.Config#ARGB_8888 as the preferred bitmap config.

This is the preferrable choice in most cases, as discussed in the doc. As for non-default cases, suppose you want to specify the ALPHA_8 option instead of the default ARGB_8888. Then the code is as follows

```<code>getFramesAtIndex (myFrameIndex,
                myNumFrames,
                new MediaMetadataRetriever.BitmapParams()
                   .setPreferredConfig(Bitmap.Config.ALPHA_8));
</code>```

Hope that helps.

ContentLicense: CC BY-SA 4.0

Body:
The method MediaMetadataRetriever.getFramesAtIndex() is overloaded. If you don't have specific requirements for image quality, then you could use the two-arguments version of the method:

public List<Bitmap> getFramesAtIndex (int frameIndex,
                int numFrames)

which requires no BitmapParams. This is choice provides the simplest code as possible. There are two reasons why you might want to use the three-arguments version of the method:

Specific image quality requirements

Efficiency, as the doc says:

If the caller intends to retrieve more than one consecutive video frames, this method is preferred over getFrameAtIndex(int, android.media.MediaMetadataRetriever.BitmapParams) for efficiency

To answer your question, the simplest usage of the three-arguments version is

getFramesAtIndex (myFrameIndex,
                myNumFrames,
                new MediaMetadataRetriever.BitmapParams());

because, if you look at the doc of BitmapParams, the default constructor

Creates a default BitmapParams object. By default, it uses Bitmap.Config#ARGB_8888 as the preferred bitmap config.

This is the preferrable choice in most cases, as discussed in the doc. As for non-default cases, suppose you want to specify the ALPHA_8 option instead of the default ARGB_8888. Then the code is as follows

getFramesAtIndex (myFrameIndex,
                myNumFrames,
                new MediaMetadataRetriever.BitmapParams()
                   .setPreferredConfig(Bitmap.Config.ALPHA_8));

Hope that helps.


问:
jQuery focus on input text with name same as div id
I have several links. When I click a link I want jQuery to give focus to the corresponding input.

Links:

```<code><a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_38">Focus</a>
<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_39">Focus</a>
<a href="#" class="copy_go_to_input_field" data-divid="inp_copy_input_item_evidece_34">Focus</a>
</code>```

Input fields:

```<code><input type="text" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />
</code>```

jQuery (not working):

```<code><script>
$(function() {
    $('.copy_go_to_input_field').click(function() {
        var field = $(this).data('divid');
                $('[name=""+ field + ""]').focus();

        return false;
        });
});
</script>
</code>```

答:
You really don't need JS for that. You can do this quite easily using . Just assign an ID to your inputs, and use the for attribute as follows:

Focus
Focus
Focus

<input type="text" id="inp_copy_input_item_evidece_38" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" id="inp_copy_input_item_evidece_39" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" id="inp_copy_input_item_evidece_40" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />```

Body:
I have several links. When I click a link I want jQuery to give focus to the corresponding input.

Links:

Focus
Focus
Focus

Input fields:

<input type="text" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />

jQuery (not working):

Body:
You really don't need JS for that. You can do this quite easily using <label>. Just assign an ID to your inputs, and use the for attribute as follows:

<label class="copy_go_to_input_field" for="inp_copy_input_item_evidece_38">Focus</label>
<label class="copy_go_to_input_field" for="inp_copy_input_item_evidece_39">Focus</label>
<label class="copy_go_to_input_field" for="inp_copy_input_item_evidece_40">Focus</label>

<input type="text" id="inp_copy_input_item_evidece_38" name="inp_copy_input_item_evidece_38" value="2020_71_206_1" size="25" />
<input type="text" id="inp_copy_input_item_evidece_39" name="inp_copy_input_item_evidece_39" value="2020_71_206_1" size="25" />
<input type="text" id="inp_copy_input_item_evidece_40" name="inp_copy_input_item_evidece_40" value="2020_71_206_1" size="25" />


问:
Checking position of newly added unique_ptr to priority_queue
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

```<code>bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}
</code>```

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

```<code>bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}
</code>```

Can it be done better way?

答:
Two sad ways to solve this would be:

1.

```<code>bool foo(std::unique_ptr<SchedulerTask> task)
{
  SchedularTask* tmp = task.get();
  eventList_.push(std::move(task));
  return tmp == eventList_.top().get();
}
</code>```

2.

```<code>bool foo(std::unique_ptr<SchedulerTask> task)
{
  std::unique_ptr<SchedularTask> tmp(task.get());
  eventList_.push(std::move(task));
  bool ret = (tmp == eventList_.top());
  tmp.release();
  return ret;
}
</code>```

Body:
I am switching my design to use smart pointers and I've encountered a problem with std::priority_que

I had a method that inserts new task into queue and signalizes if new task landed at the top of it:

bool foo(SchedulerTask* task)
{
  eventList_.push(task);
  return task == eventList_.top();
}

After wrapping SchedulerTask into unique_ptr I met problem with checking its priority in container. After moving the object into queue I was not able to use it again for compare. I have end up with caching comparator member and comparing it with the top object:

bool foo(std::unique_ptr<SchedulerTask> task)
{
  const auto prio = task->getCycle(); // my priority_queue compares objects by getCycle() value

  eventList_.push(std::move(task));

  return prio >= eventList_.top()->getCycle();;
}

Can it be done better way?

Body:
Two sad ways to solve this would be:

1.

bool foo(std::unique_ptr<SchedulerTask> task)
{
  SchedularTask* tmp = task.get();
  eventList_.push(std::move(task));
  return tmp == eventList_.top().get();
}

2.

bool foo(std::unique_ptr<SchedulerTask> task)
{
  std::unique_ptr<SchedularTask> tmp(task.get());
  eventList_.push(std::move(task));
  bool ret = (tmp == eventList_.top());
  tmp.release();
  return ret;
}


问:
Power BI Calculate MAX based on the Slicer Selections
I have a table which displays hourly pay per position. I'm using MAX(HourlyPay) to get the maximum value in the table and get a value 60 for example. But when I apply a slicer (based on department), the value still show's as 60. Is there a way to recalculate the MAX of HourlyRate based on the Slicers?

Tables:
Occupants
PayDetails (table which contains "Hourly Pay")
OrgStructure (table containing Department slicer)

Relationships:
Occupants to PayDetails (1:1)
Occupants to OrgStructure (*:1)

The column MAX(HourlyPay) which I'm trying to calculate is in the table Occupants.

答: This should work. Providing the relationship that you have added links to an identical value in each table, then the slicer should filter the hourly pay column as expected. </p>


问:
Spark - convert array of JSON Strings to Struct array, filter and concat with root
I am totally new to Spark and I'm writing a pipeline to perform some transformations into a list of audits.

Example of my data:

```<code>{
    "id": 932522712299,
    "ticket_id": 12,
    "created_at": "2020-02-14T19:05:16Z",
    "author_id": 392401450482,
    "events": ["{\"id\": 932522713292, \"type\": \"VoiceComment\", \"public\": false, \"data\": {\"from\": \"11987654321\", \"to\": \"+1987644\"}"],
}
</code>```

My schema is basically:

```<code>root
 |-- id: long (nullable = true)
 |-- ticket_id: long (nullable = true)
 |-- created_at: string (nullable = true)
 |-- author_id: long (nullable = true)
 |-- events: array (nullable = true)
 |    |-- element: string (containsNull = true)
</code>```

My transformations has a few steps:

Split events by type: comments, tags, change or update;

For each event found, I must add ticket_id, author_id and created_at from root;

It must have one output for each event type.

Basically, each object inside event's array is a string JSON because each type has a different structure - the only attribute common between them it's the type.

I have reach my goals doing some terrible work by converting my dataframe to dict using the following code:

```<code>audits = list(map(lambda row: row.asDict(), df.collect()))`
comments = []
for audit in audits:
    base_info = {'ticket_id': audit['ticket_id'], 'created_at': audit['created_at'], 'author_id': audit['author_id']}
    audit['events'] = [json.loads(x) for x in audit['events']]

    audit_comments = [
        {**x, **base_info}
        for x in audit['events']
        if x['type'] == "Comment" or x['type'] == "VoiceComment"
    ]
    comments.extend(audit_comments)
</code>```

Maybe this question sounds lame or lazy but I'm really stuck in simple things like:

how to parse 'events' items to struct?

how to select event by type and add informations from root? Maybe using select syntax?

Any help is appreciated.

答:
Your code will load the complete events data onto the master node, which has submitted the job. The spark way to process data wants you to create a map reduce job.  There are multiple api for this - they create a DAG Plan for the job and the plan is manifested only when calling specific functions like head or show.
A job like this will be distributed to all machines in a cluster.

When working with a dataframe api, a lot can be done with pyspark.sql.functions

Below the same tranformations with spark.sql dataframe api

```<code>import pyspark.sql.functions as F

df = df.withColumn('event', F.explode(df.events)).drop(df.events)
df = df.withColumn('event', F.from_json(df.event, 'STRUCT <id: INT, type: STRING, public: Boolean, data: STRUCT<from: STRING, to: STRING>>'))
events = df.where('event.type = "Comment" OR event.type == "VoiceComment"')

events.printSchema()
events.head(100)
</code>```

When data cannot be processed with sql expressions you can implement a plain user defined function - UDF or Pandas UDF

Body:
I am totally new to Spark and I'm writing a pipeline to perform some transformations into a list of audits.

Example of my data:

{
    "id": 932522712299,
    "ticket_id": 12,
    "created_at": "2020-02-14T19:05:16Z",
    "author_id": 392401450482,
    "events": ["{\"id\": 932522713292, \"type\": \"VoiceComment\", \"public\": false, \"data\": {\"from\": \"11987654321\", \"to\": \"+1987644\"}"],
}

My schema is basically:

root
 |-- id: long (nullable = true)
 |-- ticket_id: long (nullable = true)
 |-- created_at: string (nullable = true)
 |-- author_id: long (nullable = true)
 |-- events: array (nullable = true)
 |    |-- element: string (containsNull = true)

My transformations has a few steps:

Split events by type: comments, tags, change or update;

For each event found, I must add ticket_id, author_id and created_at from root;

It must have one output for each event type.

Basically, each object inside event's array is a string JSON because each type has a different structure - the only attribute common between them it's the type.

I have reach my goals doing some terrible work by converting my dataframe to dict using the following code:

audits = list(map(lambda row: row.asDict(), df.collect()))`
comments = []
for audit in audits:
    base_info = {'ticket_id': audit['ticket_id'], 'created_at': audit['created_at'], 'author_id': audit['author_id']}
    audit['events'] = [json.loads(x) for x in audit['events']]

    audit_comments = [
        {**x, **base_info}
        for x in audit['events']
        if x['type'] == "Comment" or x['type'] == "VoiceComment"
    ]
    comments.extend(audit_comments)

Maybe this question sounds lame or lazy but I'm really stuck in simple things like:

how to parse 'events' items to struct?

how to select event by type and add informations from root? Maybe using select syntax?

Any help is appreciated.

Body:
Your code will load the complete events data onto the master node, which has submitted the job. The spark way to process data wants you to create a map reduce job.  There are multiple api for this - they create a DAG Plan for the job and the plan is manifested only when calling specific functions like head or show.
A job like this will be distributed to all machines in a cluster.

When working with a dataframe api, a lot can be done with pyspark.sql.functions

Below the same tranformations with spark.sql dataframe api

import pyspark.sql.functions as F

df = df.withColumn('event', F.explode(df.events)).drop(df.events)
df = df.withColumn('event', F.from_json(df.event, 'STRUCT <id: INT, type: STRING, public: Boolean, data: STRUCT<from: STRING, to: STRING>>'))
events = df.where('event.type = "Comment" OR event.type == "VoiceComment"')

events.printSchema()
events.head(100)

When data cannot be processed with sql expressions you can implement a plain user defined function - UDF or Pandas UDF


问:
SQLite in Android How to update a specific row
I've been trying to update a specific row for a while now, and it seems that there are two ways to do this. From what I've read and tried, you can just use the:

execSQL(String sql) method

or the:

update(String table, ContentValues values, String whereClause, String[] whereArgs) method.

(Let me know if this is incorrect as I am new to android and very new to SQL.)

So let me get to my actual code.

```<code>myDB.update(TableName, "(Field1, Field2, Field3)" + " VALUES ('Bob', 19, 'Male')", "where _id = 1", null);
</code>```

I am trying to accomplish this:

Update Field1, Field2, and Field3 where the primary key (_id) is equal to 1.

Eclipse gives me a red line right underneath the word "update" and gives me this explanation:

The method update(String, ContentValues, String, String[]) in the type
  SQLiteDatabase is not applicable for the arguments (String, String,
  String, null)

I'm guessing I'm not assigning the ContentValues correctly. Can anyone point me in the right direction?

答:
just give rowId and type of data that is going to be update in ContentValues.

public void updateStatus(String id , int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues data = new ContentValues();

data.put("status", status);

db.update(TableName, data, "columnName"  + " = "+id , null);

}

ContentLicense: CC BY-SA 3.0

Body:
I've been trying to update a specific row for a while now, and it seems that there are two ways to do this. From what I've read and tried, you can just use the:

execSQL(String sql) method

or the:

update(String table, ContentValues values, String whereClause, String[] whereArgs) method.

(Let me know if this is incorrect as I am new to android and very new to SQL.)

So let me get to my actual code.

myDB.update(TableName, "(Field1, Field2, Field3)" + " VALUES ('Bob', 19, 'Male')", "where _id = 1", null);

I am trying to accomplish this:

Update Field1, Field2, and Field3 where the primary key (_id) is equal to 1.

Eclipse gives me a red line right underneath the word "update" and gives me this explanation:

The method update(String, ContentValues, String, String[]) in the type
  SQLiteDatabase is not applicable for the arguments (String, String,
  String, null)

I'm guessing I'm not assigning the ContentValues correctly. Can anyone point me in the right direction?


问:
In Azure DevOps Server 2019 (on-prem) release pipeline how can one stage pass a file to another stage?
We have Azure DevOps Server 2019 on-prem. That means no unified pipelines, no YAML for release pipeline.

The scenario is this:
A stage runs terraform code to provision some resources in Azure. It is necessary to insert manual approval between terraform plan and terraform apply, however, the plan file produced by terraform plan stage must be shared with the terraform apply stage.

I can see these options:

Save the plan file on a shared file system

Save the plan file in a dedicated storage on Azure

Save the plan file somewhere within the Azure DevOps so that stages can access it without defining a dedicated file share or Azure storage

Pass the contents of the plan file as an output variable

I, personally, like the most the last option, but I wonder what are the limitations on the output variable value length? What is the maximum length of a variable in Azure Pipelines? suggests it is around 32KB, which may not be good enough. Given that, is there an option to pass files between stages?

答: There is no default task you can use in classic release pipeline. Due to the limitation of a variable, you would need to publish the file to dedicated file share or Azure storage.</p>


问:
How to draw pgraphics with different opacity out of an array?
i am trying to draw this 5 rectangles with an array but they have all the same opacity...
But they should have different but i dont now why?
Does someone can help me?
Thank you in advance :)
Sebastian</p>

```<code>PGraphics[] pgArray = new PGraphics[5];

void setup() {
  size(500, 500);
  background(255);

  for (int i = 0; i<pgArray.length; i++) {
    pgArray[i] = createGraphics(500, 500);
  }
}

void draw() {

  for (int i = 0; i < pgArray.length; i++) {
    pgArray[i].beginDraw();
    pgArray[i].fill(0, (255/pgArray.length)*i+1);
    pgArray[i].rect(20*i, 20*i, 50, 50);
    pgArray[i].endDraw();
  }

  for(int i = 0; i < pgArray.length; i++){
    image(pgArray[i],0,0);
  }
}
</code>```

答:
There are two problems: Your code does not clear the stage between frames and nor does it clear the PGraphics objects between frames. As opacity is additive, the rectangles would each reach full opacity within a few frames since you are drawing them on top of each other.

First, to refresh the background each frame:

Insert a call to background(255); at the top of the draw() loop.

Then, to clear the PGraphics objects you can either:

Move your rectangle drawing loop into setup(), so it runs once only.

Or

Insert a call to pgArray[i].clear(); after pgArray[i].beginDraw();.

Result:

Body:
i am trying to draw this 5 rectangles with an array but they have all the same opacity...
But they should have different but i dont now why?
Does someone can help me?
Thank you in advance :)
Sebastian

PGraphics[] pgArray = new PGraphics[5];

void setup() {
  size(500, 500);
  background(255);

  for (int i = 0; i<pgArray.length; i++) {
    pgArray[i] = createGraphics(500, 500);
  }
}

void draw() {

  for (int i = 0; i < pgArray.length; i++) {
    pgArray[i].beginDraw();
    pgArray[i].fill(0, (255/pgArray.length)*i+1);
    pgArray[i].rect(20*i, 20*i, 50, 50);
    pgArray[i].endDraw();
  }

  for(int i = 0; i < pgArray.length; i++){
    image(pgArray[i],0,0);
  }
}


问:
How to use lambda if else in map() on list in python?
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

```<code>l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])
</code>```

it seems that it should work but its giving syntax error

What is the issue here?

答:
you need this:</p>

```<code>[x for x in ['apple', 'banana', 'cherry'] if x == "apple"]
</code>```

Body:
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])

it seems that it should work but its giving syntax error

What is the issue here?

Body:
you need this:

[x for x in ['apple', 'banana', 'cherry'] if x == "apple"]


问:
I only have one key, but need to extract objects based on rating
Can I get synsets or words using rating even though it's all under one key? I've been trying to extract json objects based on if their rating is less than 1. However, all the syntax online searches based on key. But I only have one key. Can I search by the object attribute instead? </p>

<p>JSON document: </p>

```<code>"connections": [
        {
            "synset": 5995898,
            "rating": 1.0,
            "words": [
                "monetarism"
            ],
            "examples": []
        },
        {
            "synset": 1558749,
            "rating": 0.6,
            "words": [
                "driven",
                "impelled"
            ],
            "examples": [
                "felt impelled to take a stand against the issue"
            ]
        },
        {
            "synset": 1421122,
            "rating": 0.17204301075268819,
            "words": [
                "plug in",
                "plug into",
                "connect"
            ],
            "examples": [
                "Please plug in the toaster!",
                "Connect the TV so we can watch the football game tonight"
            ]
        },
</code>```

答:
So basicly you have one big array you can loop over:</p>

```<code>arr = [
    {
        "synset": 5995898,
        "rating": 1.0,
        "words": [
            "monetarism"
        ],
        "examples": []
    },
    {
        "synset": 1558749,
        "rating": 0.6,
        "words": [
            "driven",
            "impelled"
        ],
        "examples": [
            "felt impelled to take a stand against the issue"
        ]
    },
    {
        "synset": 1421122,
        "rating": 0.17204301075268819,
        "words": [
            "plug in",
            "plug into",
            "connect"
        ],
        "examples": [
            "Please plug in the toaster!",
            "Connect the TV so we can watch the football game tonight"
        ]
    }
]

for item in arr:
    print(item["rating"])
</code>```

Body:
Can I get synsets or words using rating even though it's all under one key? I've been trying to extract json objects based on if their rating is less than 1. However, all the syntax online searches based on key. But I only have one key. Can I search by the object attribute instead?

JSON document:

"connections": [
        {
            "synset": 5995898,
            "rating": 1.0,
            "words": [
                "monetarism"
            ],
            "examples": []
        },
        {
            "synset": 1558749,
            "rating": 0.6,
            "words": [
                "driven",
                "impelled"
            ],
            "examples": [
                "felt impelled to take a stand against the issue"
            ]
        },
        {
            "synset": 1421122,
            "rating": 0.17204301075268819,
            "words": [
                "plug in",
                "plug into",
                "connect"
            ],
            "examples": [
                "Please plug in the toaster!",
                "Connect the TV so we can watch the football game tonight"
            ]
        },

Body:
So basicly you have one big array you can loop over:

arr = [
    {
        "synset": 5995898,
        "rating": 1.0,
        "words": [
            "monetarism"
        ],
        "examples": []
    },
    {
        "synset": 1558749,
        "rating": 0.6,
        "words": [
            "driven",
            "impelled"
        ],
        "examples": [
            "felt impelled to take a stand against the issue"
        ]
    },
    {
        "synset": 1421122,
        "rating": 0.17204301075268819,
        "words": [
            "plug in",
            "plug into",
            "connect"
        ],
        "examples": [
            "Please plug in the toaster!",
            "Connect the TV so we can watch the football game tonight"
        ]
    }
]

for item in arr:
    print(item["rating"])


问:
How to optimize query with Inline Function in it?
I have a table TAB_1 with following Schema

```<code>    CAR_NO(Varchar)  START_DATE(Date)  ACTUAL_ARRIVAL_TIME(Number)  SOURCE_POINT(Varchar)
   END_POINT(Varchar)
</code>```

Table TAB_2 with following Schema

```<code>CAR_NO(Varchar)   ACTL_TIME_OF_ARRVL(Date)  EVENT_CODE(Varchar)
</code>```

My query is :

```<code> SELECT DISTINCT CAR_NO,START_DATE FROM TAB_1 WHERE
(TRUNC(START_DATE +CASE WHEN ACTUAL_ARRIVAL_TIME=0 THEN NULL ELSE ACTUAL_ARRIVAL_TIME END/1440)='10-Feb-2020' )
    AND SOURCE_POINT=END_POINT
    UNION
    SELECT DISTINCT  CAR_NO,START_DATE FROM TAB_2 WHERE EVENT_CODE='TD'
    AND TRUNC( ACTL_TIME_OF_ARRVL)='10-Feb-2020'
</code>```

Column ACTUAL_ARRIVAL_TIME stores the time value in minutes,Column ACTL_TIME_OF_ARRVL stores the date as timestamp value , I am trying to find all the cars which terminate on 10-Feb-2020 .Data can be absent from any of the tables so I have used UNION Operation here ,on top of this query I have to apply more operations ,so overall it is taking time of 35 seconds aprox. Please guide to optimize this query .

答:
Strange way to deal with date and time i guess.
First of all examine your execution plan.

I suppose with few data it works like a charm but with lots of data, performance is gone.

Starting with the UNION, it is a performance issue itself.

Inline Operations like you are doing in TAB_1 dismisses usage of indexes. I hope you have indexes in ACTUAL_ARRIVAL_TIME and ACTUAL_ARRIVAL_TIME fields, but in your case they are not being used.
I suppose this query is in the middle of a process, so you colud come with a little workaround done before executing it

1.Know your starting minute for your period: e.g. param 'startMinute'.

2.Know your ending minute for your period: e.g. param 'endMinute'.

3.Rewite query

```<code>SELECT DISTINCT CAR_NO,START_DATE
  FROM TAB_1
 WHERE START_DATE >=  startMinute
   AND START_DATE <   endMinute
   AND SOURCE_POINT = END_POINT
UNION
.
.
.
</code>```

I also hope you have an index in TAB_2.ACTL_TIME_OF_ARRVL, but also with the use of trunc, does not use index.
Maybe you need to create a function based index TRUNC(ACTL_TIME_OF_ARRVL) Index.
I'm sure you will find the following link very interesting:

https://blog.dbi-services.com/index-on-truncdate-do-you-still-need-old-index/

Body:
I have a table TAB_1 with following Schema

    CAR_NO(Varchar)  START_DATE(Date)  ACTUAL_ARRIVAL_TIME(Number)  SOURCE_POINT(Varchar)
   END_POINT(Varchar)

Table TAB_2 with following Schema

CAR_NO(Varchar)   ACTL_TIME_OF_ARRVL(Date)  EVENT_CODE(Varchar)

My query is :

 SELECT DISTINCT CAR_NO,START_DATE FROM TAB_1 WHERE
(TRUNC(START_DATE +CASE WHEN ACTUAL_ARRIVAL_TIME=0 THEN NULL ELSE ACTUAL_ARRIVAL_TIME END/1440)='10-Feb-2020' )
    AND SOURCE_POINT=END_POINT
    UNION
    SELECT DISTINCT  CAR_NO,START_DATE FROM TAB_2 WHERE EVENT_CODE='TD'
    AND TRUNC( ACTL_TIME_OF_ARRVL)='10-Feb-2020'

Column ACTUAL_ARRIVAL_TIME stores the time value in minutes,Column ACTL_TIME_OF_ARRVL stores the date as timestamp value , I am trying to find all the cars which terminate on 10-Feb-2020 .Data can be absent from any of the tables so I have used UNION Operation here ,on top of this query I have to apply more operations ,so overall it is taking time of 35 seconds aprox. Please guide to optimize this query .

Body:
Strange way to deal with date and time i guess.
First of all examine your execution plan.

I suppose with few data it works like a charm but with lots of data, performance is gone.

Starting with the UNION, it is a performance issue itself.

Inline Operations like you are doing in TAB_1 dismisses usage of indexes. I hope you have indexes in ACTUAL_ARRIVAL_TIME and ACTUAL_ARRIVAL_TIME fields, but in your case they are not being used.
I suppose this query is in the middle of a process, so you colud come with a little workaround done before executing it

1.Know your starting minute for your period: e.g. param 'startMinute'.

2.Know your ending minute for your period: e.g. param 'endMinute'.

3.Rewite query

SELECT DISTINCT CAR_NO,START_DATE
  FROM TAB_1
 WHERE START_DATE >=  startMinute
   AND START_DATE <   endMinute
   AND SOURCE_POINT = END_POINT
UNION
.
.
.

I also hope you have an index in TAB_2.ACTL_TIME_OF_ARRVL, but also with the use of trunc, does not use index.
Maybe you need to create a function based index TRUNC(ACTL_TIME_OF_ARRVL) Index.
I'm sure you will find the following link very interesting:

https://blog.dbi-services.com/index-on-truncdate-do-you-still-need-old-index/


问:
I want the view to remain static but the content to re-orient within the view
I am making a view with several subviews for iPad. I want all the positioning and sizing of the subviews to stay the same when rotating the iPad, but the content inside the subviews to re-orient. Does anyone know how to do this?</p>

答:
It sounds like you still need to layout the views depending on the orientation. However, you're portrait and landscape frames would have different proportions on the screen.

An Example of how you might layout a view:

```<code>int h = 300;
int w = 100;
int space = 50;

CGRect frame;
if( interfaceOrientation == UIInterfaceOrientationPortrait ) {

   frame = CGRectMake( space, space, w, h );
}
else if( interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) {
    frame = CGRectMake( self.view.bounds.size.width - w - space, self.view.bounds.size.height- h - space, w, h );
}
else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight ) {
    frame = CGRectMake( space, self.view.bounds.size.height- w - space, h , w );
}
else if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) {
    frame = CGRectMake( self.view.bounds.size.width - h - space, space, h, w );
}

self.label.frame = frame;
</code>```

Body:
It sounds like you still need to layout the views depending on the orientation. However, you're portrait and landscape frames would have different proportions on the screen.

An Example of how you might layout a view:

int h = 300;
int w = 100;
int space = 50;

CGRect frame;
if( interfaceOrientation == UIInterfaceOrientationPortrait ) {

   frame = CGRectMake( space, space, w, h );
}
else if( interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) {
    frame = CGRectMake( self.view.bounds.size.width - w - space, self.view.bounds.size.height- h - space, w, h );
}
else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight ) {
    frame = CGRectMake( space, self.view.bounds.size.height- w - space, h , w );
}
else if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) {
    frame = CGRectMake( self.view.bounds.size.width - h - space, space, h, w );
}

self.label.frame = frame;


答:
Greedy version:

(?:Note=).*(?:;)

None Greedy version:

(?:Note=).*?(?:;)

Match 'Note=' but does not capture it. Match and capture all other characters until you get to a semicolon. Match the semicolon but do not capture it.

Greedy version captures until the last semicolon.

None greedy version captures until the first semicolon.

Title: Extract word uptill certain symbol

Body:
Hi I have this uniprot gff data that looks like

+--------+--------+-------+------+------------------------------------------------------------------------------------------------------+
| Entry  | check  | start | end  |                                               Domains                                               |
+--------+--------+-------+------+------------------------------------------------------------------------------------------------------+
| O75581 | Repeat |    63 |  106 |  Note=LDL-receptor class B 1                                                                         |
| O75581 | Repeat |   150 |  193 |  Note=LDL-receptor class B 3                                                                         |
| O75581 | Domain |   282 |  324 |  Note=EGF-like 1                                                                                |
| O75581 | Domain |  1248 | 1286 |  Note=LDL-receptor class A 1;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00124 |
| O75581 | Domain |  1287 | 1323 |  Note=LDL-receptor class A 2;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00124 |
| O75581 | Domain |  1325 | 1361 |  Note=LDL-receptor class A 3;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00124 |
| P13688 | Domain |    35 |  142 |  Note=Ig-like V-type;Ontology_term=ECO:0000250;evidence=ECO:0000250|UniProtKB:P31997                 |
| P13688 | Domain |   145 |  232 |  Note=Ig-like C2-type 1;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00114      |
| P13688 | Domain |   237 |  317 |  Note=Ig-like C2-type 2;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00114      |
| P13688 | Domain |   323 |  413 |  Note=Ig-like C2-type 3;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00114      |
| P19022 | Domain |   160 |  267 |  Note=Cadherin 1;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00043             |
| P19022 | Domain |   268 |  382 |  Note=Cadherin 2;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00043             |
| P19022 | Domain |   383 |  497 |  Note=Cadherin 3;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00043             |
| Q13586 | Domain |   132 |  200 |  Note=SAM;Ontology_term=ECO:0000255;evidence=ECO:0000255|PROSITE-ProRule:PRU00184                    |
| P04629 | Repeat |    90 |  113 |  Note=LRR 1                                                                                |
| P04629 | Repeat |   116 |  137 |  Note=LRR 2                                                                                |
+--------+--------+-------+------+------------------------------------------------------------------------------------------------------+

I am trying to extract the domain names column df['Domains]. With the following code, I am close to getting the first 2 3 words of the domain name but doesn't work universally.

for row in df['Domains']:
    print(re.findall(r'Note=(\w*)(.?)(\w*)', row))

which gives something like this

[('LDL', '-', 'receptor')]
[('LDL', '-', 'receptor')]
[('EGF', '-', 'like')]
[('Ig', '-', 'like')]
[('Ig', '-', 'like')]`

So, I wish to change my approach and get everything starting after Note= and ends before ; or end of line. How may I get this?


问:
How can I access a webapp on WildFly 12 server from another computer?
Hello I have a webapp on Wild Fly 12 server and I want a colleague from work to access it. When I try to access it with my ip (from my computer or his) it says it can not connect). It only works from my computer with localhost. This is what I`ve tried:

I replaced in standalone.xml the old  tags with this:

```<code><interfaces>
    <interface name="management">

        <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>

    </interface>

    <interface name="public">

        <inet-address value="${jboss.bind.address:0.0.0.0}"/>

    </interface>
</interfaces>
</code>```

But it doesn`t work...Do you have any solutions ? Thank you

答:
Not that easy to analyze with the given information. Your configuration is correct, it should work.

What have you tested? Connecting to an application or to the Wildfly-Base-URL([YOUR-IP]:8080)?

Are there any other changes in the standalone.xml?

FYI: You don't have to use the binding with 0.0.0.0. It's possible to use <any-address/> instead of <inet-address value="${jboss.bind.address:0.0.0.0}"/>.

Body:
Hello I have a webapp on Wild Fly 12 server and I want a colleague from work to access it. When I try to access it with my ip (from my computer or his) it says it can not connect). It only works from my computer with localhost. This is what I`ve tried:

I replaced in standalone.xml the old  tags with this:

<interfaces>
    <interface name="management">

        <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>

    </interface>

    <interface name="public">

        <inet-address value="${jboss.bind.address:0.0.0.0}"/>

    </interface>
</interfaces>

But it doesn`t work...Do you have any solutions ? Thank you


问:
Python-How to handle X display error in python exception
While I am trying to execute python code with wx package in SSH getting below error.
    "Unable to access the X Display, is $DISPLAY set properly?"

I need to catch this in exception block but this error is not coming under any built-in python exceptions type.

It would be helpful if anyone handled the same situation.

答:
Based on the answer in this post, you can get this behaviour in a python script as follows:

```<code>import subprocess
output = subprocess.check_output(["xset", "q"], stderr=subprocess.STDOUT)
print(output)
</code>```

This script will printout the results of the xset q command if an X server is available. If I damage my $DISPLAY variable then it fails with a python exception:
subprocess.CalledProcessError: Command '['xset', 'q']' returned non-zero exit status 1

So you could put this in a try: and if it fails, you know something is up with displaying the X window. It might be due to a bad or missing DISPLAY variable, or something else but it should indicate that attempting to show the wx window is likely to fail.

Body:
Based on the answer in this post, you can get this behaviour in a python script as follows:

import subprocess
output = subprocess.check_output(["xset", "q"], stderr=subprocess.STDOUT)
print(output)

This script will printout the results of the xset q command if an X server is available. If I damage my $DISPLAY variable then it fails with a python exception:
subprocess.CalledProcessError: Command '['xset', 'q']' returned non-zero exit status 1

So you could put this in a try: and if it fails, you know something is up with displaying the X window. It might be due to a bad or missing DISPLAY variable, or something else but it should indicate that attempting to show the wx window is likely to fail.


问:
Where to start with JSP, Struts2 and CRUD?
I was wondering if anyone had a recommendation on where to start with JSP development using Struts2, with a target of creating CRUD (Create-Read-Update-Delete) applications.

I have a few links that I found through Google, but I am looking for some quick advice before I start some serious learning.   All I have done up to this point is experiment with JSP, JSTL, and Hibernate a little.   I use Eclipse with JBoss5 as a platform but I also like Tomcat (if thats possible).

答:
My Best advise is to download sample applications from Struts2 official site.it will help you to get the initial things and other required start up.
If you want to get ideas about Struts2 tags these sample applications are good to start and rest you can keep adding while you learning this.
regarding CRUD operation all you have to get familiar with Struts2 MVC work flow and how to do your underlying DB operations are completely independent of Struts2</p>


问:
Updating rows in Android SQlite
I'm using SQlite in my Android app and the task is - how can I update all the rows in one table?
I have a 1st column with name "cl_id" (integer numbers 1-2-3-4..) and after deleting some rows, I wan't to make a cycle to fill this 1st column with a new values to keep them in right order.

I was trying to execute:

```<code>        data.put("cl_id",index);
        db.update("mdb_table_contactList", data, null, null);
</code>```

but it's updates all the values in the first column :(

答:
"just give rowId and type of data that is going to be update in ContentValues."

public void updateStatus(String id , int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues data = new ContentValues();

data.put("status", status);

db.update(TableName, data, "columnName" + " = "+id , null);

}

Title: Updating rows in Android SQlite

Body:
I'm using SQlite in my Android app and the task is - how can I update all the rows in one table?
I have a 1st column with name "cl_id" (integer numbers 1-2-3-4..) and after deleting some rows, I wan't to make a cycle to fill this 1st column with a new values to keep them in right order.

I was trying to execute:

        data.put("cl_id",index);
        db.update("mdb_table_contactList", data, null, null);

but it's updates all the values in the first column :(


问:
Dataclasses and property decorator
I've been reading up on Python 3.7's dataclass as an alternative to namedtuples (what I typically use when having to group data in a structure). I was wondering if dataclass is compatible with the property decorator to define getter and setter functions for the data elements of the dataclass. If so, is this described somewhere? Or are there examples available? </p>

答:
Following a very thorough post about data classes and properties that can be found here the TL;DR version which solves some very ugly cases where you have to call MyClass(_my_var=2) and strange __repr__ outputs:

from dataclasses import field, dataclass

@dataclass
class Vehicle:

    wheels: int
    _wheels: int = field(init=False, repr=False)

    def __init__(self, wheels: int):
       self._wheels = wheels

    @property
    def wheels(self) -> int:
         return self._wheels

    @wheels.setter
    def wheels(self, wheels: int):
        self._wheels = wheels
```

Title: Dataclasses and property decorator


问:
when I click a button in a list of buttons, it changes all of them instead of only one -Angular
I have a problem with changing the text inside a button when clicked

I have a list of buttons in my HTML displaying  a list of angular material:

  <ng-container matColumnDef="finishDate">
     Estimated Finish
     {{ element.finishDate | date: 'medium'}}
  </ng-container>

  <ng-container matColumnDef="buildId">
     Cancel

      <button mat-flat-button color="accent
 (click)="cancelBuildingImage(element.buildId); setCancelingText($event)">
            {{content}}
      </button>

  </ng-container>

```

<p>My <code>.ts</code></p>

<pre class="lang-js prettyprint-override"><code>export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];

  content: string;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.content = "Cancel build"
  }
  setCancelingText($event) {
    this.content = "Canceling..."
  }

  private populateBuildingImageList(): void {
    this.builderService.getBuildingImageList().then(response => {
      this.buildingImageErrorMessage = null;
      this.buildingImageList = response;
      this.convertDurationToDate();
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error getting the company list.";
    });
  }

public cancelBuildingImage(buildId: string): void {
    console.log("button pressed")
    this.builderService.cancelBuildingImage(buildId).then(() => {
      this.snackMessageService.sendMessage("Build canceled.");
      this.populateBuildingImageList(); // No se si es necesario, porque ya se llama en el builder.service
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error canceling the image build."
    });
  }
</code>```

Clicking one button changes the text of all my button settings and the value is canceled.

How do I change only one-button text when clicked? The dataSource is an object with the keys displayed as columns (example: finishDate) and it doesn't allow me to interact with the text button.

答: {{content}} should be something like {{element.content}}. Click event functions should also need to change accordingly

Body:
I have a problem with changing the text inside a button when clicked

I have a list of buttons in my HTML displaying  a list of angular material:

  <ng-container matColumnDef="finishDate">
     Estimated Finish
     {{ element.finishDate | date: 'medium'}}
  </ng-container>

  <ng-container matColumnDef="buildId">
     Cancel

      <button mat-flat-button color="accent
 (click)="cancelBuildingImage(element.buildId); setCancelingText($event)">
            {{content}}
      </button>

  </ng-container>

My .ts

export class BuildingImagesComponent implements OnInit, OnDestroy {
  buildingImageList: BuildingImage[];
  displayedColumns: string[] = ["tag", "created", "startedBuilding", "finishDate", "buildId"];

  content: string;

  constructor(private builderService: BuilderService, private snackMessageService: SnackMessageService) {
    this.content = "Cancel build"
  }
  setCancelingText($event) {
    this.content = "Canceling..."
  }

  private populateBuildingImageList(): void {
    this.builderService.getBuildingImageList().then(response => {
      this.buildingImageErrorMessage = null;
      this.buildingImageList = response;
      this.convertDurationToDate();
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error getting the company list.";
    });
  }

public cancelBuildingImage(buildId: string): void {
    console.log("button pressed")
    this.builderService.cancelBuildingImage(buildId).then(() => {
      this.snackMessageService.sendMessage("Build canceled.");
      this.populateBuildingImageList(); // No se si es necesario, porque ya se llama en el builder.service
    }).catch(() => {
      this.buildingImageErrorMessage = "Oops, there was an error canceling the image build."
    });
  }

Clicking one button changes the text of all my button settings and the value is canceled.

How do I change only one-button text when clicked? The dataSource is an object with the keys displayed as columns (example: finishDate) and it doesn't allow me to interact with the text button.


问:
Firebase Remote Config on Vue
i've just tried to integrate firebase custom config at Vue. I'm newbie at this and got error like this

I already add firebase sdk to my project.
This is my main.js

```<code>
Vue.config.productionTip = false

const config = {
  apiKey: "######################",
    authDomain: "######################",
    databaseURL: "######################",
    projectId: "######################",
    storageBucket: "######################",
    messagingSenderId: "######################",
    appId: "######################",
    measurementId: "######################"
 };
firebase.initializeApp(config);

new Vue({
  router,
  vuetify,
  render: h => h(App)
}).$mount('#app')
</code>```

and I want to use firebase remote config on my View

```<code><script>
import firebase from "firebase";

  remoteConfig = firebase.remoteConfig();

  // [START enable_dev_mode]
  remoteConfig.settings = {
    minimumFetchIntervalMillis: 3600000,
  };
  // [END enable_dev_mode]
  // [START set_default_values]
  remoteConfig.defaultConfig = ({
    'is_auto_location': 'false',
  });
  // [END set_default_values]

  remoteConfig.ensureInitialized()
  .then(() => {
    console.log('Firebase Remote Config is initialized');
    setLocation();
  })
  .catch((err) => {
    console.error('Firebase Remote Config failed to initialize', err);
  });

  function setLocation() {
    this.isAutoLocation = remoteConfig.getString('is_auto_location');
  }

</script>
</code>```

please help.
Thankyou

答:
import firebase in main.js file import * as firebase from 'firebase'

there have an awesome vuejs package for firebase call vuefire. you can use it

Title: Firebase Remote Config on Vue

Body:
i've just tried to integrate firebase custom config at Vue. I'm newbie at this and got error like this

I already add firebase sdk to my project.
This is my main.js

Vue.config.productionTip = false

const config = {
  apiKey: "######################",
    authDomain: "######################",
    databaseURL: "######################",
    projectId: "######################",
    storageBucket: "######################",
    messagingSenderId: "######################",
    appId: "######################",
    measurementId: "######################"
 };
firebase.initializeApp(config);

new Vue({
  router,
  vuetify,
  render: h => h(App)
}).$mount('#app')

and I want to use firebase remote config on my View

please help.
Thankyou


问:
Continually sending GPS data to the Android emulator
I am writing an app for Android that will measure speed as the Android device is moving, using the GPS receiver. I know I can telnet into the Android emulator and send Geo coordinates using the "geo fix" command. What I want to know though, is there a way to continually send geo fix data to simulate a car moving down a street? Otherwise, how else can I test my application?</p>

答: write the application and install the apk file in a GPS enabled android mobile. you can see the approximate speed at which the android mobile is moving from place to place.</p>


问:
com.android.volley.noconnectionerror:javax.net.SSLHandshakeException:
who knows how can solves this problem?

com.android.volley.noconnectionerror:javax.net.SSLHandshakeException:java.security.cert.CertPathVaildatorException: Trust anchor for certification path not found.

```<code>implementation 'com.android.volley:volley:1.1.0'

private static String URL_REGIST = "https://192.168.1.126/functions.php";

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String success = jsonObject.getString("successs");
                        //Log.d("123: " ,  response);
                        if (success.equals("1")){
                            Toast.makeText(RegistActivity.this,"Register Success!", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        //Log.e("456: ", response);
                        Toast.makeText(RegistActivity.this,"Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
                        accountloading.setVisibility(View.GONE);
                        btn_regist.setVisibility(View.VISIBLE);
                    }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(RegistActivity.this,"Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
                        accountloading.setVisibility(View.GONE);
                        btn_regist.setVisibility(View.VISIBLE);
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("lastname", lastname);
                params.put("firstname", firstname);
                params.put("nickname", nickname);
                params.put("password", password);
                //params.put("birthday", birthday);
                params.put("email", email);
                //params.put("phone", phone);
                return params;
            }
        };
</code>```

I don't know what's happening.

below is my php code and it's can link to DB. But I dont know what get errors.

```<code>if ($_SERVER['REQUEST_METHOD'] == 'POST'){

        $lastname = $_POST['lastname'];
        $firstname = $_POST['firstname'];
        $nickname = $_POST['nickname'];
        $password1 = $_POST['password'];
        //$birthday = $_POST['birthday'];
        $email = $_POST['email'];
        //$phone = $_POST['phone'];

        $password1 = password_hash($password1, PASSWORD_DEFAULT);

        require_once 'connect.php';

       $sql = "INSERT INTO user (lastname, firstname, nickname, password1, email)
        VALUES
        ('$lastname','$firstname', '$nickname', '$password1', '$email')";

        //$sql = "INSERT INTO user (lastname, firstname, nickname, password1, birthday, email, phone)
        //VALUES
        //('$lastname','$firstname', '$nickname', '$password1', '$birthday', '$email', '$phone')";

        if (mysqli_query($conn, $sql)){
            $result["success"] = "1";
            $result["message"] = "Success";
            echo json_encode($result);
            mysqli_close($conn);
        } else {
            $result["success"] = "0";
            $result["message"] = "Error";
            echo json_encode($result);
            mysqli_close($conn);
        }
    }
</code>```

答:
Problem is you are using private static String URL_REGIST = "https://192.168.1.126/functions.php"; as URL.

But your local IP address 192.168.1.126 does not have a valid SSL certificate.
To fix this you can use http instead of https for your local URL.

Please note, you should still use https when deploying to a real server if you have a valid SSL certificate for your real URL.

Body:
who knows how can solves this problem?

com.android.volley.noconnectionerror:javax.net.SSLHandshakeException:java.security.cert.CertPathVaildatorException: Trust anchor for certification path not found.

implementation 'com.android.volley:volley:1.1.0'

private static String URL_REGIST = "https://192.168.1.126/functions.php";

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String success = jsonObject.getString("successs");
                        //Log.d("123: " ,  response);
                        if (success.equals("1")){
                            Toast.makeText(RegistActivity.this,"Register Success!", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        //Log.e("456: ", response);
                        Toast.makeText(RegistActivity.this,"Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
                        accountloading.setVisibility(View.GONE);
                        btn_regist.setVisibility(View.VISIBLE);
                    }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(RegistActivity.this,"Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
                        accountloading.setVisibility(View.GONE);
                        btn_regist.setVisibility(View.VISIBLE);
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("lastname", lastname);
                params.put("firstname", firstname);
                params.put("nickname", nickname);
                params.put("password", password);
                //params.put("birthday", birthday);
                params.put("email", email);
                //params.put("phone", phone);
                return params;
            }
        };

I don't know what's happening.

below is my php code and it's can link to DB. But I dont know what get errors.

if ($_SERVER['REQUEST_METHOD'] == 'POST'){

        $lastname = $_POST['lastname'];
        $firstname = $_POST['firstname'];
        $nickname = $_POST['nickname'];
        $password1 = $_POST['password'];
        //$birthday = $_POST['birthday'];
        $email = $_POST['email'];
        //$phone = $_POST['phone'];

        $password1 = password_hash($password1, PASSWORD_DEFAULT);

        require_once 'connect.php';

       $sql = "INSERT INTO user (lastname, firstname, nickname, password1, email)
        VALUES
        ('$lastname','$firstname', '$nickname', '$password1', '$email')";

        //$sql = "INSERT INTO user (lastname, firstname, nickname, password1, birthday, email, phone)
        //VALUES
        //('$lastname','$firstname', '$nickname', '$password1', '$birthday', '$email', '$phone')";

        if (mysqli_query($conn, $sql)){
            $result["success"] = "1";
            $result["message"] = "Success";
            echo json_encode($result);
            mysqli_close($conn);
        } else {
            $result["success"] = "0";
            $result["message"] = "Error";
            echo json_encode($result);
            mysqli_close($conn);
        }
    }


问:
Encoding Problem: Atom can't print UTF-8 ('ä ö ü')
I got a new machine and after setting everything up, the IDE Atom somehow can't print the UTF-8 characters 'ä ö ü' anymore (other such characters probably as well).
It is super strange and I have this problem since moving to this new PC of mine.

Here is a screenshot of the problem:

I'm using:

Windows 10 Pro 64-Bit

Python 3.7.4 via Anaconda 1.9.7

Atom 1.44.0

platformio-ide-terminal 2.10.0 (as a terminal inside Atom)

the system-wide environment variable: PYTHONIOENCODING=UTF-8

Did anybody encounter this problem as well and knows how to fix it?

Thanks in advance!

EDIT with solution

Solution 1:
snakecharmerb (the user on here) commented, that I need to declair the encoding when opening the file 'test.py' with the following command:

```<code>open('test.py', encoding='utf-8')
</code>```

That worked!
His/her comment was removed for some reason, but yeah, it worked. Thank you!

Solution 2:
In order to not have to declare the encoding every time, I looked into changing the systems default encoding. Windows 10 has an easy but kind of hidden solution for that:

Open Control panel >> Clock and Region >> Region >> Administrative tab >> Change system locale... >> checkmark 'Beta: Use Unicode UTF-8 for worldwide language support'

Thanks for the amazingly fast help everyone!

答:
You can try exporting PYTHONIOENCODING=utf-8

if that doesn't work you can try setting your environment variables in python to

```<code>LANG=en_US.UTF-8
</code>```

Body:
I got a new machine and after setting everything up, the IDE Atom somehow can't print the UTF-8 characters 'ä ö ü' anymore (other such characters probably as well).
It is super strange and I have this problem since moving to this new PC of mine.

Here is a screenshot of the problem:

I'm using:

Windows 10 Pro 64-Bit

Python 3.7.4 via Anaconda 1.9.7

Atom 1.44.0

platformio-ide-terminal 2.10.0 (as a terminal inside Atom)

the system-wide environment variable: PYTHONIOENCODING=UTF-8

Did anybody encounter this problem as well and knows how to fix it?

Thanks in advance!

EDIT with solution

Solution 1:
snakecharmerb (the user on here) commented, that I need to declair the encoding when opening the file 'test.py' with the following command:

open('test.py', encoding='utf-8')

That worked!
His/her comment was removed for some reason, but yeah, it worked. Thank you!

Solution 2:
In order to not have to declare the encoding every time, I looked into changing the systems default encoding. Windows 10 has an easy but kind of hidden solution for that:

Open Control panel >> Clock and Region >> Region >> Administrative tab >> Change system locale... >> checkmark 'Beta: Use Unicode UTF-8 for worldwide language support'

Thanks for the amazingly fast help everyone!

Body:
You can try exporting PYTHONIOENCODING=utf-8

if that doesn't work you can try setting your environment variables in python to

LANG=en_US.UTF-8


问:
Is there a way to get child class file path in parent class?
I have a parent class file A.js and child class file B.js

```<code>//A.js
class A {
  constructor(){
    console.log(__filename)
  }
}

//B.js
class B extends A {
  constructor() {
    super();
  }
}
new B()
//will output A.js
</code>```

Is there a way to get B.js path in a.js?

答:
It is possible to accomplish this by changing the constructor of A to take an argument like so:</p>

```<code>class A {
    constructor(arg){
        console.log(arg)
    }
}

//B.js
class B extends A {
    constructor() {
        super(__filename);
    }
}

new B();
</code>```

Body:
I have a parent class file A.js and child class file B.js

//A.js
class A {
  constructor(){
    console.log(__filename)
  }
}

//B.js
class B extends A {
  constructor() {
    super();
  }
}
new B()
//will output A.js

Is there a way to get B.js path in a.js?

Body:
It is possible to accomplish this by changing the constructor of A to take an argument like so:

class A {
    constructor(arg){
        console.log(arg)
    }
}

//B.js
class B extends A {
    constructor() {
        super(__filename);
    }
}

new B();


问:
Best way restructure object in JS
I have array of objects, width date and time property like below. I try restructure elements by day and time.

```<code>[
  {
    data: 'data1',
    date: '15-02-2020 06:00:00'
  },
  {
    data: 'data2',
    date: '15-02-2020 12:00:00'
  },
  ...
  {
    data: 'data6',
    date: '17-02-2020 07:00:00'
  },
  {
    data: 'data7',
    date: '17-02-2020 09:00:00'
  }
]
</code>```

I want to get this:

```<code>{
  '15-02-2020' : {
    '06:00:00' : 'data1',
    '12:00:00' : 'data2'
  },
  '16-02-2020' : {
    '06:00:00' : 'data3',
    '12:00:00' : 'data4'
  },
  '17-02-2020' : {
    '01:00:00' : 'data5',
    '07:00:00' : 'data6',
    '09:00:00' : 'data7'
  }
}
</code>```

I tried use reduce, but cant. I want do that, without temporary variables in one loop.

```<code>list.reduce((obj, item) => Object.assign(obj, {[item.date]: item}), {});
</code>```

答:
Just loop through your array and build the result object dynamically:

const arr = [
  {
    data: 'data1',
    date: '15-02-2020 06:00:00'
  },
  {
    data: 'data2',
    date: '15-02-2020 12:00:00'
  },
  {
    data: 'data6',
    date: '17-02-2020 07:00:00'
  },
  {
    data: 'data7',
    date: '17-02-2020 09:00:00'
  }
]

const res = {}

arr.forEach(item => {
  const dateArr = item.date.split(' ')
  if (res[dateArr[0]]) {
    res[dateArr[0]][dateArr[1]] = item.data
  } else {
    res[dateArr[0]] = {}
    res[dateArr[0]][dateArr[1]] = item.data
  }
})

console.log(res)```

Title: Best way restructure object in JS

Body:
I have array of objects, width date and time property like below. I try restructure elements by day and time.

[
  {
    data: 'data1',
    date: '15-02-2020 06:00:00'
  },
  {
    data: 'data2',
    date: '15-02-2020 12:00:00'
  },
  ...
  {
    data: 'data6',
    date: '17-02-2020 07:00:00'
  },
  {
    data: 'data7',
    date: '17-02-2020 09:00:00'
  }
]

I want to get this:

{
  '15-02-2020' : {
    '06:00:00' : 'data1',
    '12:00:00' : 'data2'
  },
  '16-02-2020' : {
    '06:00:00' : 'data3',
    '12:00:00' : 'data4'
  },
  '17-02-2020' : {
    '01:00:00' : 'data5',
    '07:00:00' : 'data6',
    '09:00:00' : 'data7'
  }
}

I tried use reduce, but cant. I want do that, without temporary variables in one loop.

list.reduce((obj, item) => Object.assign(obj, {[item.date]: item}), {});


问:
Filling a model with a list from Textarea
Now I do not really understand you. Sorry, I just started this whole study not so long ago. I’ll try to explain again what I can’t do.
I have an empty object and an object with data with the same structure.

```<code>data: [
        {id: 1, title: "title1"},
        {id: 2, title: "title1"},
        {id: 3, title: "title3"},
        {id: 4, title: "title4"},
        {id: 5, title: "title3"}
      ],

item: [
        {
          itemId: "",
          itemname: ""
        }
      ]
</code>```

And I have select and textarear. Select have data, textarear empty. Textarear displays title.

I want to press a button. Selected item from select. copied to textarear (title only), and also itemId - this selected element id: 5 and itemname - the same title: "title3" element, was recorded in item [].

https://codesandbox.io/s/priceless-hermann-g9flw

答:
Please do check now </p>

```<code>import React from "react";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      id: null,
      title: "",
      filmItem: "",
      listFilms: [],
      data: [
        { id: 1, title: "title1" },
        { id: 2, title: "title2" },
        { id: 3, title: "title3" },
        { id: 4, title: "title4" }
      ],
      item: []
    };
    this.onChange = this.onChange.bind(this);
    this.onChangeArea = this.onChangeArea.bind(this);
    this.addFilm = this.addFilm.bind(this);
    this.choice = this.choice.bind(this);
  }

  addFilm(film) {
    const selectedData = this.state.data.find(item => item.id == film);
    console.log(selectedData);
    this.setState({
      listFilms: [...this.state.listFilms, selectedData.title],
      item: [
        ...this.state.item,
        { itemId: selectedData.id, itemname: selectedData.title }
      ]
    });
  }

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onChangeArea = e => {
    this.setState({ [e.target.name]: e.target.value.split("\n") });
  };

  choice(title) {
    this.setState({ filmItem: title });
  }

  render() {
    return (
      <div className="App">
        <div className="row App-main">
          <div>
            <select name="filmItem" size="4" onChange={e => this.onChange(e)}>
              {this.state.data.map(film => (
                <option key={film.title} value={film.id}>
                  {film.title}
                </option>
              ))}
            </select>
          </div>
          <div>
            <button
              className="editButton"
              onClick={() => this.addFilm(this.state.filmItem)}
            >
              button
            </button>
          </div>
          <div>
            <textarea
              name="films"
              onChange={this.onChangeArea}
              value={this.state.listFilms.map(r => r).join("\n")}
            />
          </div>
          <div>
            <input type="text" name="text-input" onChange={this.onChange} />
          </div>
        </div>
        <pre style={{ whiteSpace: "pre-wrap" }}>
          {JSON.stringify(this.state)}
        ```
      </div>
    );
  }
}
export default App;
</code>```

Body:
Now I do not really understand you. Sorry, I just started this whole study not so long ago. I’ll try to explain again what I can’t do.
I have an empty object and an object with data with the same structure.

data: [
        {id: 1, title: "title1"},
        {id: 2, title: "title1"},
        {id: 3, title: "title3"},
        {id: 4, title: "title4"},
        {id: 5, title: "title3"}
      ],

item: [
        {
          itemId: "",
          itemname: ""
        }
      ]

And I have select and textarear. Select have data, textarear empty. Textarear displays title.

I want to press a button. Selected item from select. copied to textarear (title only), and also itemId - this selected element id: 5 and itemname - the same title: "title3" element, was recorded in item [].

https://codesandbox.io/s/priceless-hermann-g9flw

Body:
Please do check now

import React from "react";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      id: null,
      title: "",
      filmItem: "",
      listFilms: [],
      data: [
        { id: 1, title: "title1" },
        { id: 2, title: "title2" },
        { id: 3, title: "title3" },
        { id: 4, title: "title4" }
      ],
      item: []
    };
    this.onChange = this.onChange.bind(this);
    this.onChangeArea = this.onChangeArea.bind(this);
    this.addFilm = this.addFilm.bind(this);
    this.choice = this.choice.bind(this);
  }

  addFilm(film) {
    const selectedData = this.state.data.find(item => item.id == film);
    console.log(selectedData);
    this.setState({
      listFilms: [...this.state.listFilms, selectedData.title],
      item: [
        ...this.state.item,
        { itemId: selectedData.id, itemname: selectedData.title }
      ]
    });
  }

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onChangeArea = e => {
    this.setState({ [e.target.name]: e.target.value.split("\n") });
  };

  choice(title) {
    this.setState({ filmItem: title });
  }

  render() {
    return (
      <div className="App">
        <div className="row App-main">
          <div>
            <select name="filmItem" size="4" onChange={e => this.onChange(e)}>
              {this.state.data.map(film => (
                <option key={film.title} value={film.id}>
                  {film.title}
                </option>
              ))}
            </select>
          </div>
          <div>
            <button
              className="editButton"
              onClick={() => this.addFilm(this.state.filmItem)}
            >
              button
            </button>
          </div>
          <div>
            <textarea
              name="films"
              onChange={this.onChangeArea}
              value={this.state.listFilms.map(r => r).join("\n")}
            />
          </div>
          <div>
            <input type="text" name="text-input" onChange={this.onChange} />
          </div>
        </div>
        <pre style={{ whiteSpace: "pre-wrap" }}>
          {JSON.stringify(this.state)}
        </pre>
      </div>
    );
  }
}
export default App;


问:
How to set value to XML element with Set-body Policy of API Management
In this case, I want to get an accessTokenTest first, then I will create an SOAP request by using this accessTokenTest. But I have a problem with adding this accessTokenTest to an XML element. Everything fine except filling this value into XML.

<set-variable name="accessTokenTest" value="@(((IResponse)context.Variables["ABCOauth"]).Body.As<JObject>()["access_token"].ToString())" />
<set-body template="liquid">
   <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://servicxxxx>
    <soap:Body>
     <GetUsersxxx>
      <userIds>
{% for item in body.getUserxxxx.userIds -%}
<string>{{item}}</string>
{% endfor -%}
</userIds>
      <credentials>
       <Client>{{body.getUsersByUserId.credentials.client}}</Client>
       <AccessToken>(string)context.Variables.GetValueOrDefault("accessTokenTest")</AccessToken>
      </credentials>
     </GetUsersxxxx>
    </soap:Body>
   </soap:Envelope>
</set-body>```

答:
When using liquid templates in the set-body policy, there is a different syntax for accessing the context object as shown in the docs, similar to what you have used for the client value.

In your case, the policy would have to look something like this

<set-variable name="accessTokenTest" value="@(((IResponse)context.Variables["ABCOauth"]).Body.As<JObject>()["access_token"].ToString())" />
<set-body template="liquid">
  <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns="http://servicxxxx>
    <soap:Body>
      <GetUsersxxx>
        <userIds>
{% for item in body.getUserxxxx.userIds -%}
          <string>{{item}}</string>
{% endfor -%}
        </userIds>
        <credentials>
          <Client>{{body.getUsersByUserId.credentials.client}}</Client>
          <AccessToken>{{context.Variables["accessTokenTest"]}}</AccessToken>
        </credentials>
      </GetUsersxxxx>
    </soap:Body>
  </soap:Envelope>
</set-body>
```


问:
Ansible command inside a playbook with shell module
Can I use something as below in ansible:

```<code>---
- hosts: webserver
  gather_facts: False
  tasks:

    - name: Check ping
      shell: ansible -i localhost.yml  -m shell -a 'ping'
</code>```

That localhost contains all hosts whereas playbook will run on webserver.

Actual  requirement is to run on webserver whereas in one task I need to run a command on all hosts specified in the host file.

Thanks in advance!

Just to add error is :

```<code> fatal: [webservice]: FAILED! => {
        "changed": true,
        "cmd": "ansible -i localhost.yml  -m shell -a 'ping'",
        "delta": "0:00:00.009121",
        "end": "2020-02-12 04:47:06.174390",
        "invocation": {
            "module_args": {
                "_raw_params": "ansible -i   localhost.yml -m shell -a 'ping'",
                "_uses_shell": true,
                "argv": null,
                "chdir": null,
                "creates": null,
                "executable": null,
                "removes": null,
                "stdin": null,
                "stdin_add_newline": true,
                "strip_empty_ends": true,
                "warn": true
            }
        },
        "msg": "non-zero return code",
        "rc": 127,
        "start": "2020-02-12 04:47:06.165269",
        "stderr": "ansible: not found",
        "stderr_lines": [
            "ansible: not found"
        ],
        "stdout": "",
        "stdout_lines": [] }
</code>```

答:
You want to run an ansible playbook or a shell command inside a server ?
If you want to run a shell command then don't mention playbook name. If you want to run a playbook then don't mention -m shell -a shell parameter.

Body:
Can I use something as below in ansible:

---
- hosts: webserver
  gather_facts: False
  tasks:

    - name: Check ping
      shell: ansible -i localhost.yml  -m shell -a 'ping'

That localhost contains all hosts whereas playbook will run on webserver.

Actual  requirement is to run on webserver whereas in one task I need to run a command on all hosts specified in the host file.

Thanks in advance!

Just to add error is :

 fatal: [webservice]: FAILED! => {
        "changed": true,
        "cmd": "ansible -i localhost.yml  -m shell -a 'ping'",
        "delta": "0:00:00.009121",
        "end": "2020-02-12 04:47:06.174390",
        "invocation": {
            "module_args": {
                "_raw_params": "ansible -i   localhost.yml -m shell -a 'ping'",
                "_uses_shell": true,
                "argv": null,
                "chdir": null,
                "creates": null,
                "executable": null,
                "removes": null,
                "stdin": null,
                "stdin_add_newline": true,
                "strip_empty_ends": true,
                "warn": true
            }
        },
        "msg": "non-zero return code",
        "rc": 127,
        "start": "2020-02-12 04:47:06.165269",
        "stderr": "ansible: not found",
        "stderr_lines": [
            "ansible: not found"
        ],
        "stdout": "",
        "stdout_lines": [] }


问:
Keras model not training layers, validation accuracy always 0.5
My Keras CNN model (based on an implementation of AlexNet) always has training accuracy close to 0.5 (within +- 0.02) and the validation accuracy is always 0.5 exactly, no matter which epoch. It is a binary classification model where the train/val split is roughly 85/15 and within both those sets the images are split 50/50 for each class.

It doesn't seem to matter which model architecture I use, or whether I initalise with random or ImageNet weights, the validation accuracy is always 0.5. In fact, when I didn't have the images split 50/50 into their binary classifications, the validation accuracy would reflect this (so when I had significantly more images belonging to one class, the validation accuracy would always be 0.85).

Because of this last point, I have a suspicion the problem doesn't lie with the model or weight optimisation, but rather with my instantiation of the ImageDataGenerator class - although this is just an educated hunch at this stage.

I've included my code below, can anyone locate any blindingly obvious errors?

```<code>sz=224 # image width = height = 224
batch_size=64
train_data_dir = r"./crack_dataset/train"
validation_data_dir = r"./crack_dataset/validate"
nb_train_samples = 3416
nb_val_samples = 612

train_datagen = ImageDataGenerator(rescale=1./255)

validation_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_data_dir,
                                                    target_size = (sz, sz),
                                                    batch_size=batch_size,
                                                    class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(validation_data_dir,
                                                              target_size = (sz, sz),
                                                              batch_size=batch_size,
                                                              class_mode='binary')

# Create Model
model = Sequential()

model.add(Conv2D(filters=96, input_shape=input_shape, kernel_size=(11,11), strides=(4,4), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=256, kernel_size=(11,11), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Flatten())
model.add(Dense(4096, input_shape=(256,), activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer=Adam(0.1), loss='binary_crossentropy', metrics=['accuracy'])

model.fit_generator(train_generator,
                    steps_per_epoch = nb_train_samples // batch_size,
                    epochs=30,
                    validation_data=validation_generator,
                    validation_steps=nb_val_samples // batch_size)
</code>```

答:
It was a comment, but too long so I switched to a proper answer.

I haven't tried your CNN, but I would revise your layers. I'm not an expert in designing CNN architectures but I don't see a lot of meaning in having 2 layers in a row with the same parameters (5th and 6th layers), it's pretty useless for what I've learned so far. Try with some simple architecture and "scale up" (in terms of complexity of the architecture) from there.

Furthermore, going up and down in terms of "number of units" ( 1st, 3rd, 5th, 6th, 7th layers, Conv2D) might not be the best strategy, everytime you go up you generalize in terms of features to get because you start from less features, you are asking to your network to create features from a smaller set. There are some scenarios where it might be useful, but I don't think this is one of them.

And for the rescaling you don't need to call "ImageDataGenerator", you can reach the same result with:

train_datagen = train_datagen/255.0

Simplify where you can.

Body:
My Keras CNN model (based on an implementation of AlexNet) always has training accuracy close to 0.5 (within +- 0.02) and the validation accuracy is always 0.5 exactly, no matter which epoch. It is a binary classification model where the train/val split is roughly 85/15 and within both those sets the images are split 50/50 for each class.

It doesn't seem to matter which model architecture I use, or whether I initalise with random or ImageNet weights, the validation accuracy is always 0.5. In fact, when I didn't have the images split 50/50 into their binary classifications, the validation accuracy would reflect this (so when I had significantly more images belonging to one class, the validation accuracy would always be 0.85).

Because of this last point, I have a suspicion the problem doesn't lie with the model or weight optimisation, but rather with my instantiation of the ImageDataGenerator class - although this is just an educated hunch at this stage.

I've included my code below, can anyone locate any blindingly obvious errors?

sz=224 # image width = height = 224
batch_size=64
train_data_dir = r"./crack_dataset/train"
validation_data_dir = r"./crack_dataset/validate"
nb_train_samples = 3416
nb_val_samples = 612

train_datagen = ImageDataGenerator(rescale=1./255)

validation_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(train_data_dir,
                                                    target_size = (sz, sz),
                                                    batch_size=batch_size,
                                                    class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(validation_data_dir,
                                                              target_size = (sz, sz),
                                                              batch_size=batch_size,
                                                              class_mode='binary')

# Create Model
model = Sequential()

model.add(Conv2D(filters=96, input_shape=input_shape, kernel_size=(11,11), strides=(4,4), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=256, kernel_size=(11,11), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=384, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))

model.add(Conv2D(filters=256, kernel_size=(3,3), strides=(1,1), padding='valid', activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='valid'))

model.add(Flatten())
model.add(Dense(4096, input_shape=(256,), activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.4))

model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer=Adam(0.1), loss='binary_crossentropy', metrics=['accuracy'])

model.fit_generator(train_generator,
                    steps_per_epoch = nb_train_samples // batch_size,
                    epochs=30,
                    validation_data=validation_generator,
                    validation_steps=nb_val_samples // batch_size)


问:
how to use "text.changed" control from code using MVVM (in Xamarin.Forms)
I am trying to make a text box change its color when an entry's text meets some requisites, calling a function form my ViewModel every time a new character is added to the text, and I am using FreshMVVM, meaning that I cant directly use the control "text.changed" since bindings can't be used for controls (if I am not mistaken).

Looking for answers I have found the nugget package "Behaviors.Forms", which would let me do it.
The problem is that I am not using an entry perse, but a custom view that works as an entry, and the previously mentioned package doesn't let me use entry.behaviors for my custom entry.

Most of the posts and discussions about this matter were old (from 2016 or 2017), so is there any way to bind controls to your ViewModel now?, and if not, is there any way to do the specific task that I have explained?

Thank you all for your time, hope you have a good day.

答:
You can use Behaviors, They are used to enhance the functionality of a control.
this link : https://xamarinhelp.com/xamarin-forms-triggers-behaviors-effects/ : discusses a similar use case u are looking for.

your code should be something like this,

```<code>public class DoSomethingOnTextChanged: Behavior<>
{

    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += bindable_TextChanged;
    }

    private void bindable_TextChanged(object sender, TextChangedEventArgs e)
    {
       var newTextValue = (string)e.NewTextValue;
       //Do Some Logic
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= bindable_TextChanged;
    }
}
</code>```

Body:
You can use Behaviors, They are used to enhance the functionality of a control.
this link : https://xamarinhelp.com/xamarin-forms-triggers-behaviors-effects/ : discusses a similar use case u are looking for.

your code should be something like this,

public class DoSomethingOnTextChanged: Behavior<>
{

    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += bindable_TextChanged;
    }

    private void bindable_TextChanged(object sender, TextChangedEventArgs e)
    {
       var newTextValue = (string)e.NewTextValue;
       //Do Some Logic
    }

    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= bindable_TextChanged;
    }
}


问:
Using Hadoop to update MySQL
I'm using my reducers to input data into MySQL.
My concern is that in some cases, multiple reducers are launched for the same key simultaneously. In that case, there is a chance that the DB could be updated twice by the same data.
Is there a way to protect against that?

Would it make sense to turn off autocommit mode in the SQL connection in this case?

答:
You can change setting:

```<code>mapred.reduce.tasks.speculative.execution
</code>```

That would disable speculative execution of reduce tasks if this is you case.

The other way I would suggest is to use Sqoop to write to MySQL: http://archive.cloudera.com/cdh/3/sqoop/SqoopUserGuide.html#_literal_sqoop_export_literal

Title: Using Hadoop to update MySQL

Body:
You can change setting:

mapred.reduce.tasks.speculative.execution

That would disable speculative execution of reduce tasks if this is you case.

The other way I would suggest is to use Sqoop to write to MySQL: http://archive.cloudera.com/cdh/3/sqoop/SqoopUserGuide.html#_literal_sqoop_export_literal


问:
how to handle request from gateway to right microservice on jhipster registry?
we used microservice architecture of jhipster and generated three applications
uaa,
microservice,
gateway.
then run uaa and jhipster registry on a server, also we have some full stack developers
who want to develop both gateway and microservice at the same time.

then, they deploy their microservice and gateway on jhipsterRegistery which is located on remote server.
Because of the same name of microservices, jhipsterregistery can not handle requests from gateway to the
right microservice

how to manage this problem?

答:
We had the same problem and solved our issue by using a variable as a microservice application name. Then changed all rest URLs in gateway with this variable.
So each developer just needs to change appname in application.yml in micro the same as the variable in app.constants.ts in the gateway as well.
jhipster</p>


问:
Laravel table relationship to pivot table
I'm confused on how to get my model setup in laravel with a table that is connected to a pivot table.

Here's the problem

Say I have

```<code>Locations
    id
    name

area_types
    id
    name

area_type_location (Pivot table)
    id
    location_id
    area_type_id

area_test
    id
    area_type_location_id
    clean
    headCount
</code>```

Relationship between the tables are different areas type belongs to different locations.
i.e: beach, 25m pools, kids pools, bbq, etc

area_test is connected to the pivot table because the test has to be generated from area that exists, in this case it is area that is registered under different locations. Thus it has to be tested daily, measured, etc.

I understand the structure between area_types and locations for many to many relationship, however I can't get over my head of how do i structure my area_test model? How do I get the data from locations table -> where are my test?

Should I create a model for my pivot table? Is that a good practice in laravel?

Does anyone has the same use case?

I read about eloquent has many through
 relationship but I understand that it does not mention about getting through pivot table. I don't quite get if my use case is the same.

Thanks

答:
There is no need to create a new model for pivot table.
Just declare in Location model below code:

```<code>  /**
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function area_types()
  {
        return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');

  }
</code>```

and declare below code in AreaType model:

```<code>  /**
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function locations()
  {
        return $this->belongsToMany('App\Location', 'area_type_location', 'area_type_id', 'location_id');

  }
</code>```

every time you need to get for example the locations of an area_type in every controller, you can call the function like this: $areatype->locations()->get();

Don't forget to create area_type_location table migration.

Body:
I'm confused on how to get my model setup in laravel with a table that is connected to a pivot table.

Here's the problem

Say I have

Locations
    id
    name

area_types
    id
    name

area_type_location (Pivot table)
    id
    location_id
    area_type_id

area_test
    id
    area_type_location_id
    clean
    headCount

Relationship between the tables are different areas type belongs to different locations.
i.e: beach, 25m pools, kids pools, bbq, etc

area_test is connected to the pivot table because the test has to be generated from area that exists, in this case it is area that is registered under different locations. Thus it has to be tested daily, measured, etc.

I understand the structure between area_types and locations for many to many relationship, however I can't get over my head of how do i structure my area_test model? How do I get the data from locations table -> where are my test?

Should I create a model for my pivot table? Is that a good practice in laravel?

Does anyone has the same use case?

I read about eloquent has many through
 relationship but I understand that it does not mention about getting through pivot table. I don't quite get if my use case is the same.

Thanks

Body:
There is no need to create a new model for pivot table.
Just declare in Location model below code:

  /**
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function area_types()
  {
        return $this->belongsToMany('App\AreaType', 'area_type_location', 'location_id', 'area_type_id');

  }

and declare below code in AreaType model:

  /**
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function locations()
  {
        return $this->belongsToMany('App\Location', 'area_type_location', 'area_type_id', 'location_id');

  }

every time you need to get for example the locations of an area_type in every controller, you can call the function like this: $areatype->locations()->get();

Don't forget to create area_type_location table migration.