问:
Machine learning question(Classifier Evaluation)
2 classifiers evaluation~~~~in bagged committee

I had 2 classifiers~~~~classifier burger and classifier fries~~~

both of them has same error bias~~~with committee size 10~~~

classifier burger has error variance 40~~~found generate non-related model under bagging~~~

classifier fries has error variance 30~~~found generate model with pairwise covariance of 0.3 under bagging~~~~

so which one is better? why?

答: I would prefer the classifier fries, because the error variance is telling that with a smaller volume of data , it's explaining an entire data set due to which the model predictability will is higher. Having higher variance would largely impact the accuracy of the model.</p>


来源: stackexchange

问:
App crash when trying to move intent to another adapter
So I have two Adapter class for RecyclerView. I want the ImageView inside one Adapter class to display the other Adapter class

I already tried to use intent on MainActivity

```<code>// listener for image
        cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
            Intent detail = new Intent(context,DetailAdapter.class);
                context.startActivity(detail);
            }
        }
        ));
</code>```

here is the link for what the application supposed to be
https://ibb.co/gmnnghw
 https://giphy.com/gifs/Y3NK0lHfAcN1dGbCZX

CardViewDeviceAdapter

```<code>package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;

public class CardViewDeviceAdapter extends RecyclerView.Adapter<CardViewDeviceAdapter.CardViewHolder> {

    private Context context;
    private ArrayList<Device> deviceArrayList;
    private ArrayList<Device> getDeviceArrayList() {
        return deviceArrayList;
    }

    public void setDeviceArrayList(ArrayList<Device> deviceArrayList) {
        this.deviceArrayList = deviceArrayList;
    }

    public CardViewDeviceAdapter(Context context) {
        this.context = context;
    }

    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_device, viewGroup, false);
        return new CardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CardViewHolder cardViewHolder, int i) {
        Device d = getDeviceArrayList().get(i);

        Glide.with(context)
                .load(d.getPhoto())
                .apply(new RequestOptions().override(350, 550))
                .into(cardViewHolder.photo);

        cardViewHolder.title.setText(d.getTitle());
        cardViewHolder.detail.setText(d.getDetail());

        // listener untuk button favorite
        cardViewHolder.favorite.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
                Toast.makeText(context, "Favorite device"+getDeviceArrayList()
                .get(position)
                .getTitle()
                , Toast.LENGTH_SHORT).show();
            }
        }
        ));

        // listener untuk button share
        cardViewHolder.share.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
                Toast.makeText(context, "Share device"+getDeviceArrayList()
                                .get(position)
                                .getTitle()
                        , Toast.LENGTH_SHORT).show();
            }
        }
        ));

        // listener untuk image
        cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
                Intent detail = new Intent(context, DetailAdapter.class);
                context.startActivity(detail);
            }
        }
        ));
    }

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

    public class CardViewHolder extends RecyclerView.ViewHolder {
        ImageView photo;
        TextView title, detail;
        Button favorite, share;
        public CardViewHolder(View itemView) {
            super(itemView);
            photo = itemView.findViewById(R.id.pc_photo);
            title = itemView.findViewById(R.id.pc_name);
            detail = itemView.findViewById(R.id.pc_details);
            favorite = itemView.findViewById(R.id.pc_favourite);
            share = itemView.findViewById(R.id.pc_share);
        }
    }
}
</code>```

DetailAdapter

```<code>package com.example.myapplication;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;

public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailHolder> {

    private Context context;
    private ArrayList<Device> deviceArrayList;
    private ArrayList<Device> getDeviceArrayList() {
        return deviceArrayList;
    }

    @NonNull
    @Override
    public DetailAdapter.DetailHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.detail_adapter, viewGroup, false);
        return new DetailAdapter.DetailHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DetailAdapter.DetailHolder detailHolder, int i) {
        Device d = getDeviceArrayList().get(i);

        Glide.with(context)
                .load(d.getPhoto())
                .apply(new RequestOptions().override(350, 550))
                .into(detailHolder.photo);

        detailHolder.title.setText(d.getTitle());
        detailHolder.detail.setText(d.getDetail());
        detailHolder.summary.setText(d.getSummary());
        detailHolder.origin.setText(d.getOrigin());
        detailHolder.market_value.setText(d.getMarket_value());
        detailHolder.consumer.setText(d.getConsumer());
    }

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

    public class DetailHolder extends RecyclerView.ViewHolder {
        ImageView photo;
        TextView title, detail, summary, origin, market_value, consumer;
        public DetailHolder(View view) {
            super(view);
            photo = view.findViewById(R.id.photo_detail);
            title = view.findViewById(R.id.title_title);
            detail = view.findViewById(R.id.detail_title);
            summary = view.findViewById(R.id.detail_detail);
            origin = view.findViewById(R.id.origin_year);
            market_value = view.findViewById(R.id.market_value);
            consumer = view.findViewById(R.id.konsumer);
        }
    }
}
</code>```

Right now it asks for explicit activity on AndroidManifest.xml ,
but I can't assign DetailAdapter to AndroidManifest.xml

Logcat

```<code>2019-05-29 17:38:59.097 8897-8897/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 8897
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapplication/com.example.myapplication.DetailAdapter}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2012)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1675)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
        at com.example.myapplication.CardViewDeviceAdapter$3.onItemClicked(CardViewDeviceAdapter.java:89)
        at com.example.myapplication.CustomOnItemClick.onClick(CustomOnItemClick.java:16)
        at android.view.View.performClick(View.java:6608)
        at android.view.View.performClickInternal(View.java:6585)
        at android.view.View.access$3100(View.java:782)
        at android.view.View$PerformClick.run(View.java:25945)
        at android.os.Handler.handleCallback(Handler.java:874)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:6729)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

App crashses when tapping on Image

答:
You've got all the concept of RecyclerView wrong. Check out how to use RecyclerView from
Simple RecyclerView Example.

What you're trying to do is launch RecyclerView like an Activity. Your RecyclerView is not an activity, it is a view.
In the gif you've attached to shown what you want to accomplish, it's a completely different thing. After clicking the item in RecyclerView, a new activity is launched with SharedElement transition. Your DetailAdapter should be AppCompatActivity.

To correct your error, make your DetailAdapter extend AppCompatActivity, after doing that, while launching the DetailAdapter with Intent, pass the data like title, detail through Intent.

ContentLicense: CC BY-SA 4.0

Body:
So I have two Adapter class for RecyclerView. I want the ImageView inside one Adapter class to display the other Adapter class

I already tried to use intent on MainActivity

// listener for image
        cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
            Intent detail = new Intent(context,DetailAdapter.class);
                context.startActivity(detail);
            }
        }
        ));

here is the link for what the application supposed to be
https://ibb.co/gmnnghw
 https://giphy.com/gifs/Y3NK0lHfAcN1dGbCZX

CardViewDeviceAdapter

package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;

public class CardViewDeviceAdapter extends RecyclerView.Adapter<CardViewDeviceAdapter.CardViewHolder> {

    private Context context;
    private ArrayList<Device> deviceArrayList;
    private ArrayList<Device> getDeviceArrayList() {
        return deviceArrayList;
    }

    public void setDeviceArrayList(ArrayList<Device> deviceArrayList) {
        this.deviceArrayList = deviceArrayList;
    }

    public CardViewDeviceAdapter(Context context) {
        this.context = context;
    }

    @Override
    public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_device, viewGroup, false);
        return new CardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CardViewHolder cardViewHolder, int i) {
        Device d = getDeviceArrayList().get(i);

        Glide.with(context)
                .load(d.getPhoto())
                .apply(new RequestOptions().override(350, 550))
                .into(cardViewHolder.photo);

        cardViewHolder.title.setText(d.getTitle());
        cardViewHolder.detail.setText(d.getDetail());

        // listener untuk button favorite
        cardViewHolder.favorite.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
                Toast.makeText(context, "Favorite device"+getDeviceArrayList()
                .get(position)
                .getTitle()
                , Toast.LENGTH_SHORT).show();
            }
        }
        ));

        // listener untuk button share
        cardViewHolder.share.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
                Toast.makeText(context, "Share device"+getDeviceArrayList()
                                .get(position)
                                .getTitle()
                        , Toast.LENGTH_SHORT).show();
            }
        }
        ));

        // listener untuk image
        cardViewHolder.photo.setOnClickListener(new CustomOnItemClick(
                i, new CustomOnItemClick.OnItemClickCallback() {
            @Override
            public void onItemClicked(View view, int position) {
                Intent detail = new Intent(context, DetailAdapter.class);
                context.startActivity(detail);
            }
        }
        ));
    }

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

    public class CardViewHolder extends RecyclerView.ViewHolder {
        ImageView photo;
        TextView title, detail;
        Button favorite, share;
        public CardViewHolder(View itemView) {
            super(itemView);
            photo = itemView.findViewById(R.id.pc_photo);
            title = itemView.findViewById(R.id.pc_name);
            detail = itemView.findViewById(R.id.pc_details);
            favorite = itemView.findViewById(R.id.pc_favourite);
            share = itemView.findViewById(R.id.pc_share);
        }
    }
}

DetailAdapter

package com.example.myapplication;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.util.ArrayList;

public class DetailAdapter extends RecyclerView.Adapter<DetailAdapter.DetailHolder> {

    private Context context;
    private ArrayList<Device> deviceArrayList;
    private ArrayList<Device> getDeviceArrayList() {
        return deviceArrayList;
    }

    @NonNull
    @Override
    public DetailAdapter.DetailHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.detail_adapter, viewGroup, false);
        return new DetailAdapter.DetailHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DetailAdapter.DetailHolder detailHolder, int i) {
        Device d = getDeviceArrayList().get(i);

        Glide.with(context)
                .load(d.getPhoto())
                .apply(new RequestOptions().override(350, 550))
                .into(detailHolder.photo);

        detailHolder.title.setText(d.getTitle());
        detailHolder.detail.setText(d.getDetail());
        detailHolder.summary.setText(d.getSummary());
        detailHolder.origin.setText(d.getOrigin());
        detailHolder.market_value.setText(d.getMarket_value());
        detailHolder.consumer.setText(d.getConsumer());
    }

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

    public class DetailHolder extends RecyclerView.ViewHolder {
        ImageView photo;
        TextView title, detail, summary, origin, market_value, consumer;
        public DetailHolder(View view) {
            super(view);
            photo = view.findViewById(R.id.photo_detail);
            title = view.findViewById(R.id.title_title);
            detail = view.findViewById(R.id.detail_title);
            summary = view.findViewById(R.id.detail_detail);
            origin = view.findViewById(R.id.origin_year);
            market_value = view.findViewById(R.id.market_value);
            consumer = view.findViewById(R.id.konsumer);
        }
    }
}

Right now it asks for explicit activity on AndroidManifest.xml ,
but I can't assign DetailAdapter to AndroidManifest.xml

Logcat

2019-05-29 17:38:59.097 8897-8897/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 8897
    android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapplication/com.example.myapplication.DetailAdapter}; have you declared this activity in your AndroidManifest.xml?
        at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2012)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1675)
        at android.app.Activity.startActivityForResult(Activity.java:4586)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
        at android.app.Activity.startActivityForResult(Activity.java:4544)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
        at android.app.Activity.startActivity(Activity.java:4905)
        at android.app.Activity.startActivity(Activity.java:4873)
        at com.example.myapplication.CardViewDeviceAdapter$3.onItemClicked(CardViewDeviceAdapter.java:89)
        at com.example.myapplication.CustomOnItemClick.onClick(CustomOnItemClick.java:16)
        at android.view.View.performClick(View.java:6608)
        at android.view.View.performClickInternal(View.java:6585)
        at android.view.View.access$3100(View.java:782)
        at android.view.View$PerformClick.run(View.java:25945)
        at android.os.Handler.handleCallback(Handler.java:874)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:6729)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

App crashses when tapping on Image


问:
How I can hide row 'no-data' in datatable Vuetify
I'm beginner in vue and vuetify. I'm trying to make the first application on vue and vuetify. I'd like customize data table in vuetify. It has row 'no-data' default (with text 'No data available'). I want hide this row, but data table has no option such as 'hide-no-data'.</p>

答:
A bit late but it might still help someone..

You can use an empty row and hide it by setting visibility to hidden:

```<code><v-data-table ref="myTable">
    <template slot="no-data">
        <tr style="visibility: hidden;" />
    </template>
    ....
