text:
Q: Using Gson and Retrofit 2 to deserialize complex API responses I'm using Retrofit 2 and Gson and I'm having trouble deserializing responses from my API. Here's my scenario:
I have a model object named Employee that has three fields: id, name, age.
I have an API that returns a singular Employee object like this:
{
    "status": "success",
    "code": 200,
    "data": {
        "id": "123",
        "id_to_name": {
            "123" : "John Doe"
        },
        "id_to_age": {
            "123" : 30
        }
    }
}

And a list of Employee objects like this:
{
    "status": "success",
    "code": 200,
    "data": [
        {
            "id": "123",
            "id_to_name": {
                "123" : "John Doe"
            },
            "id_to_age": {
                "123" : 30
            }
        },
        {
            "id": "456",
            "id_to_name": {
                "456" : "Jane Smith"
            },
            "id_to_age": {
                "456" : 35
            }
        },
    ]
}

There are three main things to consider here:

*

*API responses return in a generic wrapper, with the important part inside of the data field.

*The API returns objects in a format that doesn't directly correspond to the fields on the model (for example, the value taken from id_to_age needs be mapped to the age field on the model)

*The data field in the API response can be a singular object, or a list of objects.

How do I implement deserialization with Gson such that it handles these three cases elegantly?
Ideally, I'd prefer to do this entirely with TypeAdapter or TypeAdapterFactory instead of paying the performance penalty of JsonDeserializer. Ultimately, I want to end up with an instance of Employee or List<Employee> such that it satisfies this interface:
public interface EmployeeService {

    @GET("/v1/employees/{employee_id}")
    Observable<Employee> getEmployee(@Path("employee_id") String employeeId);

    @GET("/v1/employees")
    Observable<List<Employee>> getEmployees();

}

This earlier question I posted discusses my first attempt at this, but it fails to consider a few of the gotchas mentioned above:
Using Retrofit and RxJava, how do I deserialize JSON when it doesn't map directly to a model object?

A: I would suggest using a JsonDeserializer because there is not so many levels of nesting in the response, so it won't be a big performance hit.
Classes would look something like this:
Service interface needs to be adjusted for the generic response:
interface EmployeeService {

    @GET("/v1/employees/{employee_id}")
    Observable<DataResponse<Employee>> getEmployee(@Path("employee_id") String employeeId);

    @GET("/v1/employees")
    Observable<DataResponse<List<Employee>>> getEmployees();

}

This is a generic data response:
class DataResponse<T> {

    @SerializedName("data") private T data;

    public T getData() {
        return data;
    }
}

Employee model:
class Employee {

    final String id;
    final String name;
    final int age;

    Employee(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

}

Employee deserializer:
class EmployeeDeserializer implements JsonDeserializer<Employee> {

    @Override
    public Employee deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {

        JsonObject employeeObject = json.getAsJsonObject();
        String id = employeeObject.get("id").getAsString();
        String name = employeeObject.getAsJsonObject("id_to_name").entrySet().iterator().next().getValue().getAsString();
        int age = employeeObject.getAsJsonObject("id_to_age").entrySet().iterator().next().getValue().getAsInt();

        return new Employee(id, name, age);
    }
}

The problem with the response is that name and age are contained inside of an JSON object whitch translates to a Map in Java so it requires a bit more work to parse it.

A: EDIT: Relevant update: creating a custom converter factory DOES work--the key to avoiding an infinite loop through ApiResponseConverterFactory's is to call Retrofit's nextResponseBodyConverter which allows you to specify a factory to skip over. The key is this would be a Converter.Factory to register with Retrofit, not a TypeAdapterFactory for Gson. This would actually be preferable since it prevents double-deserialization of the ResponseBody (no need to deserialize the body then repackage it again as another response).
See the gist here for an implementation example.
ORIGINAL ANSWER:
The ApiResponseAdapterFactory approach doesn't work unless you are willing to wrap all your service interfaces with ApiResponse<T>. However, there is another option: OkHttp interceptors.
Here's our strategy:

*

*For the particular retrofit configuration, you will register an application interceptor that intercepts the Response

*Response#body() will be deserialized as an ApiResponse and we return a new Response where the ResponseBody is just the content we want.

So ApiResponse looks like:
public class ApiResponse {
  String status;
  int code;
  JsonObject data;
}

ApiResponseInterceptor:
public class ApiResponseInterceptor implements Interceptor {
  public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  public static final Gson GSON = new Gson();

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);
    final ResponseBody body = response.body();
    ApiResponse apiResponse = GSON.fromJson(body.string(), ApiResponse.class);
    body.close();

    // TODO any logic regarding ApiResponse#status or #code you need to do

    final Response.Builder newResponse = response.newBuilder()
        .body(ResponseBody.create(JSON, apiResponse.data.toString()));
    return newResponse.build();
  }
}

Configure your OkHttp and Retrofit:
OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new ApiResponseInterceptor())
        .build();
Retrofit retrofit = new Retrofit.Builder()
        .client(client)
        .build();

And Employee and EmployeeResponse should follow the adapter factory construct I wrote in the previous question. Now all of the ApiResponse fields should be consumed by the interceptor and every Retrofit call you make should only return the JSON content you are interested in.

A: Just create following TypeAdapterFactory.
public class ItemTypeAdapterFactory implements TypeAdapterFactory {

  public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>() {

        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        public T read(JsonReader in) throws IOException {

            JsonElement jsonElement = elementAdapter.read(in);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has("data")) {
                    jsonElement = jsonObject.get("data");
                }
            }

            return delegate.fromJsonTree(jsonElement);
        }
    }.nullSafe();
}

}
and add it into your GSON builder :
.registerTypeAdapterFactory(new ItemTypeAdapterFactory());

or
 yourGsonBuilder.registerTypeAdapterFactory(new ItemTypeAdapterFactory());

A: I must say that I haven't thought about using Interceptors for something like this, but that's an interesting approach. Here's what I usually do when I need to model backend-wrapper responses:
If you get something like this from the backend:
{
  "success": "success", // Let's say you may get "error", "unauthorized", etc.
  "payload": [...] // Let's say that you may either get a json object or an array.
}

Then you could declare a deserializer:
import com.demo.core.utils.exceptions.NonSuccessfullResponse
import com.google.gson.Gson
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type

/**
 * A custom deserializers that uses the generic arg TYPE to deserialize on the fly the json responses from
 * the API.
 */
class WrapperDeserializer<TYPE>(
    private val castClazz: Class<TYPE>,
    private val isList: Boolean
) : JsonDeserializer<TYPE> {

    val gson = Gson()

    override fun deserialize(
        element: JsonElement,
        arg1: Type,
        arg2: JsonDeserializationContext
    ): TYPE? {
        val jsonObject = element.asJsonObject

        if (jsonObject.get("success").asBoolean) {
            return if (isList) {
                val type = TypeToken.getParameterized(List::class.java, castClazz).type
                gson.fromJson(jsonObject.get("payload"), type)
            } else {
                gson.fromJson(jsonObject.get("payload"), castClazz)
            }
        } else {
            throw NonSuccessfullResponse()
        }
    }
}

And then in whatever place you instantiate your Gson instance you can do something like:
fun provideGson(): Gson {
        val bookListType = TypeToken.getParameterized(List::class.java, ApiAvailableBooksResponse::class.java).type
        return GsonBuilder()
            .registerTypeAdapter(bookListType, WrapperDeserializer(ApiAvailableBooksResponse::class.java, true))
            .registerTypeAdapter(ApiProfileInfoResponse::class.java, WrapperDeserializer(ApiProfileInfoResponse::class.java, false))
            .registerTypeAdapter(Date::class.java, DateDeserializer())
            .create()
    }

Notice that there we are mapping two different kinds of responses, a list of books, something like:
{
  "success": "success",
  "payload": [
    {...}, // Book 1
    {...}, // Book 2
    {...} // Book 3
  ]
}

And a single user profile response:
{
  "success": "success",
  "payload": {
     "name": "etc",
     // ...
   }
}

Again, the Interceptor approach is a very interesting option that I haven't thought about before - it worries me a bit in terms of flexibility since you're forcing all endpoint responses to follow the same standard - but it looks like a more tidy approach.