</v-data-table>
</code>```

Or if you want the entire content gone you can remove it manually by code:

```<code>$refs.myTable.$el.getElementsByTagName('tbody')[0].innerHTML = '';
</code>```

Where myTable refers to the v-data-table.

Body:
A bit late but it might still help someone..

You can use an empty row and hide it by setting visibility to hidden:

<v-data-table ref="myTable">
    <template slot="no-data">
        <tr style="visibility: hidden;" />
    </template>
    ....
</v-data-table>

Or if you want the entire content gone you can remove it manually by code:

$refs.myTable.$el.getElementsByTagName('tbody')[0].innerHTML = '';

Where myTable refers to the v-data-table.


问:
Unable to execute insert operation into Sql Azure db through Azure Functions
So I'm trying to simply logg some stuff from Azure Function to a database.
My code looks like this below

I've managed to see that the error is generated at the cmd.ExecuteNonQuery() because my log.information shows

```<code>2019-05-29T11:21:45.149 [Info] First Stop
2019-05-29T11:21:45.149 [Info] Connection Made
2019-05-29T11:21:45.149 [Info] Open Connection
2019-05-29T11:21:45.149 [Info] Create Query InsertInto
2019-05-29T11:21:45.149 [Info] enter SQL Command cmd
2019-05-29T11:21:45.149 [Info] insert a log to the database
2019-05-29T11:21:45.160 [Info] Function completed (Success, Id=7e507164-a17d-4aa7-84bd-279e0934514e, Duration=261ms)

using System.Net;
using Dapper;
using System.Data.SqlClient;
using System.Configuration;

[FunctionName("CreateLoggsToDbWithAzureFunctions")]
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
    log.LogInformation($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");

    var successful =true;

    try
    {
        log.LogInformation("First Stop");
        var cnnString  = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;

        //Environment.GetEnvironmentVariable("sqldb_connection");
        log.LogInformation("Connection Made", cnnString);
        using(var connection = new SqlConnection(cnnString))
        {
            connection.Open();
            log.LogInformation("Open Connection");

            //var rLog = await req.Content.ReadAsAsync<LogRequest>();

            log.LogInformation("Create Query InsertInto");

                    var query = "INSERT INTO Loggs (LogError)";
                    query += "VALUES (@LogError)";

                        log.LogInformation("enter SQL Command cmd");
                using(SqlCommand cmd = new SqlCommand(query, connection))
                {
                        log.LogInformation("insert a log to the database");
                        var rows = cmd.ExecuteNonQuery();
                        log.LogInformation("Log added to database successfully!");
                }
                //connection.Execute(query, rLog);

            // insert a log to the database
            // NOTE: Execute is an extension method from Dapper library
            //connection.Execute("INSERT INTO [dbo].[Loggs] ([LogError]) VALUES (@LogError)", rLog);
            //log.LogInformation("Log added to database successfully!");
        }
    }
    catch
    {
        successful=false;
    }

    return !successful
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process your request!")
        : req.CreateResponse(HttpStatusCode.OK, "Data saved successfully!");
}
public class LogRequest
{
    //public string Id{get;set;}
    //public string Date{get;set;}
    //public string LogCritical{get;set;}
    //public string LogDebug{get;set;}
    public string LogError{get;set;}
    //public string LogInformation{get;set;}
    //public string LogTrace{get;set;}
    //public string LogWarning{get;set;}
}
</code>```

I have tried different methods like using dapper and creating
 connection.Execute(query, rLog);
or doing

```<code>connection.Execute("INSERT INTO [dbo].[Loggs] ([LogError]) VALUES (@LogError)", rLog);`
</code>```

But there is nothing saved to the database and I do get the message

```<code>2019-05-29T11:21:45.160 [Info] Function completed
</code>```

But nothing happens, does anyone have an idea?

答:
You need to add your parameter like this:

cmd.Parameters.AddWithValue("@LogError", "ACTUAL ERROR");

Body:
So I'm trying to simply logg some stuff from Azure Function to a database.
My code looks like this below

I've managed to see that the error is generated at the cmd.ExecuteNonQuery() because my log.information shows

2019-05-29T11:21:45.149 [Info] First Stop
2019-05-29T11:21:45.149 [Info] Connection Made
2019-05-29T11:21:45.149 [Info] Open Connection
2019-05-29T11:21:45.149 [Info] Create Query InsertInto
2019-05-29T11:21:45.149 [Info] enter SQL Command cmd
2019-05-29T11:21:45.149 [Info] insert a log to the database
2019-05-29T11:21:45.160 [Info] Function completed (Success, Id=7e507164-a17d-4aa7-84bd-279e0934514e, Duration=261ms)

using System.Net;
using Dapper;
using System.Data.SqlClient;
using System.Configuration;

[FunctionName("CreateLoggsToDbWithAzureFunctions")]
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
    log.LogInformation($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");

    var successful =true;

    try
    {
        log.LogInformation("First Stop");
        var cnnString  = ConfigurationManager.ConnectionStrings["sqldb_connection"].ConnectionString;

        //Environment.GetEnvironmentVariable("sqldb_connection");
        log.LogInformation("Connection Made", cnnString);
        using(var connection = new SqlConnection(cnnString))
        {
            connection.Open();
            log.LogInformation("Open Connection");

            //var rLog = await req.Content.ReadAsAsync<LogRequest>();

            log.LogInformation("Create Query InsertInto");

                    var query = "INSERT INTO Loggs (LogError)";
                    query += "VALUES (@LogError)";

                        log.LogInformation("enter SQL Command cmd");
                using(SqlCommand cmd = new SqlCommand(query, connection))
                {
                        log.LogInformation("insert a log to the database");
                        var rows = cmd.ExecuteNonQuery();
                        log.LogInformation("Log added to database successfully!");
                }
                //connection.Execute(query, rLog);

            // insert a log to the database
            // NOTE: Execute is an extension method from Dapper library
            //connection.Execute("INSERT INTO [dbo].[Loggs] ([LogError]) VALUES (@LogError)", rLog);
            //log.LogInformation("Log added to database successfully!");
        }
    }
    catch
    {
        successful=false;
    }

    return !successful
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Unable to process your request!")
        : req.CreateResponse(HttpStatusCode.OK, "Data saved successfully!");
}
public class LogRequest
{
    //public string Id{get;set;}
    //public string Date{get;set;}
    //public string LogCritical{get;set;}
    //public string LogDebug{get;set;}
    public string LogError{get;set;}
    //public string LogInformation{get;set;}
    //public string LogTrace{get;set;}
    //public string LogWarning{get;set;}
}

I have tried different methods like using dapper and creating
 connection.Execute(query, rLog);
or doing

connection.Execute("INSERT INTO [dbo].[Loggs] ([LogError]) VALUES (@LogError)", rLog);`

But there is nothing saved to the database and I do get the message

2019-05-29T11:21:45.160 [Info] Function completed

But nothing happens, does anyone have an idea?


问:
Yocto rebuild image after modifying source code
How can I rebuild the image after making some modifications to driver source code?

I have tried bitbake -f -c compile and bitbake but I coudn't find the modified settings in the driver. Can someone tell me how can i rebuild the image with the modified code.

答:
If you did your modifications not directly in the ${WORKDIR}, you have to set the SRCREV to your new hash and increase your PR. Then enter the command

```<code>bitbake <image-name>
</code>```

Which compiles the one package again and creates the new image with your changes.

If you did your changes in the ${WORKDIR}, please add, commit and push them to your repository and then follow my steps above. This is the cleanest solution.

The command suggested by other solutions:

```<code>bitbake <image-name> -c cleansstate
</code>```

Will cause all of the packages to rebuild, which can take very long if you don't have an sstate mirror.

Body:
If you did your modifications not directly in the ${WORKDIR}, you have to set the SRCREV to your new hash and increase your PR. Then enter the command

bitbake <image-name>

Which compiles the one package again and creates the new image with your changes.

If you did your changes in the ${WORKDIR}, please add, commit and push them to your repository and then follow my steps above. This is the cleanest solution.

The command suggested by other solutions:

bitbake <image-name> -c cleansstate

Will cause all of the packages to rebuild, which can take very long if you don't have an sstate mirror.


问:
Python compare list of dictionaries with another dictionary in loop
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

```<code>a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)
</code>```

Below is the output When I tried to execute above code

```<code>Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]
</code>```

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

答:
Agree with @Alexander, but you also need a variable to count the color in the list. with the count, you can reconstruct your array if there is duplicate in the list</p>

```<code>a = {'red': 'blue', 'yellow': 'green', 'blue': 'blue1'}
# in case like a = [{'main_color': 'red', 'second_color': 'blue'},
# {'main_color': 'red', 'second_color': 'blue'}]
a_count = {'red': 1, 'yellow':1, 'blue': 1}
b = {'red': 'black', 'yellow': 'white'}

for i, j in b.items():
    if i in a:
        a[i] = j
print(a)
</code>```

Body:
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)

Below is the output When I tried to execute above code

Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

Body:
Agree with @Alexander, but you also need a variable to count the color in the list. with the count, you can reconstruct your array if there is duplicate in the list

a = {'red': 'blue', 'yellow': 'green', 'blue': 'blue1'}
# in case like a = [{'main_color': 'red', 'second_color': 'blue'},
# {'main_color': 'red', 'second_color': 'blue'}]
a_count = {'red': 1, 'yellow':1, 'blue': 1}
b = {'red': 'black', 'yellow': 'white'}

for i, j in b.items():
    if i in a:
        a[i] = j
print(a)


问:
Downloading Tensorflow 2.0 GPU version On Mac OS
I'm on a Mac and trying to download tensorflow 2.0 for GPU but every way I try to do it I get an error of this form:

```<code>"Could not find a version that satisfies the requirement"
</code>```

I've tried these ways to download it with Python 3.6:

pip install tensorflow-gpu==2.0.0-alpha0

pip install tf-nightly-gpu-2.0-preview

I'm able to install other versions of tensorflow-gpu but not the 2.0 version. Is anyone able to help me?

答:
I don't think gpu is supported for macOS 10.12.6 (Sierra) or later currently.

See tensorflow installation guide
The commands works on linux but doesn't work on mac.

Body:
I'm on a Mac and trying to download tensorflow 2.0 for GPU but every way I try to do it I get an error of this form:

"Could not find a version that satisfies the requirement"

I've tried these ways to download it with Python 3.6:

pip install tensorflow-gpu==2.0.0-alpha0

pip install tf-nightly-gpu-2.0-preview

I'm able to install other versions of tensorflow-gpu but not the 2.0 version. Is anyone able to help me?


问:
Ruby two strings in an IF condition
In my rails project I've if statement with string conditions which doesn't work.

```<code>  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end
</code>```

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

答:
Keep it simple-</p>

```<code>if shop.details['company_role'] == 'CEO' || shop.details['company_role'] == 'founder'
        'Other'
else
        shop.details['customer_kind']
end
</code>```

Title: Ruby two strings in an IF condition

Body:
In my rails project I've if statement with string conditions which doesn't work.

  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

Body:
Keep it simple-

if shop.details['company_role'] == 'CEO' || shop.details['company_role'] == 'founder'
        'Other'
else
        shop.details['customer_kind']
end


问:
Elasticsearch starts and stops immediately
I'm trying to start Elasticsearch process from Services. It starts, then stops immediately.

Laptop with Windows 10.
I've tried different versions, I've tried .msi and installing from zip.
Now I'm stuck with elasticsearch-6.8.0.
System variable JAVA_HOME added. ("C:\Program Files (x86)\Java\jre1.8.0_211").

I don't see anything in logs:

```<code>Java HotSpot(TM) Client VM (25.211-b12) for windows-x86 JRE (1.8.0_211-b12), built on Apr  1 2019 20:53:53 by "java_re" with MS VC++ 10.0 (VS2010)
Memory: 4k page, physical 6590616k(3782852k free), swap 7639192k(4460440k free)
CommandLine flags: -XX:+AlwaysPreTouch -XX:CMSInitiatingOccupancyFraction=75 -XX:ErrorFile=logs/hs_err_pid%p.log -XX:GCLogFileSize=67108864 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=data -XX:InitialHeapSize=2147483648 -XX:MaxHeapSize=2147483648 -XX:MaxNewSize=268435456 -XX:MaxTenuringThreshold=6 -XX:NewSize=268435456 -XX:NumberOfGCLogFiles=32 -XX:OldPLABSize=16 -XX:OldSize=536870912 -XX:-OmitStackTraceInFastThrow -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:ThreadStackSize=1024 -XX:+UseCMSInitiatingOccupancyOnly -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation -XX:-UseLargePagesIndividualAllocation -XX:+UseParNewGC
</code>```

答:
Solved.

I already had 1Gb of min/max Java heap. So this didnt work for me.
I just unistalled Java, and reinstalled JDK.
Still have no idea what was the reason or crashing but now it works.

Thank you

Body:
I'm trying to start Elasticsearch process from Services. It starts, then stops immediately.

Laptop with Windows 10.
I've tried different versions, I've tried .msi and installing from zip.
Now I'm stuck with elasticsearch-6.8.0.
System variable JAVA_HOME added. ("C:\Program Files (x86)\Java\jre1.8.0_211").

I don't see anything in logs:

Java HotSpot(TM) Client VM (25.211-b12) for windows-x86 JRE (1.8.0_211-b12), built on Apr  1 2019 20:53:53 by "java_re" with MS VC++ 10.0 (VS2010)
Memory: 4k page, physical 6590616k(3782852k free), swap 7639192k(4460440k free)
CommandLine flags: -XX:+AlwaysPreTouch -XX:CMSInitiatingOccupancyFraction=75 -XX:ErrorFile=logs/hs_err_pid%p.log -XX:GCLogFileSize=67108864 -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=data -XX:InitialHeapSize=2147483648 -XX:MaxHeapSize=2147483648 -XX:MaxNewSize=268435456 -XX:MaxTenuringThreshold=6 -XX:NewSize=268435456 -XX:NumberOfGCLogFiles=32 -XX:OldPLABSize=16 -XX:OldSize=536870912 -XX:-OmitStackTraceInFastThrow -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:ThreadStackSize=1024 -XX:+UseCMSInitiatingOccupancyOnly -XX:+UseConcMarkSweepGC -XX:+UseGCLogFileRotation -XX:-UseLargePagesIndividualAllocation -XX:+UseParNewGC


问:
Why the message doesn't to be redelivered?
The Acknowledgment Deadline is 10 seconds. When I use asynchronous-pull way to process the message, I don't call message.ack() and message.nack(), wait for the message ack deadline and expect Pub/Sub redeliver this message.

After waiting over 10 seconds, the subscriber doesn't receive the message again. Here is my code:

subscriber:

import { pubsubClient, IMessage, parseMessageData } from '../../googlePubsub';
import { logger } from '../../utils';

const topicName = 'asynchronous-pull-test';
const subName = 'asynchronous-pull-test';
const subscription = pubsubClient.topic(topicName).subscription(subName);
const onMessage = (message: IMessage) => {
  const { data, ...rest } = message;
  const jsonData = parseMessageData(data);
  logger.debug('received message', { arguments: { ...rest, data: jsonData } });

  const publishTime = new Date(message.publishTime).getTime();
  const republishTimestamp = Date.now() - 5 * 1000;

  if (publishTime < republishTimestamp) {
    logger.info('message acked');
    message.ack();
  } else {
    logger.info('push message back to MQ');
  }
};
logger.info('subscribe the MQ');
subscription.on('message', onMessage).on('error', (err: Error) => logger.error(err));

```