text:
Q: Cannot boot ubuntu 22.04 - can I recover OS from Grub minimal? Or get to home files to delete them? Hello everyone and thanks so much for your previous help. I still can't boot and I can't use a flash drive because I get 2 errors, an error 71 along with a home file that is too full. These are my errors:
[ 0.459335 pc1 0000:00:07.0: DPC: RP PI0 log size 0 is invalid
[ 0.471579] pc1 0000:00:07.2: DPC: RP PI0 log size 0 is invalid
/dev/nvme0n1p2 : clean, 428341/31227904 files, 118762740/124895488 blocks

I can get to Minimal Grub commands. Can I recover my Ubuntu OS from here? If not, can I get to my home file so I can delete files and hopefully get to a graphical screen?

A: Dell XPS 13 9310 -
From Paul Menzel: (In reply to Paul Menzel from comment #28)
@linparda, your problem is very likely unrelated. (In the GRUB menu, press the key e and remove quiet from the Linux kernel command line. Then boot with F10 or Ctrl + x.) It's a problem you should report to Ubuntu though.
https://bugzilla.kernel.org/show_bug.cgi?id=209943#c28
I switched out the Dell A to C usb adapter and was finally able to see the flash drive to reinstall Ubuntu 22.04.
Thank you everyone! Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dynamically change GUI element in PyQt5? Suppose I have a GUI with one button. Upon pressing the button, it should call a definition that in return insert a table in the main GUI window. My script look like below, but upon button press, I don't see any table inserted in the main GUI. Any ideas?
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton,
QLineEdit, QLabel, QComboBox, QFileDialog
import mydef

class window(QMainWindow):
    def __init__(self):
    super(window, self).__init__()
    self.setGeometry(50, 50, 500, 300)
    self.setWindowTitle('my test gui')

    #test button
    self.button = QPushButton('Insert table',self)
    self.button.move(5,20)
    self.button.clicked.connect(lambda: mydef.createtable(self))

    self.show()

def run():
    app = QApplication(sys.argv)
    gui = window()
    sys.exit(app.exec_())

run()

mydef is contains the following code
def createtable(self):
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
self.tablewidget = QTableWidget()
self.tablewidget.resize(500,200)
self.tablewidget.setRowCount(2)
self.tablewidget.setColumnCount(3)
self.tablewidget.setItem(0,0, QTableWidgetItem("item 1"))
self.show()

I don't fully understand why it does not insert the table, and also, it does not seem that I get any error when pressing the button.

A: Try it:
import sys
from PyQt5.QtCore    import QCoreApplication
from PyQt5.QtWidgets import (QApplication, QWidget, QMainWindow, QPushButton,
                             QLineEdit, QLabel, QComboBox, QFileDialog)
import mydef

class window(QMainWindow):
    def __init__(self):
        super(window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('my test gui')

        #test button
        self.button = QPushButton('Insert table',self)
        self.button.move(5,20)
        #self.button.clicked.connect(lambda: mydef.createtable(self))
        self.button.clicked.connect(self.create_table)

        self.show()

    def create_table(self):
        self.myTable = mydef.createtable()
        self.myTable.show()

def run():
    app = QApplication(sys.argv)
    gui = window()
    sys.exit(app.exec_())

run()

mydef.py
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem

def createtable():
    tablewidget = QTableWidget()
    tablewidget.resize(500,200)
    tablewidget.setRowCount(2)
    tablewidget.setColumnCount(3)
    tablewidget.setItem(0,0, QTableWidgetItem("item 1"))

    return tablewidget

main_2.py
import sys
from PyQt5.QtCore    import QCoreApplication
from PyQt5.QtWidgets import (QApplication, QWidget, QMainWindow, QPushButton, QVBoxLayout,
                             QLineEdit, QLabel, QComboBox, QFileDialog)
import mydef

class window(QMainWindow):
    def __init__(self):
        super(window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle('my test gui')

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.lay = QVBoxLayout(self.central_widget)

        #test button
        self.button = QPushButton('Insert table', self)
        self.button.move(5,20)
        #self.button.clicked.connect(lambda: mydef.createtable(self))
        self.button.clicked.connect(self.create_table)

        self.lay.addWidget(self.button)
        self.lay.addStretch(1)

        self.show()

    def create_table(self):
        self.myTable = mydef.createtable()

        self.lay.addWidget(self.myTable)
        self.lay.addStretch(1)

def run():
    app = QApplication(sys.argv)
    gui = window()
    sys.exit(app.exec_())

run()

A: You cannot add the table to the current GUI by calling the show() method.  If you use a layout for the main window you can simply add the table to the layout.
Here is an example:
class GUITest(QtWidgets.QWidget):

    def __init__(self):
        QtWidgets.QWidget.__init__(self)

        self.layout = QtWidgets.QGridLayout()

        self.button = QtWidgets.QPushButton('Insert Table')
        self.button.clicked.connect(self.create_table)

        self.layout.addWidget(self.button)

        self.setLayout(self.layout)

    def create_table(self):
        self.tablewidget = QtWidgets.QTableWidget()
        self.tablewidget.resize(500, 200)
        self.tablewidget.setRowCount(2)
        self.tablewidget.setColumnCount(3)
        self.tablewidget.setItem(0, 0, QtWidgets.QTableWidgetItem("item 1"))

        self.layout.addWidget(self.tablewidget)  # add the table to the layout

If the table has to be added from another class the way that you show, you can supply the layout to the create_table method and use basically the same method as above.
def create_table(self, layout):
    # create table widget
    layout.addWidget(self.tablewidget)


text:
Q: Why is grid-template-row not working properly? I was expecting that setting grid-template-rows to fr will make that row to expand to fill all available space but in my case it is not doing it anyway. In other words below code must have resulted in three rows first and third of which are as thin as their content while second row fills the all remaining space in between. Tried it both on my local machine and codesandbox and am getting the same result

html:

1

2

3

css:
.container {
  display: grid;
  grid-template-rows: auto 1fr auto;
}

.item {
  border: 1px solid red;
}

A: Yes, 1fr will expand the 'item' element to fill available space, but it will not influence it parent's height. If I understood your question correctly You should set the height of your parent element to 100% to achieve the desired result.


text:
Q: Estilo moeda numa TextBox em WinForms Preciso colocar o texto R$ numa textbox de forma a que fique com o seguinte formato:

R$: 1.200,58

Estou tentando das seguintes formas sem sucesso:
textbox1.Text = Convert.ToDouble(textbox1.Text).ToString("C");

e
textbox1.Text = Decimal.Parse(texbox.text).ToString("N2");

A: Caso você aceite o uso de eventos, pode usar dessa maneira:
Função para colocar a mascara
    private void RetornarMascara(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        txt.Text = double.Parse(txt.Text).ToString("C2");
    }

Função para retirar a mascara
    private void TirarMascara(object sender, EventArgs e)
    {
        TextBox txt = (TextBox)sender;
        txt.Text = txt.Text.Replace("R$", "").Trim();
    }

Função para somente permitir números e virgula
    private void ApenasValorNumerico(object sender, KeyPressEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
        {
            if (e.KeyChar == ',')
            {
                e.Handled = (txt.Text.Contains(','));
            }
            else
                e.Handled = true;
        }
    }

Aplica todas as funções aos respectivos eventos
    private void AplicarEventos(TextBox txt)
    {
        txt.Enter += TirarMascara;
        txt.Leave += RetornarMascara;
        txt.KeyPress += ApenasValorNumerico;
    }

Exemplo de uso:
    public Form1()
    {
        InitializeComponent();

        AplicarEventos(textBox1);
        AplicarEventos(textBox2);
    }

A: Utilizo a função javascript abaixo pra colocar a mascara:
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789\37';
var aux = aux2 = '';
if (!e) e = window.event;
var whichCode = e.which || e.keyCode;
if (isValidKey(whichCode)) return true;
key = String.fromCharCode(whichCode); // Valor para o c¢digo da Chave
if (strCheck.indexOf(key) == -1) return false; // Chave inv lida
len = objTextBox.value.length;
for (i = 0; i < len; i++)
    if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
aux = '';
for (; i < len; i++)
    if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1) aux += objTextBox.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) objTextBox.value = '';
if (len == 1) objTextBox.value = '0' + SeparadorDecimal + '0' + aux;
if (len == 2) objTextBox.value = '0' + SeparadorDecimal + aux;
if (len > 2)
{
    aux2 = '';
    for (j = 0, i = len - 3; i >= 0; i--)
    {
        if (j == 3)
        {
            aux2 += SeparadorMilesimo;
            j = 0;
        }
        aux2 += aux.charAt(i);
        j++;
    }
    objTextBox.value = '';
    len2 = aux2.length;
    for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
    objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
}
return false;
}

coloque a chamada no evento onkeypress do seu textbox, return(MascaraMoeda(this,'.',',',event));
Teste e veja se causa o efeito desejado.
ou você pode utilizar alguma biblioteca jquery, exemplo:
http://www.fabiobmed.com.br/criando-mascaras-para-moedas-com-jquery/

A: Aí @Fabricio é bem simples.
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("pt-BR");
        label.Text = string.Format("{0:C}", Convert.ToDouble(1200.58));

Mas lembre-se tudo vai depender da sua CultureInfo e CultureUi. Se elas estiverem em outra língua, não vai funcionar do jeito que você quer!

A: Crie um textbox com o nome txt_valor e atribua os eventos KeyPress, Leave, KeyUp e uma string valor
string valor;
private void txt_valor_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!Char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
    {
        if (e.KeyChar == ',')
        {
            e.Handled = (txt_valor.Text.Contains(","));
        }
        else
            e.Handled = true;
    }
}

private void txt_valor_Leave(object sender, EventArgs e)
{
    valor = txt_valor.Text.Replace("R$", "");
    txt_valor.Text = string.Format("{0:C}", Convert.ToDouble(valor));
}

private void txt_valor_KeyUp(object sender, KeyEventArgs e)
{
    valor = txt_valor.Text.Replace("R$","").Replace(",","").Replace(" ","").Replace("00,","");
    if(valor.Length == 0)
    {
        txt_valor.Text = "0,00"+valor;
    }
    if(valor.Length == 1)
    {
        txt_valor.Text = "0,0"+valor;
    }
    if(valor.Length == 2)
    {
        txt_valor.Text = "0,"+valor;
    }
    else if(valor.Length >= 3)
    {
        if(txt_valor.Text.StartsWith("0,"))
        {
            txt_valor.Text = valor.Insert(valor.Length - 2,",").Replace("0,","");
        }
        else if(txt_valor.Text.Contains("00,"))
        {
            txt_valor.Text = valor.Insert(valor.Length - 2,",").Replace("00,","");
        }
        else
        {
            txt_valor.Text = valor.Insert(valor.Length - 2,",");
        }
    }
    valor = txt_valor.Text;
    txt_valor.Text = string.Format("{0:C}", Convert.ToDouble(valor));
    txt_valor.Select(txt_valor.Text.Length,0);
}

A: Quando tenho dúvida sempre aqui encontro soluções que me auxiliam a realizar o que quero....
Por este motivo hoje venho contribuir.
Não sei se é a melhor forma, mas ai vai como utilizo.
Tenho uma classe static chamada uUseful, nela possuo três métodos public.
Método KeyPress (Class cUseful)
public static void DecimalKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if (sender.GetType().Name != "TextBox") return;
        System.Windows.Forms.TextBox objTextBox = (sender as System.Windows.Forms.TextBox);

        if (e.KeyChar == '.')
        {
            if (objTextBox.Text.IndexOf(",") >= 0)
            {
                e.Handled = true;
                return;
            }
            if (objTextBox.Text.Trim().Length < 1)
            {
                e.Handled = true;
                objTextBox.Text = "0,";
                objTextBox.SelectionStart = objTextBox.Text.Length;
                return;
            }
            else
            {
                e.KeyChar = ',';
            }
        }
    }

Método KeyDown (Class cUseful)
public static void DecimalKeyDown(object sender, System.Windows.Forms.KeyEventArgs e, int pNumberDecimalPlaces = 2)
    {
        if (sender.GetType().Name != "TextBox") return;
        System.Windows.Forms.TextBox objTextBox = (sender as System.Windows.Forms.TextBox);

        if (objTextBox.SelectionLength == objTextBox.Text.Length || objTextBox.Text == ("0,").ToString().PadRight(pNumberDecimalPlaces, '0')) objTextBox.Text = "";

        if (e.KeyCode < System.Windows.Forms.Keys.D0 || e.KeyCode > System.Windows.Forms.Keys.D9)
        {
            if (e.KeyCode < System.Windows.Forms.Keys.NumPad0 || e.KeyCode > System.Windows.Forms.Keys.NumPad9)
            {
                if (e.KeyCode != System.Windows.Forms.Keys.Back)
                {
                    if (e.KeyCode == System.Windows.Forms.Keys.Oemcomma || e.KeyCode == System.Windows.Forms.Keys.Decimal || e.KeyCode == System.Windows.Forms.Keys.OemPeriod)
                    {

                        if (objTextBox.Text.IndexOf(",") >= 0) // só permite uma virgula
                        {
                            e.SuppressKeyPress = true;
                            return;
                        }

                        if (objTextBox.Text.Trim().Length < 1) // caso coloque uma virgula sem colocar valor
                        {
                            objTextBox.Text = "0,";
                            e.SuppressKeyPress = true;
                            objTextBox.SelectionStart = objTextBox.Text.Length;
                            return;
                        }

                    }
                    else
                    {
                        e.SuppressKeyPress = true;
                        return;
                    }
                }
                else
                {
                    if (objTextBox.Text == "0,")
                    {
                        objTextBox.Text = "";
                        e.SuppressKeyPress = true;
                        return;
                    }
                }
            }
            else
            {
                if (objTextBox.Text.IndexOf(",") >= 0)
                {
                    if (((System.Convert.ToInt32(objTextBox.Text.IndexOf(",") + 1) - objTextBox.Text.Length) * -1) == pNumberDecimalPlaces)
                    {
                        e.SuppressKeyPress = true;
                        return;
                    }
                }
            }
        }
    }

Método Leave (Class cUseful)
public static void DecimalLeave(object sender, System.EventArgs e, int pNumberDecimalPlaces = 2)
    {
        if (sender.GetType().Name != "TextBox") return;
        System.Windows.Forms.TextBox objTextBox = (sender as System.Windows.Forms.TextBox);

        if (!string.IsNullOrEmpty(objTextBox.Text))
        {
            if (objTextBox.Text.Trim().Length != 0) objTextBox.Text = System.Convert.ToDecimal(objTextBox.Text.Replace(".", ",")).ToString("n2");
            else objTextBox.Text = ("0,").ToString().PadRight(pNumberDecimalPlaces, '0');
        }
        else
        {
            objTextBox.Text = ("0,").ToString().PadRight(pNumberDecimalPlaces, '0');
        }
    }