<p><code>publisher</code>:</p>

<pre class="lang-js prettyprint-override"><code>const topicName = 'asynchronous-pull-test';

async function main() {
  const messagePayload = { email: faker.internet.email(), campaignId: '1' };
  await pub(topicName, messagePayload);
}

main();
</code>```

I am using "@google-cloud/pubsub": "^0.19.0",

I expect the subscriber will receive the message again at the ack deadline 10 seconds later. Which means my subscriber receives and processes the message every 10 seconds. Am I wrong?

答:
The Google Cloud Pub/Sub client libraries automatically call modifyAckDeadline for messages that are neither acked or nacked for a configurable period of time. In node.js, this is configured via the maxExtension property:

```<code>const options = {
  flowControl: {
    maxExtension: 60, // Specified in seconds
  },
};

const subscription = pubsubClient.topic(topicName).subscription(subName, options);
</code>```

In general, it is not a good practice to not ack/nack a message as a means to delay its redelivery. This will result in the message still counting against the flow control max outstanding messages, meaning it could prevent the delivery of future messages until the originally received messages are acked or nacked. At this time, Cloud Pub/Sub does not have a means by which to delay message redelivery, but it is something under consideration.

Body:
The Acknowledgment Deadline is 10 seconds. When I use asynchronous-pull way to process the message, I don't call message.ack() and message.nack(), wait for the message ack deadline and expect Pub/Sub redeliver this message.

After waiting over 10 seconds, the subscriber doesn't receive the message again. Here is my code:

subscriber:

import { pubsubClient, IMessage, parseMessageData } from '../../googlePubsub';
import { logger } from '../../utils';

const topicName = 'asynchronous-pull-test';
const subName = 'asynchronous-pull-test';
const subscription = pubsubClient.topic(topicName).subscription(subName);
const onMessage = (message: IMessage) => {
  const { data, ...rest } = message;
  const jsonData = parseMessageData(data);
  logger.debug('received message', { arguments: { ...rest, data: jsonData } });

  const publishTime = new Date(message.publishTime).getTime();
  const republishTimestamp = Date.now() - 5 * 1000;

  if (publishTime < republishTimestamp) {
    logger.info('message acked');
    message.ack();
  } else {
    logger.info('push message back to MQ');
  }
};
logger.info('subscribe the MQ');
subscription.on('message', onMessage).on('error', (err: Error) => logger.error(err));

publisher:

const topicName = 'asynchronous-pull-test';

async function main() {
  const messagePayload = { email: faker.internet.email(), campaignId: '1' };
  await pub(topicName, messagePayload);
}

main();

I am using "@google-cloud/pubsub": "^0.19.0",

I expect the subscriber will receive the message again at the ack deadline 10 seconds later. Which means my subscriber receives and processes the message every 10 seconds. Am I wrong?

Body:
The Google Cloud Pub/Sub client libraries automatically call modifyAckDeadline for messages that are neither acked or nacked for a configurable period of time. In node.js, this is configured via the maxExtension property:

const options = {
  flowControl: {
    maxExtension: 60, // Specified in seconds
  },
};

const subscription = pubsubClient.topic(topicName).subscription(subName, options);

In general, it is not a good practice to not ack/nack a message as a means to delay its redelivery. This will result in the message still counting against the flow control max outstanding messages, meaning it could prevent the delivery of future messages until the originally received messages are acked or nacked. At this time, Cloud Pub/Sub does not have a means by which to delay message redelivery, but it is something under consideration.


问:
i want to delete item from listview without restarting actitvity
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

```<code>@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}
</code>```

答:
Well, you should reload data in your custom adapter. From what you described I understood It's not bound with the database in any way, so why do you expect it to reload even after calling notifyDataSetChange()? notifyDataSetChange works when you have actual observers registered in your Adapter.

Have a look at Loaders's and Content Providers in order to automatically reflect database state in your ListView. Here's the link - https://developer.android.com/guide/components/loaders

Body:
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}


问:
create new instances or use public static methods?
Which one is the better way for a asp.net application in which i need to call methods from multiple pages? Or is there a third even better possibility?</p>

答: You can also inherit all the pages from a common base page. But I would opt for the public static method if you do not need access to Page class members. Depends on what you actually want to achieve</p>

ContentLicense: CC BY-SA 3.0


答:
Mathematically, its possible to generate another random 0-1 array, multiply to original array:</p>

```<code>import numpy as np

ar = np.random.rand(3,3,3)
ar2 = np.random.randint(2, size = (3,3,1))
ar3 = ar*ar2
</code>```

Title: Replace NumPy array elements with other element

Body:
Suppose I have a randomly generated 3d array srouceArray:

ex: np.random.rand(3, 3, 3)

array([[[0.61961383, 0.26927599, 0.03847151],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0.5643174 , 0.20660141, 0.58836553],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0.19352397, 0.47284641, 0.97912889],
       [0.48519117, 0.37189048, 0.37113941],
       [0.94934848, 0.92755083, 0.52662299]]])

I would like to randomly replace all 3rd dimennsion elements to zeroes.

Expected array:

array([[[0, 0, 0],
        [0.03497162, 0.77748313, 0.15807293],
        [0.15108821, 0.36729448, 0.19007034]],

      [[0.67734758, 0.88312758, 0.97610746],
       [0 , 0, 0],
       [0.59084109, 0.77019768, 0.35961768]],

      [[0, 0, 0],
       [0, 0, 0],
       [0.94934848, 0.92755083, 0.52662299]]])

I was thinking about generating "mask"? using random

np.random.choice([True, False], sourceArray.shape, p=[...])

and somehow transforming it to 3d array where False=[0, 0, 0] and True=[1, 1, 1] and multiplying with source...

But I do not know how to achieve that transformation. And I bet there is a simpler way I do not know about.

Body:
Mathematically, its possible to generate another random 0-1 array, multiply to original array:

import numpy as np

ar = np.random.rand(3,3,3)
ar2 = np.random.randint(2, size = (3,3,1))
ar3 = ar*ar2


问:
exclude time from other table in Entity Framework
I have two tables: Outages and PlannedMaintance. I have to fetch the outages records which lies under specific date time range and if this time comes under PlannedMaintance, skip these record. for ex. if there are 10 records coming between 1 may 2019 12:00 AM to 09 May 2019 11:59 PM and plannedDowntime Tables has record for StartDownTime is 3 May 2019 10:35 AM and EndDownTime is 3 may 2019 11:00 AM. during this period, there are 3 records in outages, we need to skip these and output list should have 7 records.

I don't want to loop on the records. The will be records hundreds of thousands, it may chock the website.

Here is table structures:

Outage

PlannedDownTime

Entity Framework Query:

```<code>  var netwrokErrorsQuery = db.Outages.Where(_ => _.OutageType == "Network" && _.OutageStart >= startDate && _.OutageEnd <= endDate).ToList().Where(_=>_.OutageStart.Hour<2 && _.OutageStart.Hour > 5 || _.OutageEnd.Value.Hour < 2 && _.OutageEnd.Value.Hour > 5).ToList();
        var softwareErrorsQuery = db.Outages.Where(_ => _.OutageType == "Software" && _.OutageStart >= startDate && _.OutageEnd <= endDate).ToList().Where(_ => _.OutageStart.Hour < 2 && _.OutageStart.Hour > 5 || _.OutageEnd.Value.Hour < 2 && _.OutageEnd.Value.Hour > 5).ToList();
        var hardwareErrorsQuery = db.Outages.Where(_ => _.OutageType == "Hardware" && _.OutageStart >= startDate && _.OutageEnd <= endDate).ToList().Where(_ => _.OutageStart.Hour < 2 && _.OutageStart.Hour > 5 || _.OutageEnd.Value.Hour < 2 && _.OutageEnd.Value.Hour > 5).ToList();