Já na interface possuo três métodos de direcionamento
Método KeyPress (Form)
private void DecimalKeyPress(object sender, KeyPressEventArgs e)
        {
            BackEnd.cUseful.DecimalKeyPress(sender, e);
        }

Método KeyDown (Form)
private void DecimalKeyDown(object sender, KeyEventArgs e)
        {
            BackEnd.cUseful.DecimalKeyDown(sender, e);
        }

Método Leave (Form)
private void DecimalLeave(object sender, System.EventArgs e)
        {
            BackEnd.cUseful.DecimalLeave(sender, e);
        }

Por fim, inicio a propriedade Text dos objectos TextBox com o valor "0,00" e vou aos métodos KeyPress, KeyDown e Leave e seleciono os métodos privados criados no (Form).

Att.
Ingeniero de software en América Latina
Robson Knevitz


text:
Q: How to add text or label in dataframe style to display the information I have below style to show the difference of two dataframe, and additionally How do i display total number of records and number of mismatch rows using dataframe/pandas style?
       def highlight_diff(data, color='yellow'):
            attr = 'background-color: {}'.format(color)
            other = data.xs('First', axis='columns', level=-1)
            return pd.DataFrame(np.where(data.ne(other, level=0), attr, ''),
                                index=data.index, columns=data.columns)
        caption_styles = {
            'selector':'caption',
            'props':[('font-weight', 'bold'),('margin-bottom','25px'),('font-size','25px')]
        }
        select_styles = {  # for row hover use
 instead of
            'selector': '',
            'props': [('border-collapse', 'collapse'),('margin', '100px auto')]
        }

        table_styles = {  # for row hover use
 instead of
            'selector': 'table',
            'props': [('border-collapse', 'collapse'),('margin', '100px auto')]
        }

        tbody_styles = {  # for row hover use
 instead of
            'selector': 'tbody',
            'props': [('border', '1px solid #A2DBFA')]
        }
        td_styles = {  # for row hover use
 instead of
            'selector': 'td',
            'props': [('border', '1px solid #A2DBFA'),('padding','1em'),('border-bottom','2px solid #A2DBFA')]
        }
        th_styles = {  # for row hover use
 instead of
            'selector': 'th',
            'props': [('border', '1px solid #A2DBFA'),('padding','1em'),('background-color','#39A2DB'),('border-bottom','2px solid #A2DBFA')]
        }
df_all = pd.concat([df_source.set_index('id'), df_target.set_index('id')],
                   axis='columns', keys=['First', 'Second']).drop_duplicates(keep=False)
df_final = df_all.swaplevel(axis='columns')[df_source.columns[1:]]
        df_out = df_final.style.set_table_styles([caption_styles,select_styles,table_styles, tbody_styles,td_styles, th_styles]).set_caption("Test Case 1").apply(highlight_diff, axis=None)

once i have all the data, i will be rendering using df.render() and will be writing as Html.
I want to display the total number of records and number of mismatch rows using pandas/dataframe style(mentioned in red text)

A: You can either
a) (simplest) incorporate the information into the caption, and insert the calculated values:
df = pd.DataFrame(index=pd.MultiIndex.from_product([["Unit 1", "Unit 2"], ["Some Value", "Another"]], names=["Dept", "Workflow"]),
                  columns=["Comment 1", "Comment 2"],
                  data=[["Green", "Red"], ["Yellow", "Yellow"], ["Green", "Red"], ["Yellow", "Yellow"]])