</code>```

i am not able to get any way any idea how i can do it

答:
Please try this</p>

```<code>var records = db.Outages
           .Join(db.PlannedDownTime,
                 o => o.ReaderId,
                 p => p.ReaderId,
                 (o, p) => new {
                     OutageStart = o.OutageStart,
                     OutageEnd = o.OutageEnd,
                     DowntimeStart = p.DowntimeStart,
                     DowntimeEnd = p.DowntimeEnd
                 }
                 ).Where(r=>r.OutageStart >= START_TIME)
                 .Where(r=>r.OutageEnd <= END_TIME)
                 .Where(r=>(r.DowntimeStart < START_TIME && r.DowntimeEnd < START_TIME ) || (r.DowntimeStart > END_TIME && r.DowntimeEnd > END_TIME ))
                 .ToList();
</code>```

Body:
I have two tables: Outages and PlannedMaintance. I have to fetch the outages records which lies under specific date time range and if this time comes under PlannedMaintance, skip these record. for ex. if there are 10 records coming between 1 may 2019 12:00 AM to 09 May 2019 11:59 PM and plannedDowntime Tables has record for StartDownTime is 3 May 2019 10:35 AM and EndDownTime is 3 may 2019 11:00 AM. during this period, there are 3 records in outages, we need to skip these and output list should have 7 records.

I don't want to loop on the records. The will be records hundreds of thousands, it may chock the website.

Here is table structures:

Outage

PlannedDownTime

Entity Framework Query:

  var netwrokErrorsQuery = db.Outages.Where(_ => _.OutageType == "Network" && _.OutageStart >= startDate && _.OutageEnd <= endDate).ToList().Where(_=>_.OutageStart.Hour<2 && _.OutageStart.Hour > 5 || _.OutageEnd.Value.Hour < 2 && _.OutageEnd.Value.Hour > 5).ToList();
        var softwareErrorsQuery = db.Outages.Where(_ => _.OutageType == "Software" && _.OutageStart >= startDate && _.OutageEnd <= endDate).ToList().Where(_ => _.OutageStart.Hour < 2 && _.OutageStart.Hour > 5 || _.OutageEnd.Value.Hour < 2 && _.OutageEnd.Value.Hour > 5).ToList();
        var hardwareErrorsQuery = db.Outages.Where(_ => _.OutageType == "Hardware" && _.OutageStart >= startDate && _.OutageEnd <= endDate).ToList().Where(_ => _.OutageStart.Hour < 2 && _.OutageStart.Hour > 5 || _.OutageEnd.Value.Hour < 2 && _.OutageEnd.Value.Hour > 5).ToList();

i am not able to get any way any idea how i can do it

Body:
Please try this

var records = db.Outages
           .Join(db.PlannedDownTime,
                 o => o.ReaderId,
                 p => p.ReaderId,
                 (o, p) => new {
                     OutageStart = o.OutageStart,
                     OutageEnd = o.OutageEnd,
                     DowntimeStart = p.DowntimeStart,
                     DowntimeEnd = p.DowntimeEnd
                 }
                 ).Where(r=>r.OutageStart >= START_TIME)
                 .Where(r=>r.OutageEnd <= END_TIME)
                 .Where(r=>(r.DowntimeStart < START_TIME && r.DowntimeEnd < START_TIME ) || (r.DowntimeStart > END_TIME && r.DowntimeEnd > END_TIME ))
                 .ToList();


问:
SuppressWarnings("deprecation") for one line in java
I am working with threads and using thread.stop(); to end a thread for a temporary solution to a problem I was having. I understand that it is deprecated and should not be used, but how do I suppress the compiler warning for that one line only? I want to continue getting deprecated warnings for the rest of my class, just not that one line. I tried using the code below and got the error "Annotations are not allowed here" on the @SupressWarnings("deprecation") line. What is the correct way to suppress this error?

class Handeler {
   private Thread thread;
   .....
   void stopThread() {
      if(thread!=null && thread.isAlive()) {
         @SuppressWarnings("deprecation")
            thread.stop();
      }
   }
}
```

答:
You can annotate the method instead:

```<code>class Handeler {
   private Thread thread;
   .....
   @SuppressWarnings("deprecation")
   void stopThread() {
      if(thread!=null && thread.isAlive()) {
            thread.stop();
      }
   }
}
</code>```

This annotation on a single line is not allowed.

Body:
You can annotate the method instead:

class Handeler {
   private Thread thread;
   .....
   @SuppressWarnings("deprecation")
   void stopThread() {
      if(thread!=null && thread.isAlive()) {
            thread.stop();
      }
   }
}

This annotation on a single line is not allowed.


问:
LinkedBlockingQueue thowing InterruptedException
I have this piece of code. A LinkedBlockingQueue should only throw an Exception if interrupted while waiting to add to the queue. But this queue is unbounded so it should add asap. Why does my shutdown methode throw an InterruptedException?

```<code>private final LinkedBlockingQueue<Message> messages= new LinkedBlockingQueue<Message>();

public void run(){
    LinkedList<Message> messages = new LinkedList<Message>();
    while (true){
        try{
            messages.clear();
            messages.add(this.messages.take());
                            this.messages.drainTo(messages);
            for (Message message:messages){
                if(message.isPoison())return;
                doSomething(message);
            }
        }catch(Exception e){
            getLogger().addException(e);
        }
    }
}

protected void add(Message m){
    try {
        messages.put(m);
    }catch (InterruptedException e) {
        getLogger().addException(e);
        addRollback(e);
    }
}

public void shutdown(){
    try{
        messages.put(MessageFactory.getPoison());
    }catch(InterruptedException e){
     //here an exception is thrown. Why?
    }

}
</code>```

答: If the thread is in a state of interruption, that is Thread.interrupted() == true, then the call will throw an InterruptionException.  It doesn't necessarily mean that the thread was interrupted while you were putting, it could have already been in the state before entering.

Body:
I have this piece of code. A LinkedBlockingQueue should only throw an Exception if interrupted while waiting to add to the queue. But this queue is unbounded so it should add asap. Why does my shutdown methode throw an InterruptedException?

private final LinkedBlockingQueue<Message> messages= new LinkedBlockingQueue<Message>();

public void run(){
    LinkedList<Message> messages = new LinkedList<Message>();
    while (true){
        try{
            messages.clear();
            messages.add(this.messages.take());
                            this.messages.drainTo(messages);
            for (Message message:messages){
                if(message.isPoison())return;
                doSomething(message);
            }
        }catch(Exception e){
            getLogger().addException(e);
        }
    }
}

protected void add(Message m){
    try {
        messages.put(m);
    }catch (InterruptedException e) {
        getLogger().addException(e);
        addRollback(e);
    }
}

public void shutdown(){
    try{
        messages.put(MessageFactory.getPoison());
    }catch(InterruptedException e){
     //here an exception is thrown. Why?
    }

}


问:
Audit for EF Core
I would like to implement audit functionality using EF Core.

I mean would like to log every transaction/action such as Create, update and delete in DB table.

I have searched on google and found some library and solution.

https://www.nuget.org/packages/Audit.EntityFramework.Core/

https://beeming.net/data/2017/1/easily-adding-auditing-to-a-entity-framework-code-first-project

Can some one suggest me best practices for auditing for EF Core
Note: I am using EF Core 2.X

答: The basic process for auditing is to override the SaveChanges() method on the DbContext and plug in some logic. The DbContext has a ChangeTracker property that makes it super easy to access the before and after values</p>

Title: Audit for EF Core


问:
Is there an c++ function from Armadillo for selecting a column from a matrix?”
I'm looking for selecting a column from a matrix H for example, knowingly that a have the index off this column

I searched in Armadillio

答: According to http://arma.sourceforge.net/docs.html#submat you can use X.col(col_number).


问:
Python doesn't convert string list into regular list?
I have a string ouput which looks like below

```<code>result = "[(u'Delhi', 20199330), (u'Mumbai', 134869470), (u'Kolkata', 6678446)]"
</code>```

Now I want to convert it to a regular array. So this is what I do

```<code>import json

print(json.loads(result))
</code>```

But I get the following error

```<code>ValueError: No JSON object could be decoded
</code>```

Now I know result is not  a json. But python does convert a string list into a regular list by doing something like

```<code>some_list = "[10, 20, 30]"

print(json.loads(some_list))
</code>```

So I was hoping it would convert my result which is a string list of tuples into a regular list of tuples. But it throws error.

How can I convert result into a regular list?

Body:
I have a string ouput which looks like below

result = "[(u'Delhi', 20199330), (u'Mumbai', 134869470), (u'Kolkata', 6678446)]"

Now I want to convert it to a regular array. So this is what I do

import json

print(json.loads(result))

But I get the following error

ValueError: No JSON object could be decoded

Now I know result is not  a json. But python does convert a string list into a regular list by doing something like

some_list = "[10, 20, 30]"

print(json.loads(some_list))

So I was hoping it would convert my result which is a string list of tuples into a regular list of tuples. But it throws error.

How can I convert result into a regular list?

Body:
Try this,

>>> result = "[(u'Delhi', 20199330), (u'Mumbai', 134869470), (u'Kolkata', 6678446)]"
>>> import ast
>>> ast.literal_eval(result)
[('Delhi', 20199330), ('Mumbai', 134869470), ('Kolkata', 6678446)]


问:
How to order an array of objects according to different properties?
I need to order an array where the elements are objects. I want to fill up a dropdown in a specific order

```<code>[{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }]
</code>```

What I am trying to achieve is to to get a dropdown where first appear the Country (parent null), then its children, but immediately, if those children have also children, they should appear down below, kind of:

- Country

- City1

- City2

- City3

- Village1

- Village2

- City4

. . .
And so on..

Anyone can give me a hand? I am really struggling here...

答:
That should do it:</p>

```<code>let finalArray = [];
originalArray.map(x => {
   if(x.name === 'Country') {finalArray[0] = x}
   if(x.name === 'City1') {finalArray[1] = x}
   if(x.name === 'City2') {finalArray[2] = x}
   if(x.name === 'City3') {finalArray[3] = x}
   if(x.name === 'Village1') {finalArray[4] = x}
   if(x.name === 'Village2') {finalArray[5] = x}
   if(x.name === 'City4') {finalArray[6] = x}
 })
</code>```

Body:
I need to order an array where the elements are objects. I want to fill up a dropdown in a specific order

[{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }]

What I am trying to achieve is to to get a dropdown where first appear the Country (parent null), then its children, but immediately, if those children have also children, they should appear down below, kind of:

- Country

- City1

- City2

- City3

- Village1

- Village2

- City4

. . .
And so on..

Anyone can give me a hand? I am really struggling here...

Body:
That should do it:

let finalArray = [];
originalArray.map(x => {
   if(x.name === 'Country') {finalArray[0] = x}
   if(x.name === 'City1') {finalArray[1] = x}
   if(x.name === 'City2') {finalArray[2] = x}
   if(x.name === 'City3') {finalArray[3] = x}
   if(x.name === 'Village1') {finalArray[4] = x}
   if(x.name === 'Village2') {finalArray[5] = x}
   if(x.name === 'City4') {finalArray[6] = x}
 })


问:
how to do privilege escalation on lookup(ini)
My test.yml

```<code>      1 - name: Test ini
      2   hosts: localhost
      3   connection: local
      4   become: true
      5
      6   tasks:
      7
      8   - name: Verifying /etc/heat/heat.conf Configuration
      9     become_user: root
     10     become_method: sudo
     11     fail: msg="Unable to set in /etc/heat/heat.conf"
     12     when: "lookup('ini', 'max_resources_per_stack section=DEFAULT file=/etc/heat/heat.conf') != '-1'"

</code>```

Error

```<code>$ ansible-playbook test.yml
 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [Test ini] ***********************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************
ok: [localhost]

TASK [Verifying /etc/heat/heat.conf Configuration] ************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'lookup('ini', 'max_resources_per_stack section=DEFAULT file=/etc/heat/heat.conf') != '-1'' failed. The error was: An unhandled exception occurred while running the lookup plugin 'ini'. Error was a <class 'ansible.errors.AnsibleParserError'>, original message: an error occurred while trying to read the file '/etc/heat/heat.conf': [Errno 13] Permission denied: '/etc/heat/heat.conf'\n\nThe error appears to have been in '/home/stack/test.yml': line 8, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Verifying /etc/heat/heat.conf Configuration\n    ^ here\n"}
    to retry, use: --limit @/home/stack/test.retry

PLAY RECAP ****************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

</code>```

I have no idea why is it not working? ini file modification is working with ini_file without specifying become_user or become_user. But it is not working with lookup? Even I'm able run crudini --get command in shell too.

```<code>$ ls -la /etc/heat/heat.conf
-rw-r-----. 1 root heat 85196 May 29 01:39 /etc/heat/heat.conf

</code>```

UPDATE

The playbook is only working when I run playbook with sudo like sudo ansible-playbook ini_test.yml

UPDATE2

ansible 2.6.11

答:
It's bug.

With the file /root/test

```<code>> ll /root/test
-rw-r----- 1 root root 30 May 29 15:09 /root/test
</code>```

The playbook

```<code>- hosts: localhost
  become_user: root
  become_method: sudo
  become: yes
  tasks:
    - command: whoami
      register: result
    - debug:
        var: result.stdout
    - name: read the file
      debug:
        msg: "{{ lookup('file', '/root/test') }}"
</code>```

gives (abridged):

```<code>ok: [localhost] => {
    "result.stdout": "root"
}
TASK [read the file]
fatal: [localhost]: FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /root/test"}
</code>```

With all enabled to read

```<code>> ll /root/test
-rw-r--r-- 1 root root 30 May 29 15:09 /root/test
</code>```

the playbook works as expected and gives (abridged):

```<code>TASK [read the file]
ok: [localhost] => {
    "msg": "Wed May 29 15:09:43 CEST 2019"
}
</code>```

For the record. How should you answer questions that lead to bug reports?.

Body:
My test.yml

      1 - name: Test ini
      2   hosts: localhost
      3   connection: local
      4   become: true
      5
      6   tasks:
      7
      8   - name: Verifying /etc/heat/heat.conf Configuration
      9     become_user: root
     10     become_method: sudo
     11     fail: msg="Unable to set in /etc/heat/heat.conf"
     12     when: "lookup('ini', 'max_resources_per_stack section=DEFAULT file=/etc/heat/heat.conf') != '-1'"

Error

$ ansible-playbook test.yml
 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [Test ini] ***********************************************************************************************************************

TASK [Gathering Facts] ****************************************************************************************************************
ok: [localhost]

TASK [Verifying /etc/heat/heat.conf Configuration] ************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'lookup('ini', 'max_resources_per_stack section=DEFAULT file=/etc/heat/heat.conf') != '-1'' failed. The error was: An unhandled exception occurred while running the lookup plugin 'ini'. Error was a <class 'ansible.errors.AnsibleParserError'>, original message: an error occurred while trying to read the file '/etc/heat/heat.conf': [Errno 13] Permission denied: '/etc/heat/heat.conf'\n\nThe error appears to have been in '/home/stack/test.yml': line 8, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Verifying /etc/heat/heat.conf Configuration\n    ^ here\n"}
    to retry, use: --limit @/home/stack/test.retry

PLAY RECAP ****************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=1

I have no idea why is it not working? ini file modification is working with ini_file without specifying become_user or become_user. But it is not working with lookup? Even I'm able run crudini --get command in shell too.

$ ls -la /etc/heat/heat.conf
-rw-r-----. 1 root heat 85196 May 29 01:39 /etc/heat/heat.conf

UPDATE

The playbook is only working when I run playbook with sudo like sudo ansible-playbook ini_test.yml

UPDATE2

ansible 2.6.11

Body:
It's bug.

With the file /root/test

> ll /root/test
-rw-r----- 1 root root 30 May 29 15:09 /root/test

The playbook

- hosts: localhost
  become_user: root
  become_method: sudo
  become: yes
  tasks:
    - command: whoami
      register: result
    - debug:
        var: result.stdout
    - name: read the file
      debug:
        msg: "{{ lookup('file', '/root/test') }}"

gives (abridged):

ok: [localhost] => {
    "result.stdout": "root"
}
TASK [read the file]
fatal: [localhost]: FAILED! => {"msg": "An unhandled exception occurred while running the lookup plugin 'file'. Error was a <class 'ansible.errors.AnsibleError'>, original message: could not locate file in lookup: /root/test"}

With all enabled to read

> ll /root/test
-rw-r--r-- 1 root root 30 May 29 15:09 /root/test

the playbook works as expected and gives (abridged):

TASK [read the file]
ok: [localhost] => {
    "msg": "Wed May 29 15:09:43 CEST 2019"
}

For the record. How should you answer questions that lead to bug reports?.


问:
Deletion algorithm for a Red Black tree
Guys I'm trying to implement deletion algorithm for a Red Black tree and I'm having problem with understanding line three of this algorithm (from a book "Introduction to Algorithms" second edition):

1 if left[z] = nil[T] or right[z] = nil[T]

 2    then y ← z

 3    else y ← TREE-SUCCESSOR(z)

 4 if left[y] ≠ nil[T]

 5    then x ← left[y]

 6    else x ← right[y]

 7 p[x] ← p[y]

 8 if p[y] = nil[T]

 9    then root[T] ← x

10    else if y = left[p[y]]