styler = df.style
styler.set_table_styles([{'selector': 'td', 'props': 'text-align: left;'},
                         {'selector': 'th.level1', 'props': 'text-align: left;'},
                         {'selector': 'caption', 'props': 'color: red;'}])\
      .applymap(lambda x: f"color: {x.lower()}")\
      .set_caption(f"number of reds: {2}
number of rows: {4}")

Since the caption is rendered directly as HTML from string you can actually be clever and use the caption to build multiple elements. For example:
styler.set_table_styles([{'selector': 'td', 'props': 'text-align: left;'},
                         {'selector': 'th.level1', 'props': 'text-align: left;'},
                         {'selector': 'caption', 'props': 'color: red;'},
                         {'selector': '.my-cls', 'props': 'color: blue; font-size: 16pt;'])\
      .applymap(lambda x: f"color: {x.lower()}")\
      .set_caption('Big Blue Text
little red text')

b) (harder) Subclass the styler template as explained in the user guide
Create a new file, "my_html.tpl" in the same directory as your notebook as follows:
{% extends "html_table.tpl" %}
{% block table %}

{{ table_title|default("My Table") }}

number of reds: {{ reds }}
number of rows: {{ rows }}

{{ super() }}
{% endblock table %}

Then create your own Styler
from pandas.io.formats.style import Styler
MyStyler = Styler.from_custom_template(searchpath="", html_table="my_table.tpl")
styler = MyStyler(df)
styler.set_table_styles([{'selector': 'td', 'props': 'text-align: left;'},
                         {'selector': 'th.level1', 'props': 'text-align: left;'}])\
      .applymap(lambda x: f"color: {x.lower()}")\
      .render(reds=2, rows=4)


text:
Q: Pushing configuration changes to an iOS app we have an app which gets its configuration from a portal.
This is neither an MDM Portal nore any MDM Functionality is available in the app.
If the app starts for the first time, it contacts the portal and gets its initial configuration.
After this, it is polling the portal in a regular intervals to receive changes, if there is any.
I want to stop the polling. If there is a change, the Portal should PUSH it to its Apps. This can be done by Push Notifications, I can send some hint to the app, that there is new configuration to take it, but if the app does not run, the user can ignore this or according to the documentation, the PN is not a reliable system for vital information.
What could be the solution, did anyone have the same situation and solved it ?

A: You should use the silent push notifications (using content-available APNS payload key).
Of course this is not guaranteed to be received so you should also implement some sort of data versioning / etag / date last updated mechanism which you poll when the app is opened in order to download the latest data manually if your silent notification was not received.


text:
Q: SelectPicker - Select option Live search if the result doesn't match by bootstrap-select I want to display other for default and enable to select. The case is if we type and didn't match between the result and option.

$('.selectpicker').selectpicker({
     noneResultsText: 'I found no results'
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>

<select class="selectpicker" data-live-search="true" >
    <option value="other">other</option>
    <option>Alabama</option>
    <option>Alaska </option>
    <option>Arizona </option>
</select>

How to condition value="other" will show if didn't match between result and option?

A: I modified bootstrap-select.js to accommodate that behavior;
I inserted this line of code after the search event, this would search for the option with "Other" in its data attribute and will always display it.
    var defaultOption;

    that.$lis.find('a').each(function(){
      // console.log($(this).data("normalized-text"));

      if($(this).data("normalized-text").indexOf("other") >-1){
        defaultOption = $(this);
      }
    });

    defaultOption.parent().removeClass('hide').show();

I minified the script below. Do run the snippet.

!function(e){"use strict";function t(e,t){return e.toUpperCase().indexOf(t.toUpperCase())>-1}function i(t){return e.each([{re:/[\xC0-\xC6]/g,ch:"A"},{re:/[\xE0-\xE6]/g,ch:"a"},{re:/[\xC8-\xCB]/g,ch:"E"},{re:/[\xE8-\xEB]/g,ch:"e"},{re:/[\xCC-\xCF]/g,ch:"I"},{re:/[\xEC-\xEF]/g,ch:"i"},{re:/[\xD2-\xD6]/g,ch:"O"},{re:/[\xF2-\xF6]/g,ch:"o"},{re:/[\xD9-\xDC]/g,ch:"U"},{re:/[\xF9-\xFC]/g,ch:"u"},{re:/[\xC7-\xE7]/g,ch:"c"},{re:/[\xD1]/g,ch:"N"},{re:/[\xF1]/g,ch:"n"}],function(){t=t.replace(this.re,this.ch)}),t}function n(e){var t={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},i="(?:"+Object.keys(t).join("|")+")",n=new RegExp(i),s=new RegExp(i,"g"),o=null==e?"":""+e;return n.test(o)?o.replace(s,function(e){return t[e]}):o}e.expr[":"].icontains=function(i,n,s){return t(e(i).text(),s[3])},e.expr[":"].aicontains=function(i,n,s){return t(e(i).data("normalizedText")||e(i).text(),s[3])};var s=function(t,i,n){n&&(n.stopPropagation(),n.preventDefault()),this.$element=e(t),this.$newElement=null,this.$button=null,this.$menu=null,this.$lis=null,this.options=i,null===this.options.title&&(this.options.title=this.$element.attr("title")),this.val=s.prototype.val,this.render=s.prototype.render,this.refresh=s.prototype.refresh,this.setStyle=s.prototype.setStyle,this.selectAll=s.prototype.selectAll,this.deselectAll=s.prototype.deselectAll,this.destroy=s.prototype.remove,this.remove=s.prototype.remove,this.show=s.prototype.show,this.hide=s.prototype.hide,this.init()};function o(t,i){var n,o=arguments,a=t;t=o[0],i=o[1];[].shift.apply(o),void 0===t&&(t=a);var l=this.each(function(){var a=e(this);if(a.is("select")){var l=a.data("selectpicker"),d="object"==typeof t&&t;if(l){if(d)for(var r in d)d.hasOwnProperty(r)&&(l.options[r]=d[r])}else{var c=e.extend({},s.DEFAULTS,e.fn.selectpicker.defaults||{},a.data(),d);a.data("selectpicker",l=new s(this,c,i))}"string"==typeof t&&(n=l[t]instanceof Function?l[t].apply(l,o):l.options[t])}});return void 0!==n?n:l}s.VERSION="1.6.2",s.DEFAULTS={noneSelectedText:"Nothing selected",noneResultsText:"No results match",countSelectedText:function(e,t){return 1==e?"{0} item selected":"{0} items selected"},maxOptionsText:function(e,t){var i=[];return i[0]=1==e?"Limit reached ({n} item max)":"Limit reached ({n} items max)",i[1]=1==t?"Group limit reached ({n} item max)":"Group limit reached ({n} items max)",i},selectAllText:"Select All",deselectAllText:"Deselect All",multipleSeparator:", ",style:"btn-default",size:"auto",title:null,selectedTextFormat:"values",width:!1,container:!1,hideDisabled:!1,showSubtext:!1,showIcon:!0,showContent:!0,dropupAuto:!0,header:!1,liveSearch:!1,actionsBox:!1,iconBase:"glyphicon",tickIcon:"glyphicon-ok",maxOptions:!1,mobile:!1,selectOnTab:!1,dropdownAlignRight:!1,searchAccentInsensitive:!1},s.prototype={constructor:s,init:function(){var t=this,i=this.$element.attr("id");this.$element.hide(),this.multiple=this.$element.prop("multiple"),this.autofocus=this.$element.prop("autofocus"),this.$newElement=this.createView(),this.$element.after(this.$newElement),this.$menu=this.$newElement.find("> .dropdown-menu"),this.$button=this.$newElement.find("> button"),this.$searchbox=this.$newElement.find("input"),this.options.dropdownAlignRight&&this.$menu.addClass("dropdown-menu-right"),void 0!==i&&(this.$button.attr("data-id",i),e('label[for="'+i+'"]').click(function(e){e.preventDefault(),t.$button.focus()})),this.checkDisabled(),this.clickListener(),this.options.liveSearch&&this.liveSearchListener(),this.render(),this.liHeight(),this.setStyle(),this.setWidth(),this.options.container&&this.selectPosition(),this.$menu.data("this",this),this.$newElement.data("this",this),this.options.mobile&&this.mobile()},createDropdown:function(){var t=this.multiple?" show-tick":"",i=this.$element.parent().hasClass("input-group")?" input-group-btn":"",n=this.autofocus?" autofocus":"",s=this.$element.parents().hasClass("form-group-lg")?" btn-lg":this.$element.parents().hasClass("form-group-sm")?" btn-sm":"",o=this.options.header?'
<button type="button" class="close" aria-hidden="true">×</button>'+this.options.header+"
":"",a=this.options.liveSearch?'
<input type="text" class="input-block-level form-control" autocomplete="off" />
':"",l=this.options.actionsBox?'

<button class="actions-btn bs-select-all btn btn-sm btn-default">'+this.options.selectAllText+'</button><button class="actions-btn bs-deselect-all btn btn-sm btn-default">'+this.options.deselectAllText+"</button>

":"";return e('
<button type="button" class="btn dropdown-toggle selectpicker'+s+'" data-toggle="dropdown"'+n+'> </button>
'+o+a+l+'

')},createView:function(){var e=this.createDropdown(),t=this.createLi();return e.find("ul").append(t),e},reloadLi:function(){this.destroyLi();var e=this.createLi();this.$menu.find("ul").append(e)},destroyLi:function(){this.$menu.find("li").remove()},createLi:function(){var t=this,s=[],o=0,a=function(e,t,i){return"
"+e+"
"},l=function(e,s,o,a){var l=i(n(e));return''+e+''};return this.$element.find("option").each(function(){var i=e(this),n=i.attr("class")||"",d=i.attr("style"),r=i.data("content")?i.data("content"):i.html(),c=void 0!==i.data("subtext")?''+i.data("subtext")+"":"",h=void 0!==i.data("icon")?' ':"",p=i.is(":disabled")||i.parent().is(":disabled"),u=i[0].index;if(""!==h&&p&&(h=""+h+""),i.data("content")||(r=h+''+r+c+""),!t.options.hideDisabled||!p)if(i.parent().is("optgroup")&&!0!==i.data("divider")){if(0===i.index()){o+=1;var f=i.parent().attr("label"),m=void 0!==i.parent().data("subtext")?''+i.parent().data("subtext")+"":"";f=(i.parent().data("icon")?' ':"")+''+f+m+"",0!==u&&s.length>0&&s.push(a("",null,"divider")),s.push(a(f,null,"dropdown-header"))}s.push(a(l(r,"opt "+n,d,o),u))}else!0===i.data("divider")?s.push(a("",u,"divider")):!0===i.data("hidden")?s.push(a(l(r,n,d),u,"hide is-hidden")):s.push(a(l(r,n,d),u))}),this.multiple||0!==this.$element.find("option:selected").length||this.options.title||this.$element.find("option").eq(0).prop("selected",!0).attr("selected","selected"),e(s.join(""))},findLis:function(){return null==this.$lis&&(this.$lis=this.$menu.find("li")),this.$lis},render:function(t){var i=this;!1!==t&&this.$element.find("option").each(function(t){i.setDisabled(t,e(this).is(":disabled")||e(this).parent().is(":disabled")),i.setSelected(t,e(this).is(":selected"))}),this.tabIndex();var s=this.options.hideDisabled?":not([disabled])":"",o=this.$element.find("option:selected"+s).map(function(){var t,n=e(this),s=n.data("icon")&&i.options.showIcon?' ':"";return t=i.options.showSubtext&&n.attr("data-subtext")&&!i.multiple?' '+n.data("subtext")+"":"",n.data("content")&&i.options.showContent?n.data("content"):void 0!==n.attr("title")?n.attr("title"):s+n.html()+t}).toArray(),a=this.multiple?o.join(this.options.multipleSeparator):o[0];if(this.multiple&&this.options.selectedTextFormat.indexOf("count")>-1){var l=this.options.selectedTextFormat.split(">");if(l.length>1&&o.length>l[1]||1==l.length&&o.length>=2){s=this.options.hideDisabled?", [disabled]":"";var d=this.$element.find("option").not('[data-divider="true"], [data-hidden="true"]'+s).length;a=("function"==typeof this.options.countSelectedText?this.options.countSelectedText(o.length,d):this.options.countSelectedText).replace("{0}",o.length.toString()).replace("{1}",d.toString())}}this.options.title=this.$element.attr("title"),"static"==this.options.selectedTextFormat&&(a=this.options.title),a||(a=void 0!==this.options.title?this.options.title:this.options.noneSelectedText),this.$button.attr("title",n(a)),this.$newElement.find(".filter-option").html(a)},setStyle:function(e,t){this.$element.attr("class")&&this.$newElement.addClass(this.$element.attr("class").replace(/selectpicker|mobile-device|validate\[.*\]/gi,""));var i=e||this.options.style;"add"==t?this.$button.addClass(i):"remove"==t?this.$button.removeClass(i):(this.$button.removeClass(this.options.style),this.$button.addClass(i))},liHeight:function(){if(!1!==this.options.size){var e=this.$menu.parent().clone().find("> .dropdown-toggle").prop("autofocus",!1).end().appendTo("body"),t=e.addClass("open").find("> .dropdown-menu"),i=t.find("li").not(".divider").not(".dropdown-header").filter(":visible").children("a").outerHeight(),n=this.options.header?t.find(".popover-title").outerHeight():0,s=this.options.liveSearch?t.find(".bs-searchbox").outerHeight():0,o=this.options.actionsBox?t.find(".bs-actionsbox").outerHeight():0;e.remove(),this.$newElement.data("liHeight",i).data("headerHeight",n).data("searchHeight",s).data("actionsHeight",o)}},setSize:function(){this.findLis();var t,i,n,s=this,o=this.$menu,a=o.find(".inner"),l=this.$newElement.outerHeight(),d=this.$newElement.data("liHeight"),r=this.$newElement.data("headerHeight"),c=this.$newElement.data("searchHeight"),h=this.$newElement.data("actionsHeight"),p=this.$lis.filter(".divider").outerHeight(!0),u=parseInt(o.css("padding-top"))+parseInt(o.css("padding-bottom"))+parseInt(o.css("border-top-width"))+parseInt(o.css("border-bottom-width")),f=this.options.hideDisabled?", .disabled":"",m=e(window),v=u+parseInt(o.css("margin-top"))+parseInt(o.css("margin-bottom"))+2,b=function(){i=s.$newElement.offset().top-m.scrollTop(),n=m.height()-i-l};if(b(),this.options.header&&o.css("padding-top",0),"auto"==this.options.size){var $=function(){var e,l=s.$lis.not(".hide");b(),t=n-v,s.options.dropupAuto&&s.$newElement.toggleClass("dropup",i>n&&t-v<o.height()),s.$newElement.hasClass("dropup")&&(t=i-v),e=l.length+l.filter(".dropdown-header").length>3?3*d+v-2:0,o.css({"max-height":t+"px",overflow:"hidden","min-height":e+r+c+h+"px"}),a.css({"max-height":t-r-c-h-u+"px","overflow-y":"auto","min-height":Math.max(e-u,0)+"px"})};$(),this.$searchbox.off("input.getSize propertychange.getSize").on("input.getSize propertychange.getSize",$),e(window).off("resize.getSize").on("resize.getSize",$),e(window).off("scroll.getSize").on("scroll.getSize",$)}else if(this.options.size&&"auto"!=this.options.size&&o.find("li"+f).length>this.options.size){var g=this.$lis.not(".divider"+f).find(" > *").slice(0,this.options.size).last().parent().index(),x=this.$lis.slice(0,g+1).filter(".divider").length;t=d*this.options.size+x*p+u,s.options.dropupAuto&&this.$newElement.toggleClass("dropup",i>n&&t<o.height()),o.css({"max-height":t+r+c+h+"px",overflow:"hidden"}),a.css({"max-height":t-u+"px","overflow-y":"auto"})}},setWidth:function(){if("auto"==this.options.width){this.$menu.css("min-width","0");var e=this.$newElement.clone().appendTo("body"),t=e.find("> .dropdown-menu").css("width"),i=e.css("width","auto").find("> button").css("width");e.remove(),this.$newElement.css("width",Math.max(parseInt(t),parseInt(i))+"px")}else"fit"==this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width","").addClass("fit-width")):this.options.width?(this.$menu.css("min-width",""),this.$newElement.css("width",this.options.width)):(this.$menu.css("min-width",""),this.$newElement.css("width",""));this.$newElement.hasClass("fit-width")&&"fit"!==this.options.width&&this.$newElement.removeClass("fit-width")},selectPosition:function(){var t,i,n=this,s=e("
"),o=function(e){s.addClass(e.attr("class").replace(/form-control/gi,"")).toggleClass("dropup",e.hasClass("dropup")),t=e.offset(),i=e.hasClass("dropup")?0:e[0].offsetHeight,s.css({top:t.top+i,left:t.left,width:e[0].offsetWidth,position:"absolute"})};this.$newElement.on("click",function(){n.isDisabled()||(o(e(this)),s.appendTo(n.options.container),s.toggleClass("open",!e(this).hasClass("open")),s.append(n.$menu))}),e(window).resize(function(){o(n.$newElement)}),e(window).on("scroll",function(){o(n.$newElement)}),e("html").on("click",function(t){e(t.target).closest(n.$newElement).length<1&&s.removeClass("open")})},setSelected:function(e,t){this.findLis(),this.$lis.filter('[data-original-index="'+e+'"]').toggleClass("selected",t)},setDisabled:function(e,t){this.findLis(),t?this.$lis.filter('[data-original-index="'+e+'"]').addClass("disabled").find("a").attr("href","#").attr("tabindex",-1):this.$lis.filter('[data-original-index="'+e+'"]').removeClass("disabled").find("a").removeAttr("href").attr("tabindex",0)},isDisabled:function(){return this.$element.is(":disabled")},checkDisabled:function(){var e=this;this.isDisabled()?this.$button.addClass("disabled").attr("tabindex",-1):(this.$button.hasClass("disabled")&&this.$button.removeClass("disabled"),-1==this.$button.attr("tabindex")&&(this.$element.data("tabindex")||this.$button.removeAttr("tabindex"))),this.$button.click(function(){return!e.isDisabled()})},tabIndex:function(){this.$element.is("[tabindex]")&&(this.$element.data("tabindex",this.$element.attr("tabindex")),this.$button.attr("tabindex",this.$element.data("tabindex")))},clickListener:function(){var t=this;this.$newElement.on("touchstart.dropdown",".dropdown-menu",function(e){e.stopPropagation()}),this.$newElement.on("click",function(){t.setSize(),t.options.liveSearch||t.multiple||setTimeout(function(){t.$menu.find(".selected a").focus()},10)}),this.$menu.on("click","li a",function(i){var n=e(this),s=n.parent().data("originalIndex"),o=t.$element.val(),a=t.$element.prop("selectedIndex");if(t.multiple&&i.stopPropagation(),i.preventDefault(),!t.isDisabled()&&!n.parent().hasClass("disabled")){var l=t.$element.find("option"),d=l.eq(s),r=d.prop("selected"),c=d.parent("optgroup"),h=t.options.maxOptions,p=c.data("maxOptions")||!1;if(t.multiple){if(d.prop("selected",!r),t.setSelected(s,!r),n.blur(),!1!==h||!1!==p){var u=h<l.filter(":selected").length,f=p<c.find("option:selected").length;if(h&&u||p&&f)if(h&&1==h)l.prop("selected",!1),d.prop("selected",!0),t.$menu.find(".selected").removeClass("selected"),t.setSelected(s,!0);else if(p&&1==p){c.find("option:selected").prop("selected",!1),d.prop("selected",!0);var m=n.data("optgroup");t.$menu.find(".selected").has('a[data-optgroup="'+m+'"]').removeClass("selected"),t.setSelected(s,!0)}else{var v="function"==typeof t.options.maxOptionsText?t.options.maxOptionsText(h,p):t.options.maxOptionsText,b=v[0].replace("{n}",h),$=v[1].replace("{n}",p),g=e('

');v[2]&&(b=b.replace("{var}",v[2][h>1?0:1]),$=$.replace("{var}",v[2][p>1?0:1])),d.prop("selected",!1),t.$menu.append(g),h&&u&&(g.append(e("
"+b+"
")),t.$element.trigger("maxReached.bs.select")),p&&f&&(g.append(e("
"+$+"
")),t.$element.trigger("maxReachedGrp.bs.select")),setTimeout(function(){t.setSelected(s,!1)},10),g.delay(750).fadeOut(300,function(){e(this).remove()})}}}else l.prop("selected",!1),d.prop("selected",!0),t.$menu.find(".selected").removeClass("selected"),t.setSelected(s,!0);t.multiple?t.options.liveSearch&&t.$searchbox.focus():t.$button.focus(),(o!=t.$element.val()&&t.multiple||a!=t.$element.prop("selectedIndex")&&!t.multiple)&&t.$element.change()}}),this.$menu.on("click","li.disabled a, .popover-title, .popover-title :not(.close)",function(e){e.target==this&&(e.preventDefault(),e.stopPropagation(),t.options.liveSearch?t.$searchbox.focus():t.$button.focus())}),this.$menu.on("click","li.divider, li.dropdown-header",function(e){e.preventDefault(),e.stopPropagation(),t.options.liveSearch?t.$searchbox.focus():t.$button.focus()}),this.$menu.on("click",".popover-title .close",function(){t.$button.focus()}),this.$searchbox.on("click",function(e){e.stopPropagation()}),this.$menu.on("click",".actions-btn",function(i){t.options.liveSearch?t.$searchbox.focus():t.$button.focus(),i.preventDefault(),i.stopPropagation(),e(this).is(".bs-select-all")?t.selectAll():t.deselectAll(),t.$element.change()}),this.$element.change(function(){t.render(!1)})},liveSearchListener:function(){var t=this,s=e('

');this.$newElement.on("click.dropdown.data-api",function(){t.$menu.find(".active").removeClass("active"),t.$searchbox.val()&&(t.$searchbox.val(""),t.$lis.not(".is-hidden").removeClass("hide"),s.parent().length&&s.remove()),t.multiple||t.$menu.find(".selected").addClass("active"),setTimeout(function(){t.$searchbox.focus()},10)}),this.$searchbox.on("input propertychange",function(){var o;t.$searchbox.val()?(t.options.searchAccentInsensitive?t.$lis.not(".is-hidden").removeClass("hide").find("a").not(":aicontains("+i(t.$searchbox.val())+")").parent().addClass("hide"):t.$lis.not(".is-hidden").removeClass("hide").find("a").not(":icontains("+t.$searchbox.val()+")").parent().addClass("hide"),t.$menu.find("li").filter(":visible:not(.no-results)").length?s.parent().length&&s.remove():(s.parent().length&&s.remove(),s.html(t.options.noneResultsText+' "'+n(t.$searchbox.val())+'"').show(),t.$menu.find("li").last().after(s))):(t.$lis.not(".is-hidden").removeClass("hide"),s.parent().length&&s.remove()),t.$menu.find("li.active").removeClass("active"),t.$menu.find("li").filter(":visible:not(.divider)").eq(0).addClass("active").find("a").focus(),e(this).focus(),t.$lis.find("a").each(function(){e(this).data("normalized-text").indexOf("other")>-1&&(o=e(this))}),o.parent().removeClass("hide").show()})},val:function(e){return void 0!==e?(this.$element.val(e),this.render(),this.$element):this.$element.val()},selectAll:function(){this.findLis(),this.$lis.not(".divider").not(".disabled").not(".selected").filter(":visible").find("a").click()},deselectAll:function(){this.findLis(),this.$lis.not(".divider").not(".disabled").filter(".selected").filter(":visible").find("a").click()},keydown:function(t){var n,s,o,a,l,d,r,c,h,p=e(this),u=p.is("input")?p.parent().parent():p.parent(),f=u.data("this"),m={32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9"};if(f.options.liveSearch&&(u=p.parent().parent()),f.options.container&&(u=f.$menu),n=e("[role=menu] li a",u),!(h=f.$menu.parent().hasClass("open"))&&/([0-9]|[A-z])/.test(String.fromCharCode(t.keyCode))&&(f.options.container?f.$newElement.trigger("click"):(f.setSize(),f.$menu.parent().addClass("open"),h=!0),f.$searchbox.focus()),f.options.liveSearch&&(/(^9$|27)/.test(t.keyCode.toString(10))&&h&&0===f.$menu.find(".active").length&&(t.preventDefault(),f.$menu.parent().removeClass("open"),f.$button.focus()),n=e("[role=menu] li:not(.divider):not(.dropdown-header):visible",u),p.val()||/(38|40)/.test(t.keyCode.toString(10))||0===n.filter(".active").length&&(n=f.options.searchAccentInsensitive?f.$newElement.find("li").filter(":aicontains("+i(m[t.keyCode])+")"):f.$newElement.find("li").filter(":icontains("+m[t.keyCode]+")"))),n.length){if(/(38|40)/.test(t.keyCode.toString(10)))s=n.index(n.filter(":focus")),a=n.parent(":not(.disabled):visible").first().index(),l=n.parent(":not(.disabled):visible").last().index(),o=n.eq(s).parent().nextAll(":not(.disabled):visible").eq(0).index(),d=n.eq(s).parent().prevAll(":not(.disabled):visible").eq(0).index(),r=n.eq(o).parent().prevAll(":not(.disabled):visible").eq(0).index(),f.options.liveSearch&&(n.each(function(t){e(this).is(":not(.disabled)")&&e(this).data("index",t)}),s=n.index(n.filter(".active")),a=n.filter(":not(.disabled):visible").first().data("index"),l=n.filter(":not(.disabled):visible").last().data("index"),o=n.eq(s).nextAll(":not(.disabled):visible").eq(0).data("index"),d=n.eq(s).prevAll(":not(.disabled):visible").eq(0).data("index"),r=n.eq(o).prevAll(":not(.disabled):visible").eq(0).data("index")),c=p.data("prevIndex"),38==t.keyCode&&(f.options.liveSearch&&(s-=1),s!=r&&s>d&&(s=d),s<a&&(s=a),s==c&&(s=l)),40==t.keyCode&&(f.options.liveSearch&&(s+=1),-1==s&&(s=0),s!=r&&s<o&&(s=o),s>l&&(s=l),s==c&&(s=a)),p.data("prevIndex",s),f.options.liveSearch?(t.preventDefault(),p.is(".dropdown-toggle")||(n.removeClass("active"),n.eq(s).addClass("active").find("a").focus(),p.focus())):n.eq(s).focus();else if(!p.is("input")){var v,b=[];n.each(function(){e(this).parent().is(":not(.disabled)")&&e.trim(e(this).text().toLowerCase()).substring(0,1)==m[t.keyCode]&&b.push(e(this).parent().index())}),v=e(document).data("keycount"),v++,e(document).data("keycount",v),e.trim(e(":focus").text().toLowerCase()).substring(0,1)!=m[t.keyCode]?(v=1,e(document).data("keycount",v)):v>=b.length&&(e(document).data("keycount",0),v>b.length&&(v=1)),n.eq(b[v-1]).focus()}(/(13|32)/.test(t.keyCode.toString(10))||/(^9$)/.test(t.keyCode.toString(10))&&f.options.selectOnTab)&&h&&(/(32)/.test(t.keyCode.toString(10))||t.preventDefault(),f.options.liveSearch?/(32)/.test(t.keyCode.toString(10))||(f.$menu.find(".active a").click(),p.focus()):e(":focus").click(),e(document).data("keycount",0)),(/(^9$|27)/.test(t.keyCode.toString(10))&&h&&(f.multiple||f.options.liveSearch)||/(27)/.test(t.keyCode.toString(10))&&!h)&&(f.$menu.parent().removeClass("open"),f.$button.focus())}},mobile:function(){this.$element.addClass("mobile-device").appendTo(this.$newElement),this.options.container&&this.$menu.hide()},refresh:function(){this.$lis=null,this.reloadLi(),this.render(),this.setWidth(),this.setStyle(),this.checkDisabled(),this.liHeight()},update:function(){this.reloadLi(),this.setWidth(),this.setStyle(),this.checkDisabled(),this.liHeight()},hide:function(){this.$newElement.hide()},show:function(){this.$newElement.show()},remove:function(){this.$newElement.remove(),this.$element.remove()}};var a=e.fn.selectpicker;e.fn.selectpicker=o,e.fn.selectpicker.Constructor=s,e.fn.selectpicker.noConflict=function(){return e.fn.selectpicker=a,this},e(document).data("keycount",0).on("keydown",".bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bs-searchbox input",s.prototype.keydown).on("focusin.modal",".bootstrap-select [data-toggle=dropdown], .bootstrap-select [role=menu], .bs-searchbox input",function(e){e.stopPropagation()}),e(window).on("load.bs.select.data-api",function(){e(".selectpicker").each(function(){var t=e(this);o.call(t,t.data())})})}(jQuery);

$('.selectpicker').selectpicker({
     noneResultsText: 'I found no results'
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>

<select class="selectpicker" data-live-search="true" >
    <option value="other">other</option>
    <option>Alabama</option>
    <option>Alaska </option>
    <option>Arizona </option>
</select>


text:
Q: Filtering a list by a property matching a property in another list The assignment is pretty easy. Given a list of invoices and a list of accounts, I need to filter the former only keeping those with an active account related to them. An example of what it should behave like follows.

Invoices: {"a", 1}, {"b", 2}, {"c", 3}, {"d", 4}
  Accounts: {"a", 100}, {"c", 101}
  Results: {"a", 1}, {"c", 3}

I resolved it using Contains but it failed on the EF not being able to execute such an complex query (there are other conditions as well and it's also possible that the EF isn't set up properly). Then I tried to fetch all the data and do the filtration on the client but it failed on exception overflow and was painstakingly slow.
After a night of balancing code quality versus performance by trial and horror, fighting weird exceptions I don't understand (yes, google gave a lot but nothing that made me more wise) and can't do anything about (pre-existing configuration to be accepted as-in), I've arrived at the following code.
List<Guid> guids = datas.Select(data => data.Id).ToList();
List<Invoice> invoices = context.Invoices
  .Where(invoice => condition_00)
  ...
  .Where(invoice => condition_99).ToList();
invoices = invoices.Where(invoice => guids.Any(guid => invoice.Id == guid)).ToList();

Frankly, I'm not satisfied with the steps and I feel that the right way is to perform the whole operation in a single whack. Supposing that we're not allowed to discuss the issues of how EF is set up and how the DB behaves, can anything be improved to work faster in the following request? Preferably, I want the DB to process it all by the magic of LINQ.

A: What about using JOIN?
           List<List<object>> Invoices = new List<List<object>>() {
               new List<object>(){"a", 1},
               new List<object>(){"b", 2},
               new List<object>(){"c", 3},
               new List<object>(){"d", 4}
            };

            List<List<object>> Accounts = new List<List<object>>() {
               new List<object>(){"a", 100},
               new List<object>(){"c", 101}
            };

            var results = (from invoices in Invoices
                          join accounts in Accounts on invoices[0] equals accounts[0]
                          select new { name = invoices[0], id = invoices[1], total = accounts[1] })
                          .ToList();


text:
Q: Can a class inherit from an "argument" class? (Conditional inheriting) I am using python 3.6 and would like to build a subclass from different possible classes.
So a toy example would be:
class MNISTArchitecture:
    def __init__(self, inputs):
        self.input_pl = inputs
        self.learning_rate = LEARNING_RATE
        self.batch_size = BATCH_SIZE
        self.encoder
        self.decoder

class CIFARArchitecture:
    def __init__(self, inputs):
        self.input_pl = inputs
        self.learning_rate = LEARNING_RATE
        self.batch_size = BATCH_SIZE
        self.encoder
        self.decoder

And then build a class that could inherit from first architecture or the second one:
class AutoEncoder(Architecture):
    def __init__(self, input_pl, dataset):
        super().__init__(input_pl)
        self.dataset = dataset
        self.anomalous_label = anomalous_label
        self.build_graph()

I guess I could do multi-class inheritance and build the second class from all different classes (architectures), but I don't want python to build a huge graph (because I have more than 2 architectures).
Hope it is clear, please tell me if any other information is needed.
Best

A: It sounds like you want composition instead of inheritance.  Is an AutoCoder an Architecture?  It will work better to make an AutoCoder have an Architecture.  Then you can choose how to combine them together.
I don't know your problem domain well enough to make a specific recommendation, but:
class MNISTArchitecture:
    # your code...

class CIFARArchitecture:
    # your code...

class AutoEncoder:
    def __init__(self):
        if condition:
            self.arch = MNISTArchitecture()
        else:
            self.arch = CIFARArchitecture()


text:
Q: When an activity has a transparent theme, what state is the activity under it in? SO Link here specifies how we get an activity with a transparent background. I'm not clear on what state the activity under it is in. Is it paused because a transparent activity is maybe like a modal dialog? Or is it stopped? Will it ever disappear if the activity get killed? Will I always see this background?
As an additional question, Can I pass touch events to this activity below? So that I can allow my user to interact with the activity below.

A: The foreground activity is still in the same state as any normal activity. The only difference is that the activity's window background is transparent. The background activity will be paused since it is still visible to the user in the background.


text:
Q: Server-Side javascript framework I'm looking to replace PHP with something better (everybody seems to say that PHP is evil, right ?), and considering server-side JavaScript.
node.js seems very popular, but I'm afraid I'll go crazy with asynhronous stuff. Is it possible to write normal (synchronous) code under node ?
My whishlist: web and command-line scripting, good performance (on the
The Computer Language
Benchmarks Game  , V8 seems to be an order of magnitude faster than PHP), preferably developed by some company or community so that it will not be just abandoned someday, user community with a decent modules library.
I don't consider various frameworks based on Rhino, as Rhino runs in Java, and I'm not into Java, aware of it's memory footprint, and the whole idea of compiling javascript to java makes no sense to me.
Spent some time googling, and found numerous projects: Myna, Meteor, GromJS, APE, GLUEscript, v8cgi, silkjs, wakanda, GPSEE, sorrowjs, ejscript, Persevere, PhantomJS.
Does somebody have any experience with those ? Any recommendation are welcome.

A: Well Node.JS is the way to go if you ask me. You can write synchronous code, BUT only do that in command line scripts. When writing a web servers you have to go the async route otherwise it will not perform because JavaScript is single threaded and everything comes to a halt.
The reason Node.js is so fast is because of asynchronous IO.
You will get used to callbacks and eventing and after a while you don't want to go back.

Node.js is a platform built on Chrome's JavaScript runtime for easily
  building fast, scalable network applications. Node.js uses an
  event-driven, non-blocking I/O model that makes it lightweight and
  efficient, perfect for data-intensive real-time applications that run
  across distributed devices.

A: Meteor. Built on top of Node.js and growing very fast.

In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node. We find the linear execution model a better fit for the typical server code in a Meteor application.

UPDATE One year later - Why Meteor

A: Have you looked at Comparison of server side JavaScript solutions ?
Node.js is popular. As for php speed, have you looked at HipHop? Rewriting your code in javascript probably won't give much of a performance boost over php.

A: Nodejs is very good option on many fronts.
But you say you are concerned about its a async nature.
Two points on this.

*

*you never need to worry about async and can continue to write you application from top bottom like PHP. That's if you are not performing "blocking IO".

*If you are performing "blocking IO" like reading a database or accessing the file-system than you will need to deal with async. Luckly there are good ways to do this without the need to change you coding practices too much.

A: Thanks for providing the list of "numerous projects" you found. We are currently using Microsoft ASP 3.0 ("Classic ASP", coming with IIS) that provides a server-side JavaScript implementation since 1996 - it's fast, mature and due to the COM technology quite extensible. If you are not fixed to open source, it's worth a look. For our open source strategy, we will have a closer look at SilkJS.


text:
Q: How do I assign an INI section to a record in delphi 7 I'm sorry I'm not being clear...lets try again
I have a record type :
MyRecord = Record
   Name: string;
   Age: integer;
   Height: integer;
   several more fields....

and an INI file with:
[PEOPLE]
Name=Maxine
Age=30
maybe one or two other key/value pairs

All I want to do is load the record with the data from the INI file.
I have the data from the INI in a TStringList I want to be able to loop through the TStringList and assign/update only the Record Fields with key value pairs in the TStringList.
Charles

A: So you have an INI file with the content
[PEOPLE]
Name=Maxine
Age=30

and want to load it into a record defined by
type
  TMyRecord = record
    Name: string;
    Age: integer;
  end;

? That is very easy. Just add IniFiles to the uses clause of your unit, and then do
var
  MyRecord: TMyRecord;

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TIniFile.Create(FileName) do
    try
      MyRecord.Name := ReadString('PEOPLE', 'Name', '');
      MyRecord.Age := ReadInteger('PEOPLE', 'Age', 0);
    finally
      Free;
    end;
end;

Of course, the MyRecord variable need not be a global variable. It can also be a local variable or a field in a class. But that all depends on your exact situation, naturally.
A Simple Generalisation
A slightly more interesting situation is if your INI files contains several people, like
[PERSON1]
Name=Andreas
Age=23

[PERSON2]
Name=David
Age=40

[PERSON3]
Name=Marjan
Age=49

...

and you want to load it into an array of TMyRecord records, then you can do
var
  Records: array of TMyRecord;

procedure TForm4.FormCreate(Sender: TObject);
var
  Sections: TStringList;
  i: TIniFile;
begin
  with TIniFile.Create(FileName) do
    try
      Sections := TStringList.Create;
      try
        ReadSections(Sections);
        SetLength(Records, Sections.Count);
        for i := 0 to Sections.Count - 1 do
        begin
          Records[i].Name := ReadString(Sections[i], 'Name', '');
          Records[i].Age := ReadInteger(Sections[i], 'Age', 0);
        end;
      finally
        Sections.Free;
      end;

    finally
      Free;
    end;
end;

A: If you have the INI section in a string list you can just use the Values[] property:
String list contents
Name=Maxine
Age=30

Code to read into record
MyRecord.Name := StringList.Values['Name']
MyRecord.Age = StrToInt(StringList.Values['Age'])

Naturally you would want to handle errors one way or another, but this the the basic idea.


text:
Q: Dynamic Imports for JavaScript React Meteor I've got a lot of code that looks like the following:
import {Meteor} from 'meteor/meteor'; import {createContainer} from 'meteor/react-meteor-data';

import FoodItemList from '../components/FoodItemList.jsx';

import {FoodItems} from '../../api/FoodItems/FoodItems.js';

const FoodItemListContainer = createContainer(({imageIDFilter}) => {
    const user = Meteor.user()
        ? Meteor.user().username
        : '';
    const query = {
        username: {
            $not: {
                $eq: user
            }
        }
    };
    const foodItems = Meteor.subscribe('foodItems');
    const foodItemList = FoodItems.find(query).fetch()
    const loading = !foodItems.ready();

    return {loading, foodItemList, imageIDFilter, user};

}, FoodItemList);

export default FoodItemListContainer

Obviously when I refactor I want to remove some of this boiler plate but I'm not sure how I can do this because I don't see how I can dynamically import the files I need. Is this possible in JS React Meteor?

A: I just wrote an article about how to do this and, more importantly, when and why to do this.
https://code.zeroasterisk.com/2017/05/meteor-1-5-bundle-optimization/
TL;DR: import('./my_component') returns a promise, which resolves when the client has it.
before: normal import part of clientside bundle
import PickDates from './PickDates';

after: dynamic import no longer a part of clientside bundle
import Loader from 'react-loader';

// generic loading component to show while transfering section of code
const LoadingComponent = () => ;
// new version of the component, now: loading --> rendered
const PickDates = Loader({
  // this does the dynamic import, and returns a promise
  loader: () => import('./PickDates'),
  // this is our generic loading display (optional)
  LoadingComponent,
  // this is a delay before we decide to show our LoadingComponent (optional)
  delay: 200,
});

A: It is possible to do dynamic imports with Meteor as mentioned here using require, but noticed that it is not recommended to do so because it may cause bugs in your app.
I have done this kind of import a few times and my code still work fine. But I do not recommend you to do it, only if you really need it, it may worth trying


text:
Q: Error using array in Activity I 'm building an Android app that fetches an XML-feed, parses it in different Objects(name, url, description) and saves those Objects to an Array.
All this happens in an FeedActivity, extending the Activity class.
Loading the xml and parsing to objects works fine, but each time I want to add an object to the Array, I'm getting an error on the
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord,Intent) line:2494

I've also tried using a Map, but this had the same error.


text:
Q: Formatting a Datetime in an Azure Analytics job I need to insert the timestamp as a column in a Azure Table with the format yyyy-MM-dd-HH-mm
In plain T-SQL I would do something like:
SELECT FORMAT( GETDATE(), 'yyyy-MM-dd-HH-mm' ) AS 'PK'

I thought the CONCAT and DATENAME/DATEPART functions would help me, and I ended up with this, but it is not producing the output I need:
CONCAT(DATENAME(yyyy,System.Timestamp),'-',CAST(DATEPART(mm,System.Timestamp) AS NVARCHAR(MAX)),'-',DATENAME(dd,System.Timestamp),'-',CAST(DATEPART(hh,System.Timestamp)  AS NVARCHAR(MAX)),'-',DATENAME(mi,System.Timestamp))

2015-10-12T05:17:37.807Z is formatted like 2015-10-12-5-17 and I am expecting 2015-10-12-17-17
Thanks in advance

A: I not sure I understand the question. datepart(hh,'2015-10-12T05:17:37.807Z') = 5 is the right behavior, it is hour Five. Why do you expect 17?
datepart(hh) returns hour in 24 hour format. Below query demonstrates the 24 hour format behavior
select
    DATENAME(hh,'2015-10-12T05:17:37.807Z') HourFive,
    DATENAME(hh,'2015-10-12T17:17:37.807Z') HourSeventeen
from
foo

Output
5   17
You can do something like below to always get two digits. At the moment functions that make these kind of operations easier are not there.
with T1 as
(
select
    datepart(hh,'2015-10-12T05:17:37.807Z') [Hour]
from
foo
)

select
  case when [Hour] <10 then concat('0',cast([Hour] as nvarchar(max))) else cast([Hour] as nvarchar(max)) end [Hour]
from
  T1


text:
Q: Laravel Ajax dropdown example can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
    <option selected value=" ">Choose...</option>
    @foreach($nations as $nations)
    <option value="{{@$nation_id}}"  {{@$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{@$nations->nation}}</option>
@endforeach

Controller:
$nations = nation::all();

A: <select class="form-control" name="nation_id" id="nation_id">
          <option value="">Select nation</option>
           @foreach($nations as $nation)
            <option value="{{ $nation->nation_id }}">{{ $nation->nation_name }}  </option>
          @endforeach
</select>

<select class="form-control" name="teacher" id="teacher">
</select>

now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
    var nid = $(this).val();
    if(nid){
        $.ajax({
           type:"get",
           url:"{{url('/getTeacher)}}/"+nid,
           success:function(res)
           {
                if(res)
                {
                    $("#teacher").empty();
                    $("#state").append('<option>Select Teacher</option>');
                    $.each(res,function(key,value){
                        $("#teacher").append('<option value="'+key+'">'+value+'</option>');
                    });
                }
           }

        });
        }
});
</script>

now in controller file;
public function getTeacher($id)
{
    $states = DB::table("teachers")
                ->where("nation_id",$id)
                ->pluck("teacher_name","teacher_id");
    return response()->json($teachers);
}

And last for route file:
Route::get('/getTeacher/{id}','TeachersController@getTeacher');

Hope this will work..
Good Luck...

A: Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController@method');

Create a method in your controller for the above route-
public function method()
{
    $nations = Nation::all()->pluck('nation', 'id');

    return response()->json($nations)
}

Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>

If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">

And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
    $.get('nations-list', function(data) {
        let teacher_nation_id = $('#teacher_nation_id').val();
        let nations = $('#nation_id');
        nations.empty();

        $.each(data, function(key, value) {
            nations.append("<option value='"+ key +"'>" + value + "</option>");
        });

        nations.val(teacher_nation_id); // This will select the default value
    });
});
</script>


text:
Q: Stop ExpandableListView groups expanding while Contextual Action Bar is visible I have a fragment which contains an ExpandableListView. I would like to be able to select and delete items by group. I would also like to be able to select multiple group items for deletion, via a contextual action bar.
So far, I can click on groups to view children, and I can click on children to go to another Activity. I set the choice mode of the ExpandableListView to be CHOICE_MODE_MULTIPLE_MODAL, and it If I long click on a group, it is selected, a contextual action bar appears. If I select my delete button, the item is deleted. All good.
However, the problem arises when I attempt to select multiple groups in the CAB mode. It just doesn't work. If I click a second group, that group is expanded (not selected). I want to be able to just highlight multiple group items without any expansion occurring.
There's quite a lot of code to get this working, but I'll try to show some pertinent bits. The main issue is getting a list of selected group items. Secondarily, I don't want the groups to be expanded as they're selected (whilst the CAB is visible - this is what I am attempting by holding onto the ActionMode in mActionMode).
Any help is greatly appreciated.
ex.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
        @Override
        public void onItemCheckedStateChanged(ActionMode actionMode, int position, long id, boolean checked) {
            // Ignore long clicks on children
            long pos = ex.getExpandableListPosition(position);
            if (checked && (ExpandableListView.getPackedPositionType(pos) == ExpandableListView.PACKED_POSITION_TYPE_CHILD)) {
                ex.setItemChecked(position, false);
                return;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            MenuInflater inflater = actionMode.getMenuInflater();
            inflater.inflate(R.menu.context_delete_items, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            mActionMode = actionMode;
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {
            // If delete is clicked, delete the measurement set
            switch(item.getItemId()) {
                case(R.id.context_menu_delete_item):
                    Set<mySet> setsToDelete = new HashSet<mySet>();

                    if (ex != null) {
                        if (ex.getCheckedItemCount() > 0) {
                            SparseBooleanArray checkedPositions = ex.getCheckedItemPositions();
                            for (int i = 0; i < checkedPositions.size(); i++) {
                                int position = checkedPositions.keyAt(i);

                                /* Ignore selected children */
                                long pos = ex.getExpandableListPosition(position);
                                int groupPosition = ExpandableListView.getPackedPositionGroup(pos);

                                if (checkedPositions.valueAt(i)) {
                                    Log.d(TAG, "Adding MeasurementSet at position Key = " + position + " to deletion list");
                                    setsToDelete.add(mSets.get(groupPosition));
                                }

                            }
                        }
                    }

                    try {
                        if (ex != null && setsToDelete.size() > 0) {

                            ArrayList setsToDeleteList = new ArrayList(setsToDelete);
                            deleteSets(setsToDeleteList);

                            for (mySet s : setsToDelete) {
                                mSets.remove(s);
                            }

                            Toast.makeText(getActivity(), "Set deleted successfully", Toast.LENGTH_LONG).show();

                        }
                    } catch (SQLiteException sqlex) {
                        Log.e(TAG, "Delete operation failed");
                        Log.e(TAG, "Error was: " + sqlex.getMessage());
                        Log.e(TAG, "Stack trace: " + sqlex.getStackTrace());
                        Toast.makeText(getActivity(), "There was an error whilst deleting Set(s): " + sqlex.getMessage(), Toast.LENGTH_LONG).show();
                    }

                    actionMode.finish();
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
            mActionMode = null;
        }
    });

    ex.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            Long mId = mSets.get(groupPosition).getMyList().get(childPosition).getId();
            Intent intent = new Intent(getActivity(), ViewSingleActivity.class);
            intent.putExtra(getResources().getString(R.string.EXTRA_MID_KEY), measurementId);
            startActivityForResult(intent, Constants.REQ_VIEW_M);
            return true;
        }
    });

// Here I was trying to intercept group clicks and force the clicked group to collapse. Although this doesn't seem to solve the issue of having the group "selected"
    ex.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (mActionMode != null) {
                Log.d(TAG, "mActionMode is not null. Setting View: " + parent.toString() + " to be selected");
                v.setSelected(true);
                Log.d(TAG, "Collapsing group " + groupPosition);
                parent.collapseGroup(groupPosition);
            }
            return false;
        }
    });
}