11            then left[p[y]] ← x

12            else right[p[y]] ← x

13 if y 3≠ z

14    then key[z] ← key[y]

15         copy y's satellite data into z

16 if color[y] = BLACK

17    then RB-DELETE-FIXUP(T, x)

18 return y

First of all there is nowhere in this book explained what the TREE-SUCCESSOR is suppose to look like (no algorithm for that) but I found this page: and if I feed this algorithm whit 11,2,1,7,5,8,14,15,4 and then try to delete 7 it finds predecessor but if I try to delete 11 it finds successor. And that what I can't understand. Why sometimes it takes predecessor and sometimes successor? What criteria are taken into consideration while making this decision? A node's color?

Thank you.

P.S. I also do not quite understand what it's written in line number 13. Does it mean that if y has three colors (neither black nor red) or something else?

答:
You can refer to following code.

http://code.google.com/p/cstl/source/browse/src/c_rb.c

ContentLicense: CC BY-SA 2.5

Title: Deletion algorithm for a Red Black tree


问:
iOS 12 Errors: appears to be from a different NSManagedObjectModel than this context's
I started to get the following error when launching my application on iOS 12 simulator. Did anybody face issue like this?

```<code>2018-08-11 21:17:44.440144+0300 CafeManager[4633:128874] [error] error: The fetch request's entity 0x600001f6e940 'TablesTable' appears to be from a different NSManagedObjectModel than this context's
</code>```

I have global constant defined in AppDelegate:

```<code>let viewContext = AppDelegate.viewContext
</code>```

And use it with NSFetchedResultsController for UITableView update, for example:

```<code>import UIKit
import CoreData

class HistoryTablesTableViewController: FetchedResultsTableViewController {
    //MARK: variables
    private var fetchedResultsController: NSFetchedResultsController<TablesTable>?
    private var currentTable: TablesTable?
    private var tableNameTextField: UITextField!

    //MARK: system functions for view
    override func viewDidLoad() {
        super.viewDidLoad()
        sideMenu()
        addSyncObserver()
    }
    override func viewWillAppear(_ animated: Bool) {
        updateGUI()
    }

    // MARK: IBOutlets
    @IBOutlet weak var menuButton: UIBarButtonItem!

    // MARK: side menu
    private func sideMenu() {
        if revealViewController() != nil {
            menuButton.target = revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            revealViewController().rearViewRevealWidth = 260

            view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }
    }

    //MARK: functions for table update
    private func updateGUI () {
        let request : NSFetchRequest<TablesTable> = TablesTable.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(key: "tableName", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))]
        fetchedResultsController = NSFetchedResultsController<TablesTable>(fetchRequest: request, managedObjectContext: viewContext, sectionNameKeyPath: nil, cacheName: nil)
        try? fetchedResultsController?.performFetch()
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! HistoryTablesTableViewCell
        if let tablesTable = fetchedResultsController?.object(at: indexPath) {
            cell.tableNameLabel.text = tablesTable.tableName
            cell.cellDelegate = self
            cell.table = tablesTable
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath as IndexPath)
        tableView.deselectRow(at: indexPath as IndexPath, animated: true)
        currentTable = fetchedResultsController?.object(at: indexPath)
        performSegue(withIdentifier: "showTableSessions", sender: cell)
    }

    //MARK: prepare for segue
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showTableSessions" {
            if let tableSessionsTVC = segue.destination as? TableSessionsTableViewController {
                tableSessionsTVC.title = self.currentTable!.tableName!
                tableSessionsTVC.currentTable = self.currentTable!
            }
        }
    }
}

// MARK: Delegates
extension HistoryTablesTableViewController: HistoryTablesTableViewCellDelegate {
    func didPressTablesCellButton(table: TablesTable) {
        currentTable = table
    }
}

// Common extension for fetchedResultsController
extension HistoryTablesTableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedResultsController?.sections?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let sections = fetchedResultsController?.sections, sections.count > 0 {
            return sections[section].numberOfObjects
        }
        else {
            return 0
        }
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if let sections = fetchedResultsController?.sections, sections.count > 0 {
            return sections[section].name
        }
        else {
            return nil
        }
    }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return fetchedResultsController?.sectionIndexTitles
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return fetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
    }
}

// Observer to check that sync was performed to update GUI
extension HistoryTablesTableViewController {
    private func addSyncObserver () {
        NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: appDelegate.syncDidFinishNotification), object: nil, queue: nil) {
            [weak self] notification in
            DispatchQueue.main.async {
                self?.updateGUI()
            }
        }
    }
}
</code>```

In the same time it looks like that app works, but had no chance to test everything properly yet.

I use CoreData, Seam3 framework.

I found the only one mention of this error on github, but do not see solution.

答:
In my case it was a simple solution, I am using 4 contexts and I had to set their parent to the main context.</p>

```<code>var mainManagedContext: NSManagedObjectContext {
    return persistentContainer.viewContext
}

lazy var backgroundQueueContext: NSManagedObjectContext = {
    let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    context.parent = mainManagedContext
    return context
}()

lazy var mainQueueContext: NSManagedObjectContext = {
    let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    context.parent = mainManagedContext
    return context
}()

lazy var alternativeContext: NSManagedObjectContext = {
    let context = persistentContainer.newBackgroundContext()
    return context
}()
</code>```

Body:
I started to get the following error when launching my application on iOS 12 simulator. Did anybody face issue like this?

2018-08-11 21:17:44.440144+0300 CafeManager[4633:128874] [error] error: The fetch request's entity 0x600001f6e940 'TablesTable' appears to be from a different NSManagedObjectModel than this context's

I have global constant defined in AppDelegate:

let viewContext = AppDelegate.viewContext

And use it with NSFetchedResultsController for UITableView update, for example:

import UIKit
import CoreData

class HistoryTablesTableViewController: FetchedResultsTableViewController {
    //MARK: variables
    private var fetchedResultsController: NSFetchedResultsController<TablesTable>?
    private var currentTable: TablesTable?
    private var tableNameTextField: UITextField!

    //MARK: system functions for view
    override func viewDidLoad() {
        super.viewDidLoad()
        sideMenu()
        addSyncObserver()
    }
    override func viewWillAppear(_ animated: Bool) {
        updateGUI()
    }

    // MARK: IBOutlets
    @IBOutlet weak var menuButton: UIBarButtonItem!

    // MARK: side menu
    private func sideMenu() {
        if revealViewController() != nil {
            menuButton.target = revealViewController()
            menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
            revealViewController().rearViewRevealWidth = 260

            view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }
    }

    //MARK: functions for table update
    private func updateGUI () {
        let request : NSFetchRequest<TablesTable> = TablesTable.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(key: "tableName", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))]
        fetchedResultsController = NSFetchedResultsController<TablesTable>(fetchRequest: request, managedObjectContext: viewContext, sectionNameKeyPath: nil, cacheName: nil)
        try? fetchedResultsController?.performFetch()
        tableView.reloadData()
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! HistoryTablesTableViewCell
        if let tablesTable = fetchedResultsController?.object(at: indexPath) {
            cell.tableNameLabel.text = tablesTable.tableName
            cell.cellDelegate = self
            cell.table = tablesTable
        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath as IndexPath)
        tableView.deselectRow(at: indexPath as IndexPath, animated: true)
        currentTable = fetchedResultsController?.object(at: indexPath)
        performSegue(withIdentifier: "showTableSessions", sender: cell)
    }

    //MARK: prepare for segue
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showTableSessions" {
            if let tableSessionsTVC = segue.destination as? TableSessionsTableViewController {
                tableSessionsTVC.title = self.currentTable!.tableName!
                tableSessionsTVC.currentTable = self.currentTable!
            }
        }
    }
}

// MARK: Delegates
extension HistoryTablesTableViewController: HistoryTablesTableViewCellDelegate {
    func didPressTablesCellButton(table: TablesTable) {
        currentTable = table
    }
}

// Common extension for fetchedResultsController
extension HistoryTablesTableViewController {
    override func numberOfSections(in tableView: UITableView) -> Int {
        return fetchedResultsController?.sections?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let sections = fetchedResultsController?.sections, sections.count > 0 {
            return sections[section].numberOfObjects
        }
        else {
            return 0
        }
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if let sections = fetchedResultsController?.sections, sections.count > 0 {
            return sections[section].name
        }
        else {
            return nil
        }
    }

    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return fetchedResultsController?.sectionIndexTitles
    }

    override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        return fetchedResultsController?.section(forSectionIndexTitle: title, at: index) ?? 0
    }
}

// Observer to check that sync was performed to update GUI
extension HistoryTablesTableViewController {
    private func addSyncObserver () {
        NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: appDelegate.syncDidFinishNotification), object: nil, queue: nil) {
            [weak self] notification in
            DispatchQueue.main.async {
                self?.updateGUI()
            }
        }
    }
}

In the same time it looks like that app works, but had no chance to test everything properly yet.

I use CoreData, Seam3 framework.

I found the only one mention of this error on github, but do not see solution.

Body:
In my case it was a simple solution, I am using 4 contexts and I had to set their parent to the main context.

var mainManagedContext: NSManagedObjectContext {
    return persistentContainer.viewContext
}

lazy var backgroundQueueContext: NSManagedObjectContext = {
    let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    context.parent = mainManagedContext
    return context
}()

lazy var mainQueueContext: NSManagedObjectContext = {
    let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    context.parent = mainManagedContext
    return context
}()

lazy var alternativeContext: NSManagedObjectContext = {
    let context = persistentContainer.newBackgroundContext()
    return context
}()


问:
Android Kotlin - Implement custom map marker using Bitmap with Glide
I'm trying to implement a custom map marker using my XML layout into  Google Maps.

However; when i use the createCustomMarker method to print out my custom marker into Google Maps, it does not load/show the image coming from the cloud/server.

I think it's because Glide(or the app in this matter) didn't get the change to finish downloading and rendering the image before the layout got converted into Bitmap, or maybe my implementation is just wrong. Can anyone help me with this?

```<code>@SuppressLint("InflateParams")
    private fun createCustomMarker(urlImageFromCloud: String): Bitmap{

        val marker: LayoutInflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val view: View = marker.inflate(R.layout.map_marker, null)

        val messageIcon: Int = resources.getIdentifier("local_image_from_drawable", "drawable", this.packageName)
        val markerPhoto: CircleImageView = view.findViewById(R.id.map_photo)
        val markerContainer: CircleImageView = view.findViewById(R.id.map_photo)
        val options: RequestOptions = RequestOptions()
            .centerCrop()
            .placeholder(R.color.colorGrayWhite)
            .error(R.color.colorGrayWhite)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
        Glide.with(this)
            .load(urlImageFromCloud) // String image URL from my server/cloud - this is the part that does not show up.
            .apply(options).into(markerPhoto)
        Glide.with(this)
            .load(messageIcon)
            .apply(options).into(markerContainer)

        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)

        view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels)
        view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels)
        view.buildDrawingCache()
        val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        view.draw(canvas)

        return bitmap
    }
</code>```

My map_marker XML :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/custom_marker_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <ImageView
            android:id="@+id/map_container"
            android:layout_width="75dp"
            android:layout_height="75dp"/>

    <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/map_photo"
            android:src="@color/colorGray"
            android:layout_marginTop="5dp"
            android:layout_centerHorizontal="true"
            style="@style/MapMarkerCircleImage"/>

</RelativeLayout>
</code>```

This is how i called my createCustomMarker method.

```<code>val defaultLocation = LatLng(locationLatitude, locationLongitude)
googleMap.addMarker(MarkerOptions().position(defaultLocation).icon(BitmapDescriptorFactory.fromBitmap(createCustomMarker("my_image_url_from_cloud"))))
</code>```

答:
I had the same issue. My solution was just to download the bitmap using Glide and with a listener create the marker when the download is complete.

```<code>private fun getMarkerIcon(context: Context, url: String, listener: (BitmapDescriptor) -> Unit) {
    val markerView = View.inflate(context, R.layout.view_marker, null)
    Glide.with(context)
        .asBitmap()
        .load(url)
        .into(object : SimpleTarget<Bitmap>() {

            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                markerView.avatarImageView.setImageBitmap(resource)
                listener.invoke(BitmapDescriptorFactory.fromBitmap(getBitmapFromView(markerView)))
            }
        })
}

private fun getBitmapFromView(view: View): Bitmap {
    view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
    val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
    view.draw(canvas)
    return bitmap
}
</code>```

And the call

```<code>getMarkerIcon(context, "http://....") {
    val options = MarkerOptions()
        .position(LatLng(latitude, longitude))
        .icon(it)
    googleMap.addMarker(options)
}
</code>```

Body:
I'm trying to implement a custom map marker using my XML layout into  Google Maps.

However; when i use the createCustomMarker method to print out my custom marker into Google Maps, it does not load/show the image coming from the cloud/server.

I think it's because Glide(or the app in this matter) didn't get the change to finish downloading and rendering the image before the layout got converted into Bitmap, or maybe my implementation is just wrong. Can anyone help me with this?

@SuppressLint("InflateParams")
    private fun createCustomMarker(urlImageFromCloud: String): Bitmap{

        val marker: LayoutInflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        val view: View = marker.inflate(R.layout.map_marker, null)

        val messageIcon: Int = resources.getIdentifier("local_image_from_drawable", "drawable", this.packageName)
        val markerPhoto: CircleImageView = view.findViewById(R.id.map_photo)
        val markerContainer: CircleImageView = view.findViewById(R.id.map_photo)
        val options: RequestOptions = RequestOptions()
            .centerCrop()
            .placeholder(R.color.colorGrayWhite)
            .error(R.color.colorGrayWhite)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
        Glide.with(this)
            .load(urlImageFromCloud) // String image URL from my server/cloud - this is the part that does not show up.
            .apply(options).into(markerPhoto)
        Glide.with(this)
            .load(messageIcon)
            .apply(options).into(markerContainer)

        val displayMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(displayMetrics)

        view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels)
        view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels)
        view.buildDrawingCache()
        val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        view.draw(canvas)

        return bitmap
    }

My map_marker XML :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/custom_marker_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <ImageView
            android:id="@+id/map_container"
            android:layout_width="75dp"
            android:layout_height="75dp"/>

    <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/map_photo"
            android:src="@color/colorGray"
            android:layout_marginTop="5dp"
            android:layout_centerHorizontal="true"
            style="@style/MapMarkerCircleImage"/>

</RelativeLayout>

This is how i called my createCustomMarker method.

val defaultLocation = LatLng(locationLatitude, locationLongitude)
googleMap.addMarker(MarkerOptions().position(defaultLocation).icon(BitmapDescriptorFactory.fromBitmap(createCustomMarker("my_image_url_from_cloud"))))

Body:
I had the same issue. My solution was just to download the bitmap using Glide and with a listener create the marker when the download is complete.

private fun getMarkerIcon(context: Context, url: String, listener: (BitmapDescriptor) -> Unit) {
    val markerView = View.inflate(context, R.layout.view_marker, null)
    Glide.with(context)
        .asBitmap()
        .load(url)
        .into(object : SimpleTarget<Bitmap>() {

            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                markerView.avatarImageView.setImageBitmap(resource)
                listener.invoke(BitmapDescriptorFactory.fromBitmap(getBitmapFromView(markerView)))
            }
        })
}

private fun getBitmapFromView(view: View): Bitmap {
    view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
    val bitmap = Bitmap.createBitmap(view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.layout(0, 0, view.measuredWidth, view.measuredHeight)
    view.draw(canvas)
    return bitmap
}

And the call

getMarkerIcon(context, "http://....") {
    val options = MarkerOptions()
        .position(LatLng(latitude, longitude))
        .icon(it)
    googleMap.addMarker(options)
}


问:
Thymeleaf: Get href without application context path
How to get URL without context path?
I am using spring boot 1.5.18.RELEASE and Thymeleaf

I tried this two possibilities.

```<code><a th:href="@{${website}}" target="_blank"> Click here </a>

<a th:href="${website}" target="_blank"> Click here </a>
</code>```

For example if the ${website} has the value www.example.com I get this result:

http://localhost:8081/MyApp/www.example.com
but I would like to get only this www.example.com  without context Path.

答:
I resolved it so:</p>

```<code><th:block th:with="link=${website}">
         <a th:href="@{//{link}(link=${link})}" target="_blank">> Click here</a>
</th:block>
</code>```

Body:
How to get URL without context path?
I am using spring boot 1.5.18.RELEASE and Thymeleaf

I tried this two possibilities.

 Click here

 Click here

For example if the ${website} has the value www.example.com I get this result:

http://localhost:8081/MyApp/www.example.com
but I would like to get only this www.example.com  without context Path.

Body:
I resolved it so:

<th:block th:with="link=${website}">
         <a th:href="@{//{link}(link=${link})}" target="_blank">&gt; Click here</a>
</th:block>


问:
Breaking lines at soft hyphens
I have added soft hyphen signs to all of my strings, yet android breaks the lines at entirely different points. Is there a way to breack the lines only at the points with either a soft hyphen or a space?

Please note that I want to target API 21 and above, so using breakStrategy or hyphenation frequency is not a solution.

None of these questions/answers worked for me:
Hyphenation in Android

Android:- How to add Hyphen "-" in word break android TextView below 6.0 OS

How to force hyphenation in TextView? (character "-" on word split)

答:
You can use \n to break your string. Try this way.

```<code><string name="your_string_name">I want to break after this\nIt's working fine</string>
</code>```

Title: Breaking lines at soft hyphens

Body:
You can use \n to break your string. Try this way.

<string name="your_string_name">I want to break after this\nIt's working fine</string>