A: Though this is an old post, figured I'd post an answer if anyone stumbled along. The problem is that the ExpandableListView does not support ChoiceMode. While it sorta seems to work and you can sorta manually call into the ExpandableListView to set items checked...it will never fully work right. For a more in depth reason on why; refer to this and this SO answer.
The OP did not specify if they wrote their own custom adapter or not. So I'll address both approaches.
If you wish to write your own custom ExpandableListAdapter, I suggest using the PatchedExpandabeListAdapter.  You can read about it here. Basically it patches and improves upon some things...one of which is the ChoiceMode issue asked by the OP.
If you don't want to roll your own solution, there are two nice full fledged Rolodex adapters found here which implements the PatchedExpandabeListAdapter and most everything you need aside from the view generation.


text:
Q: Convert Mysql query in Postgresql query Is there an utility to convert mysql query in postgresql query ?

A: For DDL you can use mysqldump (see http://en.wikibooks.org/wiki/Converting_MySQL_to_PostgreSQL)
mysqldump --compatible=postgresql databasename > outputfile.sql

For DML I don't know of a tool that would automatically adjust queries from MySQL to PostgreSQL.

A: Go to  http://www.sqlines.com/online  select left side mysql in source past your mysql query and select right side select postgresql in target then click left side on convert button

A: See also the PostgreSQL-wiki.


text:
Q: Inserting already deflated files in a zip file I have been searching for this issue but I cannot find any response that I can use.
Is it possible (using java) to include new files that are already deflated in a zip file in a way that, after, when I decompress the zip file, those deflated files are inflated in the same way as if they were passed "inflated" to the zip tool and incorporated to the zip as to be compressed ("DEFLETED" in the ZipEntry according to https://docs.oracle.com/javase/8/docs/api/java/util/zip/ZipOutputStream.html#setMethod-int-). In that case, how?
Most of the information about compression with java for zip files I get from google and others searchers can be resumed in:

*

*Opening the zip as a file system https://fahdshariff.blogspot.com/2011/08/java-7-working-with-zip-files.html

*Using streams directly (https://www.java-examples.com/create-zip-file-using-zipoutputstream-example)

I deflect the files using JZlib (but you can do with whatever any other library. An example, http://www.avajava.com/tutorials/lessons/how-do-i-deflate-and-inflate-a-file.html)
As you can expect about what I said, when I try to insert the already deflated files, they are deflated again (using the DEFLETED method in the ZipEntry, that is the default) and when the zip file is unzipped, the files are deflated to the their former already deflated state.
Looking to the source of ZipOutputStream.java from oracle, you can see that there are two methods for adding entries to the zip:
    DEFLATED (an integer set to 20)
    STORED   (an integer set to 10)

What I want is to add the deflated entries as STORED in the zip, but once they are added, to change the info in the own zip as if they were processed DEFLATED. Do you know any library or any alternative to do it easily? I was thinking in making my own ZipOutputStream inheriting from the jdk ZipOutputStream and overriding the methods to make the trick, but a "fast copy-paste and modification" of the methods according to this idea -just to have a "it could work" feeling- did not work according to my hopes either.
The reason why I would like to have this option is to compress huge amount of files in a zip file on demand dynamically. I am not sure if this could save time and cpu having the deflated files saved in the database and selecting in each moment those files that are requested to make the zips.
Thanks a lot,

A: The zip format is not terribly complicated, so you should just take the deflated data and write your own zip file headers around it. The format is documented here. If you are deriving the deflated data from gzip files, then you also should already have the CRCs and uncompressed lengths. (If each gzip file you want to convert consists of a single deflate stream, i.e. is one gzip member, and if the uncompressed lengths are assured to be less than 232 bytes, then you can delete the "should" in that statement.)

A: I could imagine a hack.... between putNextEntry(e) and write, you could possible use e.setMethod. The code like like it writes the header at the end of putNextEntry and decides about compression in write where it accesses the very entry it's been given in putNextEntry (no copy is made).
You may need to flip it back before calling closeEntry.
I didn't try it as you can try it much faster.

I am not sure if this could save time and cpu having the deflated files saved in the database

I'm not getting it, but I'm very skeptical.
OTOH your idea looks applicable also when given a bunch of *.gz files, you want to store their plaintext without decompressing and compressing them again.

A: Finally, I went further from my first approch, analyzed the jdk source deeper and spent some time debugging and modifying it:
https://gist.github.com/gylz/b2db94ce55f1829f2e2a2cd498092d46
https://gist.github.com/gylz/284d8b891fc0bbd3161d1ec5929be074
If you want to try it, you have to indicate the paths you want in the variables PATH_ZIP_DIR, PATH_IN_DIR, PATH_TMP_DIR in the Test class. The files to compress are taken from the PATH_IN_DIR directoy and the zip file created in PATH_ZIP_DIR. The test class is short and not too complicated (despite of being a draft as the ExtraZipOutputStream class too). I used simple text files in PATH_IN_DIR to test their compression. As you can see, in this class, the deflate() method is the one that performs the deflaton before compress() put the files in zip file (thanks to the modified ExtraZipOutputStream, using STORED but writing the metadata associated to the files as if they had been deflated by ExtraZipOutputStream itself.)
In the comment block appended to the header of ExtraZipOutputStream.class, I explain how to detect the changes I have made to the original code.

A: I know this is an outdated thread but looking in to my old folders for cleaning up the disk, I saw a "draft" project I made with this idea for my job. Finally, we discarded it but I have uploaded it to a repo if somebody could be interested in it...
https://gitlab.com/gylz.mail/dynazip
It is not even a prototype, just a short example program for showing how this would work. As Mark Alder said, the zip format is not complicated and it is well explained in the link he pointed out in his response.

A: I took a little look at ZipOutputStream & came up with this.
I've created 2 Classes: PreparedZipEntryBuilder & PreparedZipEntry.
This will create the shortest possibly ZipEntry for a given sequence of bytes.
In PreparedZipEntryBuilder I've included a number of Test Cases.
It's completely non-invasive, quite simple & commented throughout.
Have fun.
Here's PreparedZipEntry:
package com.stackoverflow.preparedzipentry;

import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class PreparedZipEntry {

    private final int    originalLength;
    private final long   originalCRC;
    private final int    deflatedLength;
    private final int    bestMethodDeterminedByBuilder;
    private final byte[] preparedEntryBytes;
    private final long   preparedEntryBytesCRC;

    /* package private */ PreparedZipEntry(final int originalLength, final long originalCRC, final int deflatedLength, final int method, final byte[] preparedEntryBytes) {

        final CRC32 preparedEntryBytesCRC32 = new CRC32();
        /**/        preparedEntryBytesCRC32.update(preparedEntryBytes);

        /*
         * These 6 Fields are all you need to correctly insert a prepared entry.
         * If desired, they can be written to a File for later use.
         * (in that case you might want to pass the original bytes to this constructor too?)
         */
        this.originalLength                = originalLength;
        this.originalCRC                   = originalCRC;
        this.deflatedLength                = deflatedLength;
        this.bestMethodDeterminedByBuilder = method;
        this.preparedEntryBytes            = preparedEntryBytes;
        this.preparedEntryBytesCRC         = preparedEntryBytesCRC32.getValue();
    }

    /**
     * Writes our PreparedZipEntry to the Outputstream.
     *

     * You may set the FileTimes in the returned ZipEntry.

     * LastModifiedTime will be used to create the Zip-Directory @ EOF
     *
     * @param   zos
     * @param   entryName
     * @return
     * @throws  IOException
     */
    public ZipEntry writeEntry(final ZipOutputStream zos, final String entryName) throws IOException {

        final ZipEntry entry = new ZipEntry(entryName);

        /*
         * Set the Sizes correctly for the Entry Header & write an Entry for the desired Method...
         */
        entry.setSize          (this.originalLength);
        entry.setCompressedSize(this.deflatedLength);
        entry.setCrc           (this.originalCRC);
        entry.setMethod        (this.bestMethodDeterminedByBuilder);  // Must use this Method (influences LOC-Header construction)
        zos.putNextEntry(entry);

        /*
         * Now set the byte-count to what write(...) is expecting for the prepared bytes and write them as STORED...
         */
        entry.setMethod(ZipEntry.STORED);
        entry.setSize  (this.preparedEntryBytes.length);
        zos.write      (this.preparedEntryBytes);

        /*
         * Now set the CRC to what closeEntry() is expecting for the bytes just STORED & close the Entry...
         */
        entry.setCrc   (this.preparedEntryBytesCRC);
        zos.closeEntry();

        /*
         * Finally, set the Sizes, CRC & Method correctly once more...
         * (ZipOutputStream will use these later to write the Zip-Directory @ EOF)
         */
        entry.setSize  (this.originalLength);
        entry.setCrc   (this.originalCRC);
        entry.setMethod(this.bestMethodDeterminedByBuilder);

        return entry;
    }
}

And here's the Builder:
package com.stackoverflow.preparedzipentry;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileTime;

import java.time.Instant;

import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class PreparedZipEntryBuilder {

    public static PreparedZipEntry of(final byte[] entryBytes) {

        final int    entryBytesLength    = entryBytes.length;
        final long   entryBytesCRC       = getCRC32(entryBytes);

        final byte[] deflatedBytes       = getDeflatedBytes(entryBytes);
        final int    deflatedBytesLength = deflatedBytes.length;

        /*
         * Depending on how well the bytes compress, generate an uncompressed or compressed PreparedZipEntry...
         */
        if (deflatedBytesLength < entryBytesLength) {
            /*
             * Compressed length was less than the uncompressed length
             */
            return new PreparedZipEntry(entryBytesLength, entryBytesCRC, deflatedBytesLength, ZipEntry.DEFLATED, deflatedBytes);
        } else {
            return new PreparedZipEntry(entryBytesLength, entryBytesCRC, entryBytesLength,    ZipEntry.STORED,   entryBytes);
            /*
             * Uncompressed was shorter!
             */
        }
    }

    private static byte[] getDeflatedBytes(final byte[] bytes) {

        try(final ByteArrayOutputStream baos = new ByteArrayOutputStream((int) (bytes.length * 0.4 /* Guess: 40% */));
            final          OutputStream bos  = new  BufferedOutputStream(baos);
            final  DeflaterOutputStream dos  = new  DeflaterOutputStream(bos, new Deflater(Deflater.BEST_COMPRESSION, true)))
        {
            dos.write(bytes, 0, bytes.length);
            dos.close();

            return baos.toByteArray();
        }
        catch (final           IOException cannotHappen) {
            throw new UncheckedIOException(cannotHappen);
        }
    }

    private static long getCRC32(final byte[] bytes) {

        final CRC32 crc32 = new CRC32();
        /**/        crc32.update(bytes);
        return      crc32.getValue();
    }

    private static ZipEntry writeRegularEntryUnknown(final ZipOutputStream zos, final String entryName, final byte[] entryBytes) throws IOException {

        final byte[] deflatedBytes       = getDeflatedBytes(entryBytes);

        final ZipEntry entry = new ZipEntry(entryName);
        /**/           entry.setLastModifiedTime(FileTime.from(Instant.now())); // For test: not absolutely necessary.

        entry.setSize          (entryBytes   .length);
        entry.setCompressedSize(deflatedBytes.length);
        entry.setCrc           (getCRC32(entryBytes));
        entry.setMethod        (ZipEntry.DEFLATED);

        zos.putNextEntry(entry);
        zos.write       (entryBytes, 0, entryBytes.length);
        zos.closeEntry();

        return entry;
    }

    private static ZipEntry writeRegularEntryKnown(final ZipOutputStream zos, final String entryName, final byte[] entryBytes) throws IOException {

        final ZipEntry entry = new ZipEntry(entryName);
        /**/           entry.setLastModifiedTime(FileTime.from(Instant.now())); // For test: not absolutely necessary.
        /**/           entry.setMethod        (ZipEntry.DEFLATED);

        zos.putNextEntry(entry);
        zos.write       (entryBytes, 0, entryBytes.length);
        zos.closeEntry();

        return entry;
    }

    public static void main(String[] args) throws IOException {

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final ZipOutputStream        zos = new ZipOutputStream(baos);
        /**/                         zos.setLevel(Deflater.BEST_COMPRESSION);

        final String string0s = ">00000000<";
        final String string09 = "0123456789";
        final String stringaz = "abcdefghijklmnopqrstuvwxyz";
        final String stringAZ = stringaz.toUpperCase();

        int z = 1000;

        for (final String entryText : new String[] {
                "Short",
                "Compresses poorly : "    + string09 + stringaz + stringAZ,
                "Compresses well : "      + string09 + string09 + string09 + string09 + string09 + string09,
                "Compresses very well : " + string0s + string0s + string0s + string0s + string0s + string0s,
                "-----------------------------------------------------------------------------------------", // <- Compresses extremely well
        }) {
            for (final String ab : new String[] {"a", "b"}) {

                final PreparedZipEntry prepared =  PreparedZipEntryBuilder.of(entryText.getBytes());
                /**/                   prepared.writeEntry     (zos, z++ + ab + "_Prepared");
                /**/                   writeRegularEntryKnown  (zos, z++ + ab + "_Regular_KnownLength",   entryText.getBytes());
                final ZipEntry  last = writeRegularEntryUnknown(zos, z++ + ab + "_Regular_unknownLength", entryText.getBytes());
                /**/            last.setLastModifiedTime(FileTime.from(Instant.now().minusSeconds(99 * z)));
            }
        }

        zos.close();

        final byte[] mainBytes = baos.toByteArray();

        final Path path = Paths.get("MultiMemberPredeflated.zip");

        Files.deleteIfExists(path);
        Files.write         (path, mainBytes, StandardOpenOption.CREATE);
    }
}


text:
Q: How to concat a number to another number when doing an insert I'm trying to concat a number to a max+1 number in an insert statement, but I'm a little stuck. My table goes like this:
CREATE TABLE `articles` (
    `artcId` INT(10) NOT NULL AUTO_INCREMENT,
    `artcUserId` INT(10) NOT NULL DEFAULT '0',
    `artcStackId` INT(10) NOT NULL DEFAULT '0',
    `artcPublicId` INT(10) ZEROFILL NOT NULL DEFAULT '0',
    `artcCountry` VARCHAR(2) NULL DEFAULT NULL,
    `artcTitle` VARCHAR(200) NULL DEFAULT NULL,
    PRIMARY KEY (`artcUserId`, `artcId`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM;

My current sql is like this:
insert into articles (artcUserId, artcStackId, artcCountry, artcTitle)
select 4,IFNULL((MAX(artcStackId)+1) ,0),'US','Hello World'
FROM articles;

What I'm tring to do is, concat a number to the new artcStackId and save it to the db. But i've got stuck. See the second image artcPublicId.
    insert into articles (artcUserId, artcStackId, artcCountry, artcTitle)
    select 2,IFNULL((MAX(artcStackId)+1) ,0),

    case when new.artcCountry = 'US' then conact(91, -- the new artcStackId goes here --)
         when new.artcCountry = 'UK' then conact(92, -- the new artcStackId goes here --)
         when new.artcCountry = 'CA' then conact(93, -- the new artcStackId goes here --)
    end

,'UK','Hello World'
FROM articles;
select * from articles;

Any idea how this can be done? artcPublicId is 91 or 92  or 93 depending on the country and the new artcStackId

A: *

*you may be better off making artcPublicId a varchar, which makes this easier to concat

*if you know the number of digits places you would like to leave after 91/92/93 you could try something like
(91 * 10000 + artcStackId)

*you can convert to instring and back again, something like
cast('910000' + cast(artcStackId as varchar), int(10))
Hope one of those helps