text:
Q: Kendo UI Treelist rows disappears after editing I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = @Html.Raw(@ViewBag.XmlData); //jsonarray data

    $( document ).ready(function() {
    });

    function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
    {
        var divMessage = $('#toggler');
        if(divMessage.css('display') != 'none')
        {
            divMessage.clearQueue();
            divMessage.stop();
            divMessage.css('display','none');
        }

        if (timeout == 0)
            divMessage.text(message).toggle('slow');
        else
            divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');

    }

    var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
        transport: {
            read: function(e) {
                e.success(parsedXmlDataInJson);
            },
            update: function(e) {
                var updatedItem = e.data;

                $.each(parsedXmlDataInJson, function(indx, value) {
                    if (value.id == updatedItem.Id) {
                        value = updatedItem;
                        return false;
                    }
                });
                e.success();
            },
            create: function(e) {//Works for root element when editing only once - it's broke my treelist.
                 e.data.Id = GetId();
                 parsedXmlDataInJson.push(e.data);
                 e.success(e.data);
            },
            destroy: function(e) {
                var updatedItem = e.data;

                $.each(parsedXmlDataInJson, function(indx, value) {
                    if (value.id == updatedItem.Id) {
                        parsedXmlDataInJson.splice(indx, 1);
                    }
                });
                e.success();
            },
            parameterMap: function(options, operation) {
                if (operation !== "read" && options.models) {
                    return {
                        models: kendo.stringify(options.models)
                    };
                }
            }
        },
        batch: false,
        schema: {
            model: {
                id: "Id",
                parentId: "parentId",
                fields: {
                    Id: {
                        type: "number",
                        editable: true,
                        nullable: false
                    },
                    parentId: {
                        field: "parentId",
                        nullable: true
                    }
                }
            }
        }
    });

    $("#treeList").kendoTreeList({
        resizable: true,
        dataSource: treelistds,
        toolbar: ["create"],
        columns: [{
            field: "typeAndAttributes",
            width:400
        }, {
            field: "text",
            title: "Текст",
        }, {
            field: "cData",
            title: "CDATA",
        }, { //my custom command
            command: ["edit", "destroy", "createchild", {
                name: "commentOut",
                text: "commentOut",
                click: function(e) {
                    var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command

                    dataItem.commentedOut = !dataItem.commentedOut;
                    var isCommentedOut = dataItem.commentedOut;

                    var childNotes = this.dataSource.childNodes(dataItem);
                    childNotes.forEach(function(childModel, i) //
                    {
                        childModel.commentedOut = isCommentedOut;
                        SetChildrenIsCommentedOut(childModel, isCommentedOut);
                    })

                    //обновляем цвет и текст кнопок у всех элементов вызывая dataBound
                    $("#treeList").data("kendoTreeList").refresh();
                },
            }, ]
        }],
        messages: {
            commands: {
                edit: "Изменить",
                destroy: "Удалить",
                createchild: "Добавить"
            }
        },
        dataBound: function(e) {
            this.autoFitColumn(3);
            Databound(e.sender, e.sender.table.find("tr"));
        },
        editable: true,
        editable: {
            mode: "popup",
            template: kendo.template($("#popup-editor").html()),
            window: {
                width:800
            }
        },
        edit: function(e) { //invokes when popup open
            $("#date").kendoDateTimePicker({
            });

            $("#cDataEditor").kendoEditor({
                tools: [
                    "formatting", "bold", "italic", "underline", "insertUnorderedList",
                    "insertOrderedList", "indent", "outdent", "createLink", "unlink"
                ],
                resizable: {
                    content: true,
                    toolbar: true,
                    max:350
                }
            });
           //my custom logic. Popup contains many fileds splitted from one model field
            if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
                var fileds = e.model.typeAndAttributes.split(';').
                filter(function(v) {
                    return v !== ''
                });

                e.container.find("#type").val(fileds[0]);

                var length = fileds.length;
                for (i = 1; i < length; i++) {
                    var keyAndValue = fileds[i].split('=');

                    if (keyAndValue[0] != "id")
                        e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
                    else
                        e.container.find("#xmlId").val(keyAndValue[1].trim());
                }
            }

        },
        save: function(e) { //invokes when saving
            var splitter = "; ";
            var inputValue = $("input[id='type']").val().trim();

            if (e.model.type !== undefined) {
                e.model.typeAndAttributes = e.model.type;
            } else {
                e.model.typeAndAttributes = inputValue;
            }

            var allInputs = $(":input[data-appointment=attributes]");
            allInputs.each(function(index, input) { //collect inputs in one filed
                var attrName;
                var attrValue;
                if (input.id != "id") {
                    attrName = input.id;
                    e.model[attrName];
                } else {
                    attrName = "id";
                    attrValue = e.model["xmlId"];
                }
                //значение изменили и оно не пустое
                if (attrValue !== undefined && attrValue !== "") {
                    if (attrValue == false)
                        return true;

                    e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
                }
                    //my custom logic
                else if (input.value.trim() && input.value != "on") {
                    e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
                }
            })
        }
    });

    //рекурсивно помечаем ряды как закомментированные или нет
    function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
        var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
        childNotes.forEach(function(childModel, i) {
            childModel.commentedOut = isCommentedOut;
            SetChildrenIsCommentedOut(childModel, isCommentedOut);
        })
    }

    //Раскрашивает строки соответственно значению закомментировано или нет
    function Databound(sender, rows) {
        rows.each(function(idx, row) {
            var dataItem = sender.dataItem(row);

            if (dataItem.commentedOut) {
                //обозначаем ряд как закомментированный
                $(row).css("background", "#DCFFE0");
                $(row).find("[data-command='commentout']").html("Раскомментировать");
            } else {
                //обозначаем ряд как незакомментированный
                $(row).css("background", "");
                $(row).find("[data-command='commentout']").html("Закомментировать");
            }
        })
    }

    });

    var currentId = 0;

    function GetId() { //генерирование Id для новых записей
        var dataSource = $("#treeList").data("kendoTreeList").dataSource;

        do {
            currentId++;
            var dataItem = dataSource.get(currentId);
        } while (dataItem !== undefined)

        return currentId;
    }


text:
Q: Why does a variable in the interface not show up in the class implementation? Why does the variable listed in the interface not show up in the class when I click implement methods? I look and I did not see the answer that I was really looking for, or would the variable be more like a property?
Class:
public class TestInterface implements myInterable {

    public TestInterface() {
    }

    public static void main(String[] args) {

    }

    @Override
    public void method1() {

    }

    @Override
    public void method2() {

    }
}

interface myInterable {
    public int score = 0;
    public void method1();
    public abstract void method2();
}

Tried this code but it would not work. It is almost exactly like the example on the listed Oracle tutorial.
Example:
interface TimeClient {
    void setTime(int hour, int minute, int second);
    void setDate(int day, int month, int year);
    void setDateAndTime(int day, int month, int year, int hour, int minute, int second);
    void getLocalDateTime();

    public static String getZoneId (String zoneString) { <-- Tutorial example
        return "";
    }

    public default int getZonedDateTime(String zoneString) { <-- like the tutorial
        return 0;
    }
}

Another Example:
Oracle states that you can not create an instance of an interface but if your class implements and interface than you can create a instance of the interface by create a new reference to the class? Is this how you would look at this. Is this a better way of creating an instance of a class by using an interface and putting all of you method stubs in the interface and then if you add in a new interface method than you do not have to rewrite all of your code because of one or two new methods.
If this is correct and I want to add a new method to my say application I would not have to go through and recompile every class to add in one new method if my variable uses this type of instance creation.
public class TestInterface implements myInterable,
                                      Runnable,
                                      MouseListener {
     //Code goes here
}

public myInterable uu = new TestInterface(); <--This is the interface class

Example that does not work.
Should this work if I create an instance of the interface with the class variable name.
public class TestInterface implements myInterable,
                                      Runnable,
                                      MouseListener {

    public  myInterable uu = new TestInterface();

    public TestInterface() {
    }

    public void method1() {
    }

    public void method2() {
    }

    public void run() {
        System.out.println("Runnable");
    }

    @Override
    public void mouseClicked(MouseEvent arg0) {
    }

    @Override
    public void mouseEntered(MouseEvent arg0) {
    }

    @Override
    public void mouseExited(MouseEvent arg0) {
    }

    @Override
    public void mousePressed(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent arg0) {
        // TODO Auto-generated method stub
    }

    public static void main(String[] args) {
        TestInterface b = new TestInterface();
        b.run();
        b.uu.run();
    }
}

interface myInterable {
    public int score = 0;
    public void method1();
    public abstract void method2();
    public abstract void run();
//     void method3() {
//      int index = 0;
//       for (index = 0; index < 10; index++) {
//       }
//  }
}

Error Message:
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)
at DDHIntefaceExample.TestInterface.<init>(TestInterface.java:10)

A: The JLS states

Every field declaration in the body of an interface is implicitly
  public, static, and final. It is permitted to redundantly specify any
  or all of these modifiers for such fields.

Therefore, the field score in your example is not inherited since it is static.

A: You can only define constants or static variables in interfaces, not instance variables.  if you want to define an instance variable, why not use an abstract class and provide getters and setters and make the instance variable private?

A: Just to nitpick, your myInterable should be MyInterable, following the typical Java capitalisation conventions.
All methods in an interface are inherently public abstract (and you cannot define static methods). Java 8 may change this though.
All variables in an interface are inherently public static final.
For much more details, see Java Tutorial trail on interfaces
So your
interface MyInterable {
    public int score = 0;
    public void method1();
    public abstract void method2();
}

Is the same as
interface MyInterable {
    public static final int score = 0;
    public void method1();
    public void method2();
}

And is also the same as
interface MyInterable {
    int score = 0;
    void method1();
    void method2();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display only one reading on text file from while loop I would like to know on how to write only a single data in the text file as the program is currently looping from the while loop, resulting in duplicate data in my text file. For instance, I only want one reading to be shown in the text file instead of the duplicate text in my text file
Alarm.txt
2021-03-19 15:12:43 TD02: Estop status: 1, Battery Alarm deactivated //How to display this reading one time

2021-03-19 15:12:49 TD02: Estop status: 0, Battery Alarm activated //How to display this reading one time

2021-03-19 15:12:55 TD02: Estop status: 1, Battery Alarm deactivated

//Afterwards, Loop every six seconds

Desire output
2021-03-19 15:12:43 TD02: Estop status: 1, Battery Alarm deactivated //How to display this reading one time

2021-03-19 15:12:49 TD02: Estop status: 0, Battery Alarm activated //How to display this reading one time

Edit:
My Code for the following
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <nav_msgs/Odometry.h>
#include <sstream>
#include <std_msgs/UInt16.h>
#include <std_msgs/Float32.h>
#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <string>
#include <iostream>
#include <fstream>
#include <time.h>
#include <cstdio>

const std::string currentDateTime() {
    time_t now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);

    strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct);

    return buf;

}
ros::Rate loop_rate(main_freq_);
get_new_cmd = 1;
uart_setting();
printf("Start modbus!!\n");

while (ros::ok())
{

    if (get_new_cmd == 1)
    {

        estop_read();
           ros::Duration(0.03).sleep();
           get_new_cmd = 2;
    }

   else if (get_new_cmd == 2)
    {

       modbus_response();
    get_new_cmd = 3;
    }

    else if (get_new_cmd == 3)
    {

       if (/*agv_battery < battery ||*/ points == 0)
       {
                red_light_on();
                    std::ofstream logfile("/home/amros/aiv150321/src/AlarmLog_TD02", std::ofstream::app); //or std::ofstream::app to append
            logfile << currentDateTime() << " TD02: Estop status: 0, Battery Alarm activated" << std::endl;

        if (logfile.is_open())
            {
               logfile << "\n";
               logfile.close();
                    }
                    else printf("Unable to open file \n");

       }
        else
       {
            red_light_off();
        std::ofstream logfile("/home/amros/aiv150321/src/AlarmLog_TD02", std::ofstream::app); //or std::ofstream::app to append
        logfile << currentDateTime() << " TD02: Estop status: 1, Battery Alarm deactivated" << std::endl;

        if (logfile.is_open())
            {
               logfile << "\n";
               logfile.close();
                    }
                    else printf("Unable to open file \n");

           }

    get_new_cmd = 4;

    }

    else if (get_new_cmd == 4)
    {

            modbus_response();
            get_new_cmd = 1;
    }

ros::spinOnce();
        loop_rate.sleep();

    }

    close(fd);
    return 0;

}

I would be glad if someone can help me on this!Thank you!


text:
Q: creating 'I have puled data from server and created a list of thumbnails and some other data from twitch TV.
I need to create popup tab with video stream in it.
Therefore I have put thumbnail in anchor tag and called a popup() function onclick.  (I am planing to put parameters for playing video in that function.)
Also I have created function for that popup() but no matter where I place it I get an Error in console when I click on thumbnail.
ERROR: Uncaught ReferenceError: popup is not defined

This is the JS code:
$(document).ready(function(){
    $.getJSON( "https://api.twitch.tv/kraken/streams", function( data ) {
    var items = [];
    var videoHTML ='
';

    //Popup Tab with streaming video

    $.each(data.streams, function(i, video){
        videoHTML += '
';
        videoHTML += '';
        videoHTML += '
' + video.channel.display_name + '
';
        videoHTML += '';
        videoHTML += '';
        videoHTML += '
' + video.game + '

';
        videoHTML += '';
        videoHTML += '' + video.viewers + '';
        videoHTML += '
' + video.created_at + '
';
        videoHTML += '
';

        var d = new Date(video.created_at);
        //var dateClass = 'date' + i;                 console.log(dateClass);
        //$(dateClass).html = d.toDateString();

    //console.log(video._id);
    //console.log(data.streams[i].game);

    //console.log(data.streams[i]._links.self);
    //console.log(data.streams[i].preview.medium);
    });

videoHTML += '
';
$('#placeholder').html(videoHTML);

    }); //getJson

    //popup tab
    function popup(){
    alert('wow');
    }

}); //end ready

Can You please help me with this becasue I can not find an answer on the internet?
-How to get popup() function running?
-How to implement parameter into this function?
(Also, I have tried to write anchor in HTML and add function and then everything works fine but when I create HTML with JS then I have this problem.
Thank You in front!
Sincerely,
Denis

A: You defined the function popup inside $(document).ready(function()). So popup can only be used within it.
Move it outside the $(document).ready(function()) function like this
$(document).ready(function(){
    // code
})
function popup(){
    // code
}


text:
Q: How to start a python file from another python file I developed a python 3.6.6 console app that does some actions. Here is the structure I'm using in this app.py file:
#!/usr/bin/python3

import threading
import time

# My app content
if __name__ == '__main__':
    # all may code is in here

Now I need to call this same app in a parent app that does other actions. What do I put in the parent_app.py file:
#!/usr/bin/python3

#some imports...

#the call to the app.py, but how since app.py hasn't got functions in it???

Thanks for your help to this basic question... I'm new in Python as you can see ;-)

A: Having all your content inside the if statement would be a bad idea anyway, at the very least, put everything you have inside that into a function and have that function called from inside the if statement.
# My app content
def func():
    # all may code is now in here

if __name__ == '__main__':
    func()

Now you have a function you can import! But really you should start looking at splitting your code into multiple functions and code structure in general

A: Define a function called main or whatever u prefer in app.py
def main():
  ## TODO

if __name__ == '__main__':
  ## Encapsulate all your code inside this main function
  main()

In parent_app.py, you can import app.py and call the function main as follow:
import app
app.main()

A: parent_app.py
#-*- coding:utf-8 -*-

from script_to_load import app_function,call_method

#if you just wanted app_functions
app_function()
#if you wanted to be script get executed as it is going to execute on app.py run
call_method()

app.py
#-*- coding:utf-8 -*-

def app_method():
    #do somthing

def call_method():
    app_method()
    print("not with if __name__ == '__main__ '")
if __name__ == "__main__":
    app_method()
    print("with if __name__ == '__main__'")

as we know Every module in Python has a special attribute called name. The value of name  attribute is set to 'main'  when module run as main program. Otherwise, the value of name  is set to contain the name of the module.
I hope it will works for you

A: just use the import functionality and the name of the file
from app import *

Here the * signifies that all contents from the file is imported.
If you want to import only one function or class from the python file, consider doing
from app import function_name

or
from app import class_name

A: Perhaps you may also want to look into creating a class!
app.py:

class Example(parameters):
//insert code here

parent.py:
from app import Example
//use (instantiate) the class

A: There are three ways of doing this -

*

*You can import the file in the parent file.
import app

*Using the exec function.
exec('app.py')

*Making use of os.system(filename)
import os
os.system('app.py')


text:
Q: How to calculate separable convolutions in the Xception paper? I read the Xception paper (there's even a Keras Model for the describe NN) and it talks about separable convolutions.
I was trying to understand how exactly they are calculated. Rather than leaving it to imprecise words, I have included the piece of pseudo-code below that summarizes my understanding. The code maps from a feature map 18x18x728 to a 18x18x1024 one :
XSIZE = 18;
YSIZE = 18;
ZSIZE = 728;
ZSIXE2 = 1024;

float mapin[XSIZE][YSIZE][ZSIZE];  // Input map
float imap[XSIZE][YSIZE][ZSIZE2];  // Intermediate map
float mapout[XSIZE][YSIZE][ZSIZE2];  // Output map

float wz[ZSIZE][ZSIZE2]; // Weights for 1x1 convs
float wxy[3][3][ZSIZE2];  // Weights for 3x3 convs

// Apply 1x1 convs
for(y=0;y<YSIZE;y++)
  for(x=0;x<XSIZE;x++)
    for(o=0;o<ZSIZE2;o++){
      s=0.0;
      for(z=0;z<ZSIZE;z++)
        s+=mapin[x][y][z]*wz[z][o];
      imap[x][y][o]=s;
    }

// Apply 2D 3x3 convs
for(o=0;o<ZSIZE2;o++)
  for(y=0y<YSIZE;y++)
    for(x=0;x<XSIZE;x++){
      s=0.0;
      for(i=-1;i<2;i++)
        for(j=-1;j<2;j++)
          s+=imap[x+j][y+i][o]*wxy[j+1][i+1][o]; // This value is 0 if falls off the edge
      mapout[x][y][o]=s;
    }

Is this correct ? If not, can you suggest fixes similarly written in C or pseudo-C ?
Thank you very much in advance.

A: I found tf.nn.separable_conv2d in Tensorflow that does exactly this. So I built a very simple graph and, with the help of random numbers, I tried to get the code above to match the result. The correct code is :
XSIZE = 18;
YSIZE = 18;
ZSIZE = 728;
ZSIXE2 = 1024;

float mapin[XSIZE][YSIZE][ZSIZE];  // Input map
float imap[XSIZE][YSIZE][ZSIZE];  // Intermediate map
float mapout[XSIZE][YSIZE][ZSIZE2];  // Output map

float wxy[3][3][ZSIZE];  // Weights for 3x3 convs
float wz[ZSIZE][ZSIZE2]; // Weights for 1x1 convs

// Apply 2D 3x3 convs
for(o=0;o<ZSIZE;o++)
  for(y=0y<YSIZE;y++)
    for(x=0;x<XSIZE;x++){
      s=0.0;
      for(i=-1;i<2;i++)
        for(j=-1;j<2;j++)
          s+=mapin[x+j][y+i][o]*wxy[j+1][i+1][o]; // This value is 0 if falls off the edge
      imap[x][y][o]=s;
    }

// Apply 1x1 convs
for(y=0;y<YSIZE;y++)
  for(x=0;x<XSIZE;x++)
    for(o=0;o<ZSIZE2;o++){
      s=0.0;
      for(z=0;z<ZSIZE;z++)
        s+=imap[x][y][z]*wz[z][o];
      mapout[x][y][o]=s;
    }

The main difference is in the order that the two groups of convolutions are performed.
To my surprise, the order is important even when ZSIZE==ZSIZE2.


text:
Q: When a regular $F_{\sigma}$ set open?
A regular $F_{\sigma}$ set is a set $S \subset X$ such that S is a union of a sequence of open sets whose interiors contain $S$ i.e. $S=\cup_{1}^{\infty} F_n= \cup_{1}^{\infty} {F_n}^{\circ}$.

My question is when an open set is regular $F_{\sigma}$ set?
AS clearly every regular $F_{\sigma}$ set open, does the converse hold in all metrizable spaces or some other particular type of topological spaces? Also is there any relation between $F_{\sigma}$ set and regular $F_{\sigma}$ set?

A: Using the correct definition

A regular $F_{\sigma}$ set is a set $S \subset X$ such that S is a union of a sequence of closed sets $F_n$ whose interiors contain $S$ i.e. $S=\cup_{1}^{\infty} F_n= \cup_{1}^{\infty} {F_n}^{\circ}$.

Then it's obvious that a regular $F_\sigma$ set is in particular an $F_\sigma$ (as witnessed by $S=\bigcup_n F_n$) and open (because $S=\bigcup_n F_n^\circ$, a union of opens). Not all open $F_\sigma$ sets will be regular $F_\sigma$ in general but as noted in the comments, this is the case in any metrisable space $X$, using the sets $F_n = \{x \in O\mid d(x,O^\complement) \ge \frac1n\}$ for an open set $O$. Also in regular hereditarily Lindelöf spaces this will be the case.


text:
Q: how to List View items in two columns instead of one column in Flutter? my current implementation is retrieving items from database using Future Builder widget and then display it in a list view , what I'm trying to achieve is how I make the display of items in two column instead of one?
here is my code that preview items in a vertical single column  :
Widget build(BuildContext context) {
    return FutureBuilder<List<Product>>(
      future: fetchProducts(),
      builder: (context, snapshot) {
        if (!snapshot.hasData)
          return Center(child: CircularProgressIndicator());
        else {
          print (snapshot.data.length) ;
          return Container(
            child: Scrollbar(
              isAlwaysShown: true,
              controller: _scroll,
              child: ListView.builder(
                controller: _scroll,
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return WidgetProduct(snapshot.data[index]);
                },
              ),
            ),
          );
        }
      },
    );
  }

A: @pskink is right you can use GridView.builder()
@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ListView.separated(
      separatorBuilder: (context, int) {
        return Divider(color: Colors.black,);
      },
     // shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return GridView.count(
          shrinkWrap: true,
          crossAxisCount: 3,
          childAspectRatio: 2.0,
          children: List.generate(6, (index) {
            return Center(
              child: RaisedButton(
                onPressed: (){},
                color: Colors.greenAccent,
                child: Text(
                  'item no : $index',
                ),
              ),
            );
          }),
        );
      },
      itemCount: 4,
    ));
  }


text:
Q: Form Validation (If & then) I want to make a javascript to be shown if somebody chooses option A to show the javascripts for the A1 , A2 , A3 and if they choose B to show javascripts for the B1  , B2 , B3. So the A and B it will firstly asked as options from a select tag
For example:
<select name="AorB" >
<option value="" selected="selected">Select...</option>
<option value="A" >Option A</option>
<option value="B" >Option B</option>
</select>

I'm using this way of javascript (Error Alerts):

P.S: I don't want to make complications when they choose A to get B option javascripts or reverse.
added - explain: i mean if We select OPTION A there will be shown some Input-s ....and javascript will ask only for the shown input-s so it means OPTION A input-s ... but not to ask for OPTION B input-s too even that they're not shown cause we didnt select OPTION B ... i hope i explained a little for you.

A: You can easily check the current value of a select tag with:
alert(document.getElementById('AorB').value);

This will alert the current value of the select tag.
You can then check the value whenever the value changes with the onChange event:
<select id="AorB" onchange="alert(document.getElementById('AorB').value);">
<option value="" selected="selected">Select...</option>
<option value="A" >Option A</option>
<option value="B" >Option B</option>
</select>

Here is a jsFiffle example you can use.
You can then do some JavaScript dependent on what the value is, I will not write you the whole code though.
I hope this helps!

A: What I understand of your question is that you want a select box and this will determine what fields show up on the form. Then you want the validation script to only validate those fields that show up. This would best be handled with JQuery. Here is some working code to give an example, and a fiddle.
HTML

    <form id="myForm" name="myForm" method="POST" action="http://www.google.com">
        <select id="option" name="option">
            <option value="X">Choose One...</option>
            <option value="A">Option A</option>
            <option value="B">Option B</option>
        </select>

                Input A1: <input name="a1" id="a1" class="option-a" type="textfield" />

                Input A2: <input name="a2" id="a2" class="option-a" type="textfield" />

                Input A3: <input name="a3" id="a3" class="option-a" type="textfield" />

                Input B1: <input name="b1" id="b1" class="option-b" type="textfield" />

                Input B2: <input name="b2" id="b2" class="option-b" type="textfield" />

                Input B3: <input name="b3" id="b3" class="option-b" type="textfield" />

        <input type="submit" id="submit-button" name="submit" value="Submit" />
    </form>

JQuery
$('#optionset-a').hide();
$('#optionset-b').hide();
$('#submit-button').hide();

$('#option').change(function() {
    if ($('#option').val() == 'A') {
        $('#optionset-b').hide();
        $('#optionset-a').show();
        $('#submit-button').show();
    } else if ($('#option').val() == 'B') {
        $('#optionset-a').hide();
        $('#optionset-b').show();
        $('#submit-button').show();
    }
});

$('#submit-button').click(function() {
    var validation = true;
    if ($('#option').val() == 'A') {
        $('.option-a').each(function() {
            if ($(this).val() == '') {
                $(this).css('border','1px solid red');
                validation = false;
            }
        });
    }
    if ($('#option').val() == 'B') {
        $('.option-b').each(function() {
            if ($(this).val() == '') {
                $(this).css('border','1px solid red');
                validation = false;
            }
        });
    }
    if (validation) {
        document.forms["myForm"].submit();
    } else { alert('Please fill in all fields.'); }
});


text:
Q: I converted picture to GIF but turtle's bgpic() still not working Here is my code:
from tkinter import *
import turtle as t
import random
bob=Tk()
t.setup(width = 200,height = 200)
t.bgpic(picname="snakesandladders.gif")
def left(event):
    t.begin_fill()
    print("left")
    t.left(90)

def right(event):
    print("right")
    t.right(90)
def forward(event):
    print("forward")
    t.forward(100)

block = Frame(bob, width=300, height=250)
bob.bind("<a>", left)
bob.bind("<d>", right)
bob.bind("<w>", forward)
block.pack()
bob.mainloop()

And my error is:
Traceback (most recent call last):
  File "/Users/lolszva/Documents/test game.py", line 6, in <module>
    t.bgpic(picname="snakesandladders.gif")
  File "<string>", line 8, in bgpic
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 1481, in bgpic
    self._bgpics[picname] = self._image(picname)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 479, in _image
    return TK.PhotoImage(file=filename)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3545, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3501, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "snakesandladders.gif": no such file or directory

I am a beginner so I don't really know if I did not import a library. In another, similar question for bgpic() not working, it said to convert the picture to gif but for mine it still doesnt work. I'm using Mac OSX Python version 3.8.0.

A: Although your problem is a missing GIF file, your program will still fail even if the file exists, and is in the correct directory.
The secondary issue is that you invoke turtle standalone atop tkinter.  You can either run turtle standalone where it sets up the underlying tkinter root and window, or you can run turtle embedded in tkinter where you setup the root and a canvas for turtle to roam.  But invoking turtle standalone atop a tkinter root you created will fail with error:
...
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage2" doesn't exist

Here's how to implement your program in standalone turtle:
from turtle import Screen, Turtle

def left():
    turtle.left(90)

def right():
    turtle.right(90)

def forward():
    turtle.forward(100)

screen = Screen()
screen.setup(width=200, height=200)
screen.bgpic(picname="snakesandladders.gif")

screen.onkey(left, "a")
screen.onkey(right, 'd')
screen.onkey(forward, 'w')

turtle = Turtle()

screen.listen()
screen.mainloop()

Put your GIF background image in the same directory as the source code.
You only need embedded turtle if you want to add tkinter widgets alongside the turtle canvas.  See the documentation for RawTurtle and TurtleScreen.
Your window size is small compared to your forward() distance -- you may need to adjust one or the other.


text:
Q: Proof in Hamilton: Divergence theorem for differential forms? For a vector field $X\in\Gamma(TM)$ on a closed Riemannian manifold $(M,g)$ we have
\begin{align*}
\int_M\text{div}X\;\mu=0,
\end{align*}
where
\begin{align*}
\text{div}X=-g^{ij}g(\nabla_iX,\partial_j).
\end{align*}
Here $\mu$ is the volume form and $\nabla$ is the Levi-Civita connection of the metric $g$.
Question:  Is there an analogous statement for differential forms and even for general tensors?
In other words if $\omega\in\Gamma(T^*M)$ is a $1$-form does it hold that
\begin{align*}
\int_M\text{div}\,\omega\;\mu=0\,?
\end{align*}
Here
\begin{align*}
\text{div}\,\omega=-g^{ij}\nabla_i\omega_j.
\end{align*}
We can easily define the divergence for higher-order tensors, so does the 'divergence theorem' also hold here as well?
EDIT:  The motivation for this question is as follows.  Let $M$ be as above and
\begin{align*}
\dot{R}_{jk}=D\text{Rc}(g)h_{jk}=\frac{1}{2}g^{pq}(\nabla_q\nabla_jh_{pk}+\nabla_q\nabla_kh_{pj}-\nabla_q\nabla_ph_{jk}-\nabla_j\nabla_kh_{pq})
\end{align*}
be the linearisation of the Ricci tensor at $g$ in the direction of the symmetric tensor $h$.  Then there is a statement in a paper by Hamilton that
\begin{align*}
\int_M\text{tr}_g\dot R_{jk}\,\mu=\int_Mg^{jk}\dot R_{jk}\,\mu=0.
\end{align*}
I calculate that
\begin{align*}
\text{tr}_g\dot R_{jk}=g^{jk}\dot R_{jk}&=g^{jk}\frac{1}{2}g^{pq}(\nabla_q\nabla_jh_{pk}+\nabla_q\nabla_kh_{pj}-\nabla_q\nabla_ph_{jk}-\nabla_j\nabla_kh_{pq})\\
&=g^{jk}g^{pq}\nabla_q\nabla_jh_{pk}-g^{jk}g^{pq}\nabla_q\nabla_ph_{jk}\\
&=\text{div}(\text{div}\,h)-\Delta\text{tr}_gh.
\end{align*}
The divergence $(\text{div}\,h)_p=g^{jk}\nabla_jh_{pk}$ of the symmetric tensor $h$ is a $1$-form.
QUESTION:  The integral of the connection Laplacian is zero but how is the integral of the other term zero?  Or am I doing something silly and wrong...?

A: On a Riemannian manifold, the divergence theorem applies to $1$-forms as well as to vector fields. The simplest way to see this is by using the "musical isomorphisms" between $1$-forms and vector fields. This are the inverse isomorphisms $\flat\colon TM\to T^*M$ and $\sharp\colon T^*M\to TM$ defined by raising and lowering indices. If $X$ is a vector field and $\omega$ is a $1$-form,
$$
(X^\flat)_i = g_{ij}X^j, \qquad
(\omega^\sharp)^j = g^{jk}\omega_i.
$$
Then the divergence of $\omega$ is simply defined to be $\operatorname{div}\omega := \operatorname{div}(\omega^\sharp)$. In components, $\operatorname{div}\omega = g^{jk}\nabla_j\omega_k$.
The divergence theorem for $1$-forms then follows directly from the one for vector fields:
$$
\int_M \operatorname{div}\omega\, \mu =
\int_M \operatorname{div}(\omega^\sharp)\, \mu =
0.
$$

A: There is no Stokes's Theorem for general tensors. The general result is that $\displaystyle\int_M d\omega = 0$ for any compact oriented $n$-dimensional manifold $M$ without boundary and $(n-1)$-form $\omega$ on $M$. The divergence theorem you cite is for the case of $\omega = \star\eta$ where $\eta$ is the $1$-form corresponding to $X$ under the isomorphism $T^*M\cong TM$ induced by the Riemannian metric.

A: Addition to Jack Lee's answer:  Since $\nabla_i\omega^\sharp=(\nabla_i\omega)^\sharp$ (the covariant derivative respects the musical isomorphisms) and we also calculate that
\begin{align*}
\text{div}\,\omega&:=\text{div}\,\omega^\sharp\\
&=-g^{ij}g(\nabla_i\omega^\sharp,\partial_j)\\
&=-g^{ij}((\nabla_i\omega)^\sharp)^\flat_j\\
&=-g^{ij}\nabla_i\omega_j.
\end{align*}


text:
Q: Adding the cardinals of not disjoint sets ( without inclusion of one set in the other) : does cardinal arithmetics offer a formula? This question has been suggested to me by this post :
How to prove that $|P(A)| + |P(B)| = 16$?

Suppose A and B are disjoint.
If I want to add the cardinal of P(A) and of P(B) , I cannot use this formula
                      #X + #Y = # ( X U Y )

for here my two sets are not disjoint ( two powersets always having at least one element in common).
Here I know that the sets P(A) and P(B) only have one element in common ( since A and B are disjoint).
Is there a formula of cardinal arithmetics that applies here?

A: For any sets $X$ and $Y$,  $|X\cup Y| = |X| + |Y| - |X\cap Y|$.
That is, you count up all the elements assuming they're all different, then you subtract the elements they have in common so that you don't double-count.
In particular, the power sets $P(A)$ and $P(B)$ of disjoint sets have one element in common—the empty set. So, count up the number of elements in each power set assuming they have nothing in common, then subtract the one element $(\varnothing)$ they have in common:
$$| P(A) \cup P(B)| = |P(A)| + |P(B)| - 1 = 2^{|A|} + 2^{|B|}-1$$


text:
Q: CSS - How to create a rounded gradient border with gradient background I have a card that has a gradient as a background and border-radius, i wanna add a gradient border that respects that border radius. Things i've tried:

*

*border-image --> It didn't implement border-radius

*background-clip set to border-box and padding-box --> It only works when the card has a background of solid color

.selector {
  width: 31rem;
  height: 35rem;
  border-radius: 2.1875rem;
  border: 0.88px solid transparent;

/* Method One */
  border-image:  linear-gradient(
        -28.96deg,
        #fb37ff 0%,
        rgba(155, 111, 238, 0) 25.98%,
        rgba(123, 127, 234, 0) 60.91%,
        #1bb2de 100%
      ) 20;

/* Method Two */
  background: var(--gradient-2) padding-box,
    linear-gradient(
        -28.96deg,
        #fb37ff 0%,
        rgba(155, 111, 238, 0) 25.98%,
        rgba(123, 127, 234, 0) 60.91%,
        #1bb2de 100%
      )
      border-box;

}


text:
Q: Linux daemon to change user input stream? I'd like to write a program to remap user input for stuff like changing keyboard layouts, but also more complex things like making a shorthand program (i.e. "t qk fx jmps ovr t lzy dg" outputs as "the quick fox jumps over the lazy dog").  I'd prefer to do this at the X level or below.
Can I make some kind of virtual keyboard based on actual user output?  Ideally I'd like some kind of simple interface (i.e. standard input to the program is a series of real user input events, output is the user input events for the virtual keyboard), but if that's not possible I'd still be interested in pointers to how this can be done.  I don't know anything about Linux hardware devices, low-level X stuff, or the kernel right now; in fact I'm fairly new to Linux.  Links to "Basics" tutorials would not be unappreciated.

A: You can use the Linux event subsystem to do this:

*

*Use the Linux input event interface (evdev) to receive events from any input device. See also the input.h header file for more information on the actual API.

*Use the EVIOCGRAB ioctl to grab the keyboard device, so that no other userspace applications but your daemon will receive any input events.

*Use the uinput interface to create a new virtual keyboard with any features that you need. See also the uinput.h header file for more information on the uinput API and this for a readable walkthrough.
There are a few applications that could serve as an example, such as  EvRouter, ESE Key Daemon and my own evmapd.


text:
Q: Delete Larger data by IDs Greendao database android I want to delete some lakes of entries in Greendao database.
Problem: Because of the bad coding, table is filled with lots of duplicate entries. Now challenge is to clean only the duplicate data.
Some of the users are having 10L of data in that only 2L data is valid, rest of the data is duplicate.
Currenly, I am fetching all the data and then taken the list of duplicate entry id(It is in some lakes). Using Set parameter method in a for loop I am deleting the entries.
for (int i=0; i<data.size(); i++) {
  query.setParameter(0,data.get(i));
  query.executeDeleteWithoutDetachingEntities();
}

Most of the users having around 4-8L of duplicate data.
This is working fine but takes several minutes to complete the process. Is there any better solution to do this?


text:
Q: Font size that toggles 3 different sizes and remembers user preference

$('.toggle').click(function() {
  $('div').each(function() {
    var classes = ['font1', 'font2', 'font3'];
    this.className = classes[($.inArray(this.className, classes) + 1) % classes.length];
  });
});
div {
  color: black;
  font-size: 12px;
}

.font1 {
  font-size: 12px;
}

.font2 {
  font-size: 14px;
}

.font3 {
  font-size: 16px;
}

Toggle sizes

This is a sample text.

i'd like it to cycle through three different sizes and then remember what the user prefers when they refresh/leave the page because no one likes reselecting every refresh.


text:
Q: Composition of $\mathcal B(\mathbb R)$-$\mathcal B(\mathbb R)$ and $\mathcal E$-$\mathcal B(\mathbb R)$-measurable functions. I've proven $$h(x) = \left\{\begin{array}{ll}
1/x & : x \neq 0\\
0 & : x = 0
\end{array}
\right.$$
is $\mathcal B(\mathbb R)$-$\mathcal B(\mathbb R)$-measurable.
I'm then asked to prove that if $(X, \mathcal E)$ is a measurable space and $f,g$ are $\mathcal E$-$\mathcal B(\mathbb R)$-measurable functions, $g(x) \neq 0$ $\forall \ x \in X$, then $f/g$ is $\mathcal E$-$\mathcal B(\mathbb R)$-measurable.
A hint is given I should use $h$.
I have a theorem saying that if $h$ is $\mathcal B(\mathbb R)$-$\mathcal B(\mathbb R)$-measurable and $g$ is $\mathcal E$-$\mathcal B(\mathbb R)$-measurable then $h(g(x)$ is $\mathcal E$-$\mathcal B(\mathbb R)$-measurable.
But how can this be true ? If I set $g(x) =0$ then $g$ is $\mathcal E$-$\mathcal B(\mathbb R)$-measurable, but $h(g(x))$ is not defined ??


text:
Q: How do i get the position of a text drawn with a function after I've used the same function for different texts? def drawText(text, x, y, colour):

   font = pygame.font.SysFont('Arial', 30)
   textSurface = font.render(text, True, colour)
   textRect = textSurface.get_rect()
   textRect.center = (x, y)
   screen.blit(textSurface, textRect)

drawText("YES", 120, 300, GREEN)

Later in the code, I want to get the position of the text "YES". How do get this value after I've used the same function to display other texts? I'm very new to python and pygame.

A: You can save the coordinates into variables
def drawText(text, x, y, colour):

   font = pygame.font.SysFont('Arial', 30)
   textSurface = font.render(text, True, colour)
   textRect = textSurface.get_rect()
   textRect.center = (x, y)
   screen.blit(textSurface, textRect)

textLocation = [120, 300]
drawText("YES", textLocation[0], textLocation[1] , GREEN)

# Later on you need the coordinated of the text
# you can acces the location with textLocation[0] and textLocation[1]
print(f"Text is located at ({textLocation[0]}, {textLocation[1]})")

If later you start having a lot of texts, you might want to use a dictionary for example
textLocations = {
    "YES": {"x": 120, "y": 300},
    "NO": {"x": 200, "y": 100}
}

And access the location as
textLocations["YES"]["x"]

Take in account though, that keys are unique, so your key might need to be an id instead of just the text.


text:
Q: PersistenceUnitPostProcessor Implementation not working during junit test I have implemented a PersistenceUnitPostProcessor for scanning the entities in different packages and not listing them in the persistence.xml.
Sadly, it is only working during deployment but not when running junit tests.
The Processor is declared in the context application xml as follow:
<bean id="entityManagerFactoryMdm"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitPostProcessors">
        <list>
            <bean class="com.mypackage.MyPersistenceUnitPostProcessor" />
        </list>
    </property>
</bean>

The packages are listed as:
<util:properties id="entitiesScanProperties">
    <prop key="packagesToScan">package1.entities,package2.entities.view,package3.entities</prop>
</util:properties>

The logic:
public class MyPersistenceUnitPostProcessor implements PersistenceUnitPostProcessor {

    @Autowired
    private ResourcePatternResolver resourceLoader;

    @Value("#{entitiesScanProperties['packagesToScan']}")
    private String[] packagesToScan;

    @Override
    public void postProcessPersistenceUnitInfo(final MutablePersistenceUnitInfo mutablePersistenceUnitInfo) {
        try {
            List<Resource> resourcesList = new ArrayList<Resource>();
            for (String packageToScan : packagesToScan) {
                packageToScan = packageToScan.replace(".", "/");
                final Resource[] packageResources = resourceLoader.getResources(String.format("classpath:%s/*.class", packageToScan));
                resourcesList.addAll(Arrays.asList(packageResources));
            }
            final Resource[] resources = new Resource[resourcesList.size()];
            resourcesList.toArray(resources);

            for (Resource resource : resources) {
                final CachingMetadataReaderFactory cachingMetadataReaderFactory = new CachingMetadataReaderFactory();
                final MetadataReader metadataReader = cachingMetadataReaderFactory.getMetadataReader(resource);
                if (metadataReader.getAnnotationMetadata().isAnnotated(javax.persistence.Entity.class.getName())) {
                    mutablePersistenceUnitInfo.addManagedClassName(metadataReader.getClassMetadata().getClassName());
                }
            }
            mutablePersistenceUnitInfo.setExcludeUnlistedClasses(true);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
      }
    }

The Test definition:
@ContextConfiguration(locations = { "classpath:application-context-test.xml" })
@DatabaseDataAsResource(locations = { "/META-INF/testdata/dbunit/master-dataset.xml", "/META-INF/testdata/dbunit/complaints-dataset.xml" })
public class FuelComplaintServiceImplIntegrationTest extends TestBase {
}

The super class:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class, TestExecutionLifecycleListener.class })
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public abstract class TestBase {

}

I'm getting this exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private     com.company.repository.DataProviderRepository com.company.service.impl.ProviderConfigurationServiceImpl.dataProviderRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataProviderRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Not an managed type: class package1.entities.DataProviderEntity
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 43 more

What can be the issue, that the Processor works during deplyoment but not druing unit testing? Am I overseeing something?
Any hint is very welcome.

A: For those who may meet such a Problem.
The reason for the error was this expression:
"classpath:%s/*.class"

Changing it to:
"classpath*:%s/*.class"

resolved the error.
The problem was, that the first expression will just look in the first path found. Some classes needed won't be there like in this case the Entities causing the such error messages.
The second expression will tell the ResourcePatternResolver to look in all classes directories matching the path pattern e.g.
../classes/package1/Entity.class

../test-classes/package1/ServiceTest.class

In my case, it was looking before only to:
../test-classes/package1/ServiceTest.class

Hope this helps someone.


text:
Q: Channeling IPv4 packets to IPv6 packets between interfaces How do I route packets in my machine between interfaces (See yellow arrow). Eth0 receives IPv4 packets and I will like to channel it to Eth1 which will send IPv6 packets out.Image of dual stack machine with IPv4 and IPv6 interfaces

A: Routing cannot convert between IPv4 and IPv6. You need an application layer gateway for that.

A: IPv4 and IPv6 are different protocols, and cannot be directly routed between.
Move everything to IPv6 and you can have a single stack all the way through, which can be directly routed.
Or, tunnel IPv4 in IPv6. Maybe GRE, or some other VPN.
Or, insert a middlebox in between, terminating the IPv4 connection and starting an IPv6 one. Some kind of proxy or load balancer, for example.


text:
Q: Postgresql "Cluster is not running" after running for a while I set up a postgresql db on azure VM, Ubuntu server 18.04.
but it goes down after running for a while without any other error message.
Here is what I got from sudo systemctl status postgresql@10-main.service
Feb 18 08:08:52 server crontab[17689]: (postgres) LIST (postgres)
Feb 18 08:08:52 server crontab[17692]: (postgres) LIST (postgres)
Feb 18 08:08:52 server crontab[17695]: (postgres) LIST (postgres)
Feb 18 08:08:52 server crontab[17697]: (postgres) REPLACE (postgres)
Feb 18 08:08:52 server crontab[17698]: (postgres) LIST (postgres)
Feb 18 08:08:52 server crontab[17700]: (postgres) REPLACE (postgres)
Feb 18 08:08:52 server crontab[17701]: (postgres) LIST (postgres)
Feb 18 08:08:53 server postgresql@10-main[17704]: Cluster is not running.
Feb 18 08:08:53 server systemd[1]: postgresql@10-main.service: Control process exited, code=exited status=2
Feb 18 08:08:53 server systemd[1]: postgresql@10-main.service: Failed with result 'exit-code'.

sudo systemctl restart postgresql.service may temporarily resolve this problem, but may reoccur after a while.
Does anyone face the same issue?
Any advice?
Thank you.

A: In my case, postgresql was killed by the oom killer.


text:
Q: Wordpress: Osetin Meal Planer, Adding %author% in custom post type URL structure? I'm trying to do some WordPress URL rewriting ...
Specifically I have custom post type that currently works like this:
mydomain.com/videos/post-title/

But I would like to have it located at:
mydomain.com/videos/author-name/post-title/

Is there any way to achieve this?
NOTE: I'm using OSETIN MEAL PLANER plugin in my site. Using that plugin for publishing recipe/post on website.

A: using Jhon's Custom Post Permalinks plugin it should be easy using:
/%post_type%/%author%/%postname%/
also you can try this
add_filter( 'your-post-type_post_type_args', '_my_rewrite_slug' ); // Here replace "your-post-type" with the actual post type, e.g., "cherry_services", "cherry-projects"
function _my_rewrite_slug( $args ) {
$args['rewrite']['slug'] = '/videos/author-name'; // Replace "our-/videos/author-name" with your preferable slug
return $args;
}


text:
Q: PHP mail() function and Lotus Notes client: HTML damaged First, sorry if my English is bad, I'm French.
I have some trouble with PHP mail() function and the Lotus Notes client: I try to send an HTML email to my professional address, this using Lotus Notes, but it seems that it does not recognize HTML at all. Instead, it shows me the code of my email with the Courier New font...
Here is my code, very simple:
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
$headers .= "From: Bidouille <bidouille@entreprise.fr>\r\n";
$headers .= "X-Mailer: PHP/".phpversion()."\r\n";

$mail = "
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sed mauris at justo pretium malesuada. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean faucibus nisl a malesuada pulvinar. Aliquam suscipit aliquam mauris, nec aliquet erat feugiat eu.
";

mail("monmail@entreprise.fr", "Test", $mail, $headers);

And here is the mail I get on Lotus Notes:

Content-Type: text/html; charset=utf-8
From: Bidouille
X-Mailer: PHP/5.2.9
Message-Id: <20140218141905.F03DA7009D@kpw36063.appheb.entreprise.fr>
  Date: Tue, 18 Feb 2014 15:19:05 +0100 (CET)
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sed mauris at justo pretium malesuada. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean faucibus nisl a malesuada pulvinar. Aliquam suscipit aliquam mauris, nec aliquet erat feugiat eu.

Do you have any idea about what happens?
Thanks for your answers.

A: Try using \n instead of \r\n for separating headers.
Here is the quote from php.net/mail:

If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

And a doubled CRLF means end of headers.


text:
Q: Edit Command Button with Kendo Grid I am calling in an edit command in mvc on kendo grid
columns.Command(command =>
{
     command.Edit();
     // command.Destroy().HtmlAttributes(new { @class = "onboard-delete " });
})

It renders a button and an icon.  How can I change the way this command looks.  I'd like it to just be an icon.

A: Please try with the beloe code snippet.
<style>
    .k-grid-edit .k-icon, .k-grid-update .k-icon, .k-grid-cancel .k-icon {
        margin: 0px !important;
    }

    .k-grid-edit {
        background-color: transparent !important;
        border: medium none !important;
        margin: 0 !important;
        min-width: 0 !important;
    }
</style>

@(Html.Kendo().Grid<MvcApplication1.Models.TestModel>()
  .Name("LightsGrid")
  .Columns(col =>
  {
      col.Bound(x => x.ID);
      col.Command(command =>
      {
          command.Edit()
             .Text(" ")
             .UpdateText(" ")
             .CancelText(" ");

      });

  })
  .ToolBar(toolbar => toolbar.Create())
  .Editable()
  .DataSource(dataSource => dataSource
      .Ajax()
      .Model(model => model.Id(x => x.ID))
      .Read(read => read.Action("GetData", "Home"))
      .Create(create => create.Action("CreateData", "Home"))
      .Update(update => update.Action("UpdateData", "Home"))
      .Destroy(destroy => destroy.Action("DestroyData", "Home"))
  )
)


text:
Q: OpenCL kernel START delays when using multiple GPUs? I have an application that I designed to run on AMD GPU's with OpenCL. Finally got the app running and bug free (haha) yesterday, targted on a single GPU. Now that the app works, it's time to scale it to multiple GPUs.
Read a lot about how to set it up. We're using the single context, multiple queue method.
I pull the list of devices, and choose 2 of the GPUs and create a context containing them, then a single BuildProgram containing both devices as well. Create two separate queues.
Pseudocode of the original, working app, now converted to handle 2 gpus:
context = clCreateContext(0, 2, device_list, NULL, NULL, &ret);
for(x = 0; x < 2; x++)
  queue[x] = clCreateCommandQueue(context, device_list[x], ENABLE_PROFILING, &ret);
clBuildProgram(program, 2, device_list, options, NULL, NULL);

create kernels..

run...
for(outer_loop = 0; outer_loop < 10; outer_loop++) {
  clEnqueueNDRangeKernel(queue[0], kernel_init, offset, &event[0]);
  clEnqueueNDRangeKernel(queue[1], kernel_init, different_offset, &event[1]);
  clFinish(queue[0]);
  clFinish(queue[1]);

  get profiling data and printf results
}

Thats basically how the code looks. Arguments are set and Writes are done BEFORE the loop - the init kernel does not rely on input to start working. After it runs, it DOES do a async_work_group_copy of it's generated data to a global buffer.
Now, before I modified the code for 2 GPUs, the kernel ran in 27ms (for each loop)
After I modified the code, if I comment out ONE or the OTHER of the 2 kernel runs (the EnqueueNDRangeKernel and the associated clFinish), they will both run in 27ms.
If I run the code to run on both GPUs in parallel, I get very odd behavior.
The first run in the loop, they both execute in about 37-42ms individually. I'm ok with a slight slowdown, as I'm getting twice the work done. But after the first run, one or the other kernel will randomly have a 4-5 SECOND delay between being queued, and starting.
Here's the output of my profiling/timing for it. All numbers are in ms.
Q0: til sub:  8.8542  til start: 9.8594 til fin: 47.3749
Q1: til sub:  0.0132  til start: 13.4089 til fin: 39.2364

Q0: til sub:  0.0072  til start: 0.2310 til fin: 37.1187
Q1: til sub:  0.0122  til start: 4152.4638 til fin: 4727.1146

Q0: til sub:  0.0302  til start: 488.6218 til fin: 5049.7233
Q1: til sub:  0.0179  til start: 5023.9310 til fin: 5049.7762

Q0: til sub:  0.0190  til start: 2.0987 til fin: 39.4356
Q1: til sub:  0.0164  til start: 3996.2654 til fin: 4571.5866

Q0: til sub:  0.0284  til start: 488.5751 til fin: 5046.3555
Q1: til sub:  0.0176  til start: 5020.5919 til fin: 5046.4382

The machine I'm running this on has 5 GPUs in it. Regardless of which two I use, one of the two GPUs (its not always the same one) gets a 4-5 second delay on starting. Use a single GPU - no delay.
What could be causing this? Any idea? I'm not blocking - the clFinish is only to get profiling info. Even if it were blocking it wouldn't be a 5 second delay.
Also - I thought maybe the writes to global that the kernel was doing might have been part of the delay. I commented the writes out. Nope. No change.
In fact, I added a return; as the first line of the kernel - so it does absolutely nothing. The 40ms dropped to .25, but the 5 second delay was still there.

A: The OpenCL driver does not care about what happens in the kernel. If the kernel writes/reads or is a null kernel, or if it only writes to one section of the buffer. It cares about the buffer parameter flags, and ensures the data is consistent across GPUs, blocking the kernels if they have ANY dependency in other kernels.
GPU to GPU transfer occurs transparently and can be very costly.
When using multiple GPUs the hidden data copy and synchronization has to be taken seriously, since that is usually the main bottleneck.
If your kernels can run in parallel (because GPU1 works on different data that the one on GPU2, and so on...), then you should create different buffers for each GPU. Or if the data is the same, set the types CL_READ_ONLY/CL_WRITE_ONLY properly, to ensure proper OpenCL behaviour. And minimum copy/consistency operations.

For example for these kernels:
kernel Sum(read_only A, read_only B, write_only C);
kernel Sum_bad(read_write A, read_write B, write_only C);

If you use a single GPU, both will behave exactly the same, because all the memory resides in the same GPU.
But using multiple GPUs can cause terrible problems, for example:
Queue 1/GPU 1: Sum_Bad(A,B,C);
Queue 2/GPU 2: Sum_Bad(A,D,E);

The events will occur as follow:

*

*Memory A,B will be copied to GPU1 memory (if it was not there already). C memory allocated in GPU1.

*GPU 1 will run kernel.

*Memory A will be copied from GPU1 to GPU2. Memory D will be copied to GPU2. Memory E allocated.

*GPU2 will run kernel.

As you see, the GPU2 has to wait for the first one to finish, and additionally wait for all the parameters to copy back. (Can that be 5s? maybe, depending on the sizes)

However using the correct approach:
Queue 1/GPU 1: Sum(A,B,C);
Queue 2/GPU 2: Sum(A,D,E);

The events will occur as follow:

*

*Memory A,B will be copied to GPU1 memory (if it was not there already). C memory allocated in GPU1.

*GPU 1 will run kernel.

In parallel (because there is no dependancy)

*

*Memory A,D will be copied to GPU2 (if it was not there already). Memory E allocated.

*GPU2 will run kernel.


text:
Q: JDBC performance when connection is stablished I want to reduce the time of part of project that currently takes 2 hrs.
How it has been coded is it goes and take out almost 700,000 UID from one table and pass it to 16 different threads. Each thread then connect to JDBC and fetch a row for a UID one by one. it runs 700,000 query! 50k for each thread
Because it uses 3 to 4 fields of each row my plan is to get the needed fields at first and don't connect to database anymore.
my concerns:

*

*because it fetch a row by UID ( I assume this should be fast) does it improve performance dramatically ?

*I need to worry about memory and cache misses and everything, putting 700,000 rows with couple of fields in memory scares me.

Overall do you think this will help to improve the performance or you think it doesn't matter that much. saving 5min  because of testing necessary it doesn't worth it.
So do you think I should pursue this path or focus more on logic???
Thanks a lot

A: As has been suggested in various comments, you should load the records in batches. I don't know how your infrastructure is configured, but if you are using a cloud service, a database round trip can take on the order of hundreds of milliseconds.
However, that may not be your only problem. If you haven't configured connection pooling, it may well be that you are gaining nothing from your multi-threading as each thread waits to grab the database connection. Your pool size should take into account how many connections may be established concurrently (in this case, it sounds like 17 may be your number - 1 for the main thread and 16 for the workers - if I understand your architecture correctly).


text:
Q: How to access the co-ordinates of an element as it's being dragged If I am using this function to make an element draggable using jQuery ui draggable:
$(document).ready(function() {
  $("#draggableSquare").draggable();
});

How can I access the co-ordinates of the element as it's moved around?

A: $( "#draggable" ).draggable({
    drag: function(event,ui) {
        //relative to container: ui.position.left and ui.position.top
        //ralative to page: ui.offset.left and ui.offset.top
    }
});

jsFiddle


text:
Q: iOS - scaling text vertically on Quartz I am writing some text to a quartz context.
I have a box of 500 x 200 pixels and I am writing some text inside. The box can have any aspect ratio but the text will always write with the font proportions as it is. What I want is to scale the font vertically and keep the horizontal scale.
See the picture. The first box represents what I am getting, the second one, what I want.

this is how I am writing it...
CGRect rect = CGRectMake(0,0,500,200);
[myText drawInRect:rect
        withFont:aFont
        lineBreakMode:UILineBreakModeTailTruncation
        alignment:UITextAlignmentCenter];

is there a way to scale the font vertically?

NOTE: as this is being written in a PDF context, I don't want to
  render the text to a image context and scale it vertically, because I
  don't want to lose resolution.

thanks

A:   - (void) scaleTextVerticallyWithContext:(CGContextRef)myContext withRect:(CGRect)contextRect
{
    CGFloat w, h;
    w = contextRect.size.width;
    h = contextRect.size.height;

    CGAffineTransform myTextTransform;
    CGContextSelectFont (myContext, "Helvetica-Bold", h/10, kCGEncodingMacRoman);
    CGContextSetCharacterSpacing (myContext, 10);
    CGContextSetTextDrawingMode (myContext, kCGTextFillStroke);

    CGContextSetRGBFillColor (myContext, 0, 1, 0, .5);
    CGContextSetRGBStrokeColor (myContext, 0, 0, 1, 1);

         /*
          *  CGAffineTransformMakeScale ( CGFloat sx, CGFloat sy );
          *  sx: The factor by which to scale the x-axis of the coordinate system.
          *  sy: The factor by which to scale the y-axis of the coordinate system.
          */

    myTextTransform = CGAffineTransformMakeScale(1,8);

    CGContextSetTextMatrix (myContext, myTextTransform);
    CGContextShowTextAtPoint (myContext, 40, 0, "Hello There", 9);
}

- (void)drawRect:(CGRect)rect{

    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect viewBounds = self.bounds;
    CGContextTranslateCTM(context, 0, viewBounds.size.height);
    CGContextScaleCTM(context, 1, -1);

    [self scaleTextVerticallyWithContext:context withRect:viewBounds];
}


text:
Q: Parsing xml file with SAX parser my handler class:
   package csc241hw06;

        import java.time.format.DateTimeFormatter;
        import java.util.ArrayList;
        import java.util.List;
        import java.time.LocalDateTime;
        import java.time.ZoneOffset;

        import org.xml.sax.Attributes;
        import org.xml.sax.SAXException;
        import org.xml.sax.helpers.DefaultHandler;

        /**
         * Created by Dan1 on 3/9/2017.
         */
public class MyHandler extends DefaultHandler {
    private Customer customer;
    private Account account;
    private Address address;
    private Meter meter;
    private MeterReading meterReading;
    private ArrayList <Customer> customerArrayList;
    private ArrayList <Address> addressList;

    String lastName;
    String firstName;
    String addressType;
    String accountNum;
    String accountType;

    public MyHandler() {
        customerArrayList = new ArrayList <Customer> ();
        addressList = new ArrayList <Address> ();
    }

    public ArrayList <Customer> getCustomerList() {
        return customerArrayList;
    }

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        if ( qName.equalsIgnoreCase ( "Customer" ) ) {
            lastName = attributes.getValue ( "lastName" );
            firstName = attributes.getValue ( "firstName" );

        } else if ( qName.equalsIgnoreCase ( "account" ) ) {
            accountType = attributes.getValue ( "type" );
            accountNum = attributes.getValue ( "accountNumber" );
            if ( accountType.equalsIgnoreCase ( "residential" ) ) {
                account = new ResidentialAccount ( accountNum, customer );
            } else {
                account = new CommercialAccount ( accountNum, customer );
            }
        } else if ( qName.equalsIgnoreCase ( "address" ) ) {
            String unit = attributes.getValue ( "unit" );
            String street = attributes.getValue ( "street" );
            String number = attributes.getValue ( "number" );
            String zipCode = attributes.getValue ( "zipCode" );
            int parseNum = Integer.parseInt ( number );

            if ( attributes.getValue ( "type" ).equals ( "mailing" ) ) {
                if ( attributes.getValue ( "unit" ) == null ) {

                    if ( accountType.equalsIgnoreCase ( "residential" ) ) {
                        address = new Residence ( parseNum, street, zipCode );
                    } else {
                        address = new Commercial ( parseNum, street, zipCode );

                    }

                } else {
                    address = new Apartment ( parseNum, street, zipCode, unit );
                }
                if ( customer == null ) {
                    customer = new Customer ( lastName, firstName, address );
                }

            } else if ( attributes.getValue ( "type" ).equalsIgnoreCase ( "apartment" ) ) {
                address = new Apartment ( parseNum, street, zipCode, unit );

            } else if ( attributes.getValue ( "type" ).equalsIgnoreCase ( "commercial" ) ) {
                address = new Commercial ( parseNum, street, zipCode );
            } else if ( attributes.getValue ( "type" ).equalsIgnoreCase ( "house" ) ) {
                address = new Residence ( parseNum, street, zipCode );
            }

        } else if ( qName.equalsIgnoreCase ( "meter" ) ) {
            String id = attributes.getValue ( "id" );
            String brand = attributes.getValue ( "brand" );
            String meterType = attributes.getValue ( "type" );
            String location = attributes.getValue ( "location" );

            if ( meterType.equalsIgnoreCase ( "push" ) ) {
                meter = new PushMeter ( id, brand );
            } else if ( meterType.equalsIgnoreCase ( "poll" ) ) {
                meter = new PollMeter ( id, brand );
            }
            meter.setLocation ( address, location );

        } else if ( qName.equalsIgnoreCase ( "meterReading" ) ) {
            String reading = attributes.getValue ( "reading" );

            String date = attributes.getValue ( "date" );
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyy-MM-dd'T'HH:mm" );
            LocalDateTime dateTime = LocalDateTime.parse ( date, formatter );

            String flag = attributes.getValue ( "flag" );

            meterReading = new MeterReading ( Double.parseDouble ( reading ), dateTime, flag, meter );
        }

    }

    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ( qName.equalsIgnoreCase ( "customer" ) ) {
            customerArrayList.add ( customer );
        } else if ( qName.equalsIgnoreCase ( "account" ) ) {
            customer.addAccount ( account );
            account.updateBalance ();
        } else if ( qName.equalsIgnoreCase ( "address" ) ) {

            addressList.add ( address );

            for (int i = 0; i < addressList.size (); i++) {
                account.addAddress ( addressList.get ( i ) );
            }

            addressList = new ArrayList <Address> ();

        } else if ( qName.equalsIgnoreCase ( "meter" ) ) {
            address.addMeter ( meter );
        } else if ( qName.equalsIgnoreCase ( "meterReading" ) ) {
            meter.addReading ( meterReading );
        }
    }

}

my xml file:

    <customer lastName ="Adams" firstName="Maurice">
        <address type="mailing" unit="308" street="W 4th St." number="56" zipCode="13126"/>
        <account type="residential" accountNumber="876-543-21">
            <address type="apartment" unit="308" street="W 4th St." number="56" zipCode="13126">

                <meter id = "RM-4877-X4" brand="GE" type="push" location = "East side of building">

                    <meterReading reading="650" date = "2016-12-31T00:31" flag="push"/>
                    <meterReading reading="675" date = "2017-01-01T00:37" flag="push"/>
                    <meterReading reading="622" date = "2017-01-02T00:38" flag="push"/>
                </meter>
            </address>
        </account>
    </customer>

    <customer lastName ="Costanza" firstName="George">
        <address type="mailing" street="E 5th St." number="65" zipCode="13126"/>
        <account type="commercial" accountNumber="765-432-10">
            <address type="commercial" street="Albany St." number="56" zipCode="13126">
                <meter id = "CM-7784-D1" brand="GE" type="poll" location = "North entrance">
                    <meterReading reading="5043" date = "2016-12-31T00:32" flag="poll"/>
                    <meterReading reading="6152" date = "2017-01-01T00:38" flag="poll"/>
                    <meterReading reading="7261" date = "2017-01-02T00:41" flag="poll"/>
                </meter>
            </address>
            <address type="commercial" street="Oneida St." number="72" zipCode="13126">
                <meter id = "CM-7684-D2" brand="GE" type="push" location = "South end of basement">
                    <meterReading reading="650" date = "2016-12-31T00:21" flag="push"/>
                    <meterReading reading="760" date = "2017-01-01T00:23" flag="push"/>
                    <meterReading reading="781" date = "2017-01-02T00:25" flag="push"/>
                    <meterReading reading="722" date = "2017-01-03T00:27" flag="push"/>
                </meter>
            </address>
        </account>
    </customer>
</xml>

the problem is that every time I try to add an address to my address list it returns an error in the endElement method. Yes this is a homework assignment, I have tried everything and don't have any idea who else to ask (my teacher isn't much help at the moment) any help would be very much appreciated, thank you


text:
Q: AutoCAD Lisp hook up help function to show Youtube video I'm having trouble hooking up the F1 help function in AutoCAD Lisp with a custom Youtube video instead of showing the default AutoCAD Help files. I've found this article to be quite helpful, but it won't allow me to supply a youtube video in any way.
The custom AutoCAD browser is too old and does not support HTML5 (which is needed to run Youtube videos). Any help on how to solve my issue?
Case: How to bind the F1 help to a custom function in AutoCAD Lisp, then activate a Youtube clip on F1 keypress.

A: After a while, I got it all figured out. I had to use a combination of HTML/Javascript to trigger the default web browser (which hopefully supports HTML5), and then view the Youtube clip there:
Lisp:
(setfunhelp "C:MyFunction" "C:\\path\\to\\html\\file\\MyFunc_Help.html")
(defun C:MyFunction ()
  (alert "this is my function")
)

HTML:
<html>
    <body>
    <script>
    function OpenInNewTab(url, callback) {
      var acWindow = window.open("", "_self");
      acWindow.document.write("");
      setTimeout (function() {acWindow.close();},500);

      var newWindow = window.open(url, '_blank');
      newWindow.focus();
    }
    OpenInNewTab("https://youtu.be/FERNTAh5s0I");
    </script>
    </body>
</html>

This HTML code opens a new browser window in your default browser, then closes the AutoCAD default browser after 500 milliseconds.
I hope this will be of help to someone.


text:
Q: What is the meaning of "testifies to"?
Within a mere two centuries we have become alienated individuals. Nothing testifies better to the awesome power of culture.

The last sentence doesn't make any sense to me

A: "Testify to" means "provide evidence for". You testify (give evidence) in a court of law. The author is commenting on the power of our technological culture to alienate us by driving us physically and emotionally apart. He seems to think that this trend started with the industrial revolution, two centuries ago.
Cambridge Dictionary: Testify


text:
Q: Cannot Instanciate ZkClient due to invalid ZKStringSerializer reference I am migrating a Play v 2.3.4 app to Play v 2.5.4. Along the way I had to also upgrade to Scala 2.11.8 and kafka 9.0+ to support the updated Play version.
Most of the issues I have worked out but I cannot figure out a Kafka issue with some code that manages Kafka topics though AdminUtils. The troubles are all centered around kafka.utils.ZkStringSerialzier.
I am using org.I0Itec.zkclient package to instances ZkClient object that is passed in the construction of ZkUtils object but it fails because it cannot resolve my ZkStringSerializer.
Related code is:
import kafka.admin.AdminUtils
import kafka.utils.ZkUtils
import kafka.utils.ZKStringSerializer
import org.I0Itec.zkclient.{ZkClient, ZkConnection}
object Topic {
    def CreateKafkaTopic(topic: String, zookeeperHosts: String, partitionSize: Int, replicationCount: Int, connectionTimeoutMs: Int = 10000, sessionTimeoutMs: Int = 10000): Boolean = {
        var zkSerializer: ZKStringSerializer = ZKStringSerializer
        val zkClient: ZkClient= new ZkClient(zookeeperHosts, connectionTimeoutMs, sessionTimeoutMs, zkSerializer)
        val topicConfig: Properties = new Properties()
        val isSecureKafkaCluster: Boolean = false

        val zkUtils: ZkUtils = new ZkUtils(zkClient, new ZkConnection(zookeeperHosts), isSecureKafkaCluster)

        AdminUtils.createTopic(zkUtils, topic, partitionSize, replicationCount, topicConfig)
        zkClient.close()
    }
}

The above code results in the error that ZKStringSerializer is inaccessible from his place.
I found several related post to creating topics (mostly in Java and before Kafka 9.0)
Creating a topic for Apache Kafka 0.9 Using Java
How create Kafka ZKStringSerializer in Java?
How Can we create a topic in Kafka from the IDE using API
And Finally
Creating a Kafka topic results in no leader
Based on these I updated by code as follows:
import kafka.admin.AdminUtils
import kafka.utils.ZkUtils
import kafka.utils.ZKStringSerializer$
import org.I0Itec.zkclient.{ZkClient, ZkConnection}
object Topic {
    def CreateKafkaTopic(topic: String, zookeeperHosts: String, partitionSize: Int, replicationCount: Int, connectionTimeoutMs: Int = 10000, sessionTimeoutMs: Int = 10000): Boolean = {
        var zkSerializer: ZKStringSerializer = ZKStringSerializer$.MODULE$
        val zkClient: ZkClient= new ZkClient(zookeeperHosts, connectionTimeoutMs, sessionTimeoutMs, zkSerializer)
        val topicConfig: Properties = new Properties()
        val isSecureKafkaCluster: Boolean = false

        val zkUtils: ZkUtils = new ZkUtils(zkClient, new ZkConnection(zookeeperHosts), isSecureKafkaCluster)

        AdminUtils.createTopic(zkUtils, topic, partitionSize, replicationCount, topicConfig)
        zkClient.close()
    }
}

And then I just get unable to resolve symbol ZkStringSerialzer$ errors.
I tried both with the org.I0Itec.zkclient.serialize.ZkSerializer object as well and it did not make a difference.
So my Question is actually two fold:
 1. What is the significance of the '$' character for the Import and Declarations statements in scala. I have used it in string interpolation ( e/g/ s"var value is $var")to reference variables but this seems different.
 2. What is wrong with my code. Is it the way I am importing, declaring, something else?
I am new to scala and Play but I am feeling like quite and idiot at the moment so any advice / help is appreciated
~Dave
P.S.
In case it helps relevant bits from project files
build.sbt:
lazy val `api` = (project in file(".")).enablePlugins(PlayScala)
scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
  "org.apache.kafka" % "kafka_2.11" % "0.9.0.1",
  jdbc,
  cache,
  ws,
  specs2 % Test
)

plugins.sbt:
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.4")

addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.0.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.1")

addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.1")

addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.0.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.0.0")

build.properties:
sbt.version=0.13.5

A: After fighting this issue over the weekend I gave up on the ZKClient package that had been used previously and simple used Kafka directly which was actually much cleaner that trying to use the I0Itech ZKClient.
New implementation goes like this:
import java.util.Properties
import kafka.admin.AdminUtils
import kafka.utils.ZkUtils

class Topic {
  def CreateKafkaTopic(topic: String, zookeeperHosts: String, partitionSize: Int, replicationCount: Int, connectionTimeoutMs: Int = 10000, sessionTimeoutMs: Int = 10000): Boolean = {
    if (ListKafkaTopics(zookeeperHosts).contains(topic) ) {
      return false
    }
    val zkUtils = ZkUtils.apply(zookeeperHosts, sessionTimeoutMs, connectionTimeoutMs, false)
    AdminUtils.createTopic( zkUtils, topic, partitionSize, replicationCount, new Properties())
    zkUtils.close()
    true
  }
}

End the end removed a dependency and make cleaner code so a double win I suppose.
~Dave

A: The reason for this problem is the ZkStringSerialzer is declared as private, just use ZkUtils.createZkClient instead as follows:
    ZkUtils.createZkClient(zookeeperHosts, sessionTimeoutMs, connectionTimeoutMs)


text:
Q: How is made sure magnetic or electric fields from devices like transformers or fans close nearby do never affect hard drives? Fans and transformers which are inside the server case create magnetic and electric fields.
Electric fields can be easily shielded, but what about magnetic fields, they can only be shielded with high cost materials like mu metal http://en.wikipedia.org/wiki/Mu-metal
If a hard drive is installed too close to an intense transformer field, how is the magnetically stored information on the ferromagnetic surfaces of the disk kept safe? Even if drives are shielded, where are the limits?
Is there some technical investigation or recommendation from manufacturers about this?
(I never heard about something and never had any problem but I am interested in some facts. This is much preferred over what you believe or a habit you developed. Please try to give some solid infromation.)
I have built and repaired many servers and sometimes I did put the harddrive on top of the power supply.
Edit: This question is not about frequencies that could affect the drive via the power or data connectors of the drive, those are electronically decoupled and that's another question.
Edit 2: The wikipedia page states that the motor inside the drive is shielded with mu metal. It is obvious that manufactureres have to take care of this. This question is about such influences from outside the drive.

A: Writing to a hard drive takes a much stronger field at a much closer distance than the fan motors and power supplies put out at their typical locations. The reason the magnets in the drive are shielded is that they are of the necessary strength and distance.
Also, the article says the magnets in the drive are shielded, it doesn't say anything about the motors.
Since we quit using floppy disks, we don't have to worry about this problem. However, I occasionally find myself avoiding putting CDs on top of speakers.


text:
Q: How to use Mongodb with Fable? I'm new to F# and Fable and I'm trying to create a Mongodb collection from a Fable's compiled code.
How can I express this code in F# to compile with Fable?
var MongoClient = require('mongodb').MongoClient;

A: According to some of the source of some fable import libs, fable-import-d3 and fable-import-pixi, the Import attribute allows for JS libs to be used directly. The caveat to that is that you are mapping the imported JS to an F# type.
SIDE NOTE
There does not appear to be a lib for mongodb and fable, e.g. fable-import-mongodb


text:
Q: Jasmine env is not defined I'm working on an AngularJS app. I'm trying to do some testing on it. Unfortunately, I can't seem to get it to work. I just get an error in my console window that says: "Uncaught ReferenceError: env is not defined". I've copied the code to run tests in AngularJS with Jasmine. The only difference that I can see is that I'm referencing a CDN. I've got a jsfiddle here, with the code posted below.
<!DOCTYPE html>

    <title>My Test Results</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" />

    run tests

The contents of my tests.e2e.js file are in the fiddle. For reference, the code is posted below:
'use strict';

describe('MyApp', function() {
    describe('MyPage', function () {
        it('should test', function () {
            expect(true).toBe(false);
        });
    });
});

What am I doing wrong?

A: This is how you can test using PLUNKER. Works as expected.
Jasmine is executed on page load.

I hope this will be helpful.


text:
Q: Fetching timestamps (hh:mm:ss) from Youtube comments with Youtube API using regex in JavaScript I am analyzing timestamped YouTube comments. Because some comments may refer to a period in either mm:ss, m:ss, hh:mm:ss, or h:mm:ss, I need to prepare for these cases. The following code works on mm:ss and m:ss, but still treats the one with hours as if it was mm:ss. For example, 02:24:30 returns 144, as it is only analyzing the first two parts. Here is the code:
var timePattern = /(([0-5][0-9])|[0-9])\:[0-9]{2,2}/;
var seconds = "";

for (var i = 0; i < comments.length; i++) {
    var matches = comments[i].match(timePattern);
    var matched = matches[0];
    var a = matched.split(':');
    if(matched.length == 7 || matched.length == 8) {
        seconds = (+a[0])*60*60 + (+a[1])*60 + a[2];
    } else {
        seconds = (+a[0])*60 + (+a[1]);
    }
    times.push(seconds);
}

A: Try a different regex.
(?:([0-5]?[0-9]):)?([0-5]?[0-9]):([0-5][0-9])

First contains hours, second contains minutes, last contains seconds.
Hours will be empty if no hours are found.

A: You can also get this info on the comments feed, if you're using the API: https://developers.google.com/youtube/2.0/developers_guide_protocol#Comments
The comments feed have a published element that contains the date and time information that you can use to parse the seconds of.


text:
Q: Using react hook form with custom react native picker modal fails to register value from modal picker Hello i'm fairly new to react native development for a few weeks and i'm attempting to connect react hook forms with a custom picker i implemented. The custom picker consists of a disabled text input that when click pops up a modal and the user can select a country code. But how can we validate an option is selected with react hook forms.I tried updating the state with setValue but this doesn't get triggered.
Code:
interface ExtrafieldProp {}
export type CountryCodeDropDownProp = ExtrafieldProp & TextInputProps

export default function CountryCodeDropDown(props: CountryCodeDropDownProp) {
    const [selectedValue, setSelectedValue] = useState('')
    const [hidePicker, setHidePicker] = useState(false)

    const hideCountrycodePicker = () => setHidePicker(false)

    const onBlur = () => setHidePicker(false)

    const getCountryCode = (value: string) => {
        setSelectedValue(`+${value}`)
        setHidePicker(false)
    }

    return (
        <>
            <Container width={props.width} onPress={() => setHidePicker(!hidePicker)}>
                <Wrapper pointerEvents='none'>
                    <Input
                        editable={false}
                        placeholder={'state'}
                        value={selectedValue}
                        keyboardType='default'
                        autoCorrect={false}
                        autoCapitalize='none'
                        onFocus={hideCountrycodePicker}
                        onBlur={onBlur}
                        onChangeText={getCountryCode}
                    />
                </Wrapper>
            </Container>
            <CountryCodePicker
                isVisible={hidePicker}
                hidePicker={hideCountrycodePicker}
                getCountryCode={getCountryCode}
            />
        </>
    )
}

interface ContainerProp {
    width?: number
}
const Container = styled.Pressable<ContainerProp>`
    width: ${(props) => `${props.width}px` || '100%'};
`

const Wrapper = styled.View``

 Wrap CountryCodeDropDown with react hook form
export type RhfSelectFieldProps<T extends FieldValues> = CountryCodeDropDownProps &
    UseControllerProps<T> &
    UseFormProps<T>

export const RhfSelectField = <T extends FieldValues>(props: RhfSelectFieldProps<T>) => {
    return (
        <Controller
            control={props.control}
            name={props.name}
            rules={props.rules}
            render={(fieldProps) => {
                return (
                    <>
                        <CountryCodeDropDown
                            {...props}
                            value={fieldProps.field.value}
                            onChangeText={(value: string) => {
                                // fails to update value
                                props.setValue(props.name, value)
                            }}
                            onBlur={fieldProps.field.onBlur}
                        />
                        {fieldProps.formState.errors[props.name] && (
                            <ErrorText fontSize={sizes.xsmall} style={{ alignSelf: 'center' }}>
                                {
                                    (
                                        fieldProps.formState.errors[props.name] as DeepMap<
                                            FieldValues,
                                            FieldError
                                        >
                                    )?.message
                                }
                            </ErrorText>
                        )}
                    </>
                )
            }}
        />
    )
}

In my main screen:
code: yup.string().required('This field is required'),

const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
} = useForm<CountryCodeValue>({
    resolver: yupResolver(countryCodeSchema),
    defaultValues: {
        code: '',
    },
    mode: 'onChange',
})

<RhfSelectField width={width * 0.23} name={'code'} control={control} />

I am able to load the modal picker and select a country code but when i attempt to submit react-hook-form complains the field is required meaning it never registered the value. Please any assistance or guidance would be appreciated.


text:
Q: How can i get the correct url for style background url when i use the html-loader? for example, if i have a test.html file, the code is:
<!DOCTYPE html>

  <meta charset="UTF-8"/>
  <title>test</title>
  <link rel="stylesheet" href="/styles/test.css">

i use html-loader to require it, just like:
const html = require(test.html);
console.log(html);

and the variable html print:
<!DOCTYPE html>

  <meta charset="UTF-8"/>
  <title>test</title>
  <link rel="stylesheet" href="[object Object]">

the style -> .test -> background can't get the correct url. How to resolve it ?
This is my webpack config code about html-loader:
{
  test: /\.html$/,
  include: [
    path.resolve(config.devDir)
  ],
  loader: 'html',
  query: {
    root: config.devDir,
    attrs: ['img:src', 'img:data-src', 'link:href']
  }
}


text:
Q: How to bridge git to ClearCase? I've recently used git svn and enjoyed it very much. Now I'm starting a new project at a different customer. At that site the SCM of choice is ClearCase. I haven't found a baked equivalent of git svn for ClearCase. Is there anybody who has tried to use git locally as a front-end to ClearCase using some tricks, configuration or scripting with any measure of success? If so can you please explain the method used?

A: The one process I usually follow is:

*

*snapshot cd within a ClearCase view/vobs/myComponent

*git init .

That allows me to consider a ClearCase component as a Git repo.
I can then do all the branching and "private" commits I want within that repo, making the file writable as I need them (possible within a snapshot view).
Once I have a stable final commit, I update my snapshot view, which list all the "hijacked" file: I checkout them and check-in them back to ClearCase.
Considering the Git limits, a repo per ClearCase (UCM) component is the right size for a Git repo.
See also What are the basic clearcase concepts every developer should know? for a comparison between ClearCase and Git.
The idea remains:

*

*no git-cc

*no need to import all the history of ClearCase (which has no notion of repository baseline, unlike the SVN revisions)

*creation of a Git repo within a ClearCase view for intermediate commits

*final Git commit mirrored in the ClearCase view through a checkin of all modified files.

A: Here's a method that avoids hijacks, which our team used this method quite successfully for over a year, until we retired ClearCase for Subversion (per company policy, although it is a backwards step for our team - we were basically just using ClearCase as a dumb file system, and virtually working natively in git, but now we're using the git-svn bridge which isn't as nice as native git.)
We used two directories, one for the ClearCase snapshot and master git repo, which we shared among the whole team and never edited files in, and one for our "working" directory.
The preparation in the ClearCase snapshot view is:

% git init
% git add **/*.cxx **/*.h **/Makefile (and so on)
% git commit -m "initial"

Then clone in your working directory:

% mkdir ~/work
% git clone /path/to/repo

Work in the working directory, on a branch:

% git checkout -b feature
% ...edit/compile...
% git add -u
% git commit

Make sure the ClearCase snapshot is up-to-date with pristine (which it always was for us, because we shared it among the team, and we all used git).
Then merge the branch onto the master by rebasing it, to avoid an automatic merge commit:

% git checkout master
% git pull
% git checkout feature
% git rebase master
% git checkout master
% git merge feature
% git branch -d feature

% git diff --name-status origin/master

Prepare the ClearCase view by checking out/mkelem/rmname any changed/new/removed files,
based off the output of git diff --name-status. We used a hand-rolled script to do this. Don't forget to check out any directories that have added/removed files:
Then push the git stuff back, and check in with ClearCase:

% git push
% cd /path/to/repo
% git reset --hard
% cleartool ci `cleartool lsco -r -short -me`

It seems like a lot of commands, but this includes setup, and your daily workflow doesn't use many commands. You can trivially build a script around the push-back-to-ClearCase step, and discover/show your team all the cool extra git stuff gradually as everyone gets used to the basic workflow.
The real beauty of this system is, after a while when everyone's competent with git, you can trivially ditch ClearCase and all the associated individual monkey work and fees. Maybe give the company's ClearCase guy a much needed holiday and some retraining with the savings. (Sadly at my company the git stuff was all skunkworks, and we've moved to Subversion - forwards from ClearCase but backwards from git!)
I strongly recommend you use the pristine script from ClearCase Globally, Git Locally, which runs in the ClearCase snapshot view and ensures it and git are in sync. We set this up as a cron job that ran twice daily, and also ran it manually whenever we were about to push back to git.
Unfortunately the link to the blog post is no longer valid. However the script is still available on Github.

A: While it may not be without a few warts (you have been warned), I feel I should mention I have written a bridge of sorts.
http://github.com/charleso/git-cc
Bridging between the two systems isn't easy, and I wish my solution was as half as good as git-svn. A big limitation is that you're really confined to mirroring a single stream; git-cc can't clone all your Clearcase branches (as nice as that would be). However, given that most of the alternative scripts resolve around a single Clearcase view you are no worse off (IMO).
Personally I find history quite important and what other solutions lack is their importing of history into Git. Being able to run git-blame on files and see their real authors is quite useful from time-to-time.
If nothing else git-cc can handle the aforementioned 'git log --name-status' step in Matt's solution above.
I'm certainly curious to hear what VonC and Matt (and others) think of this, as I agree that any bridge to Clearcase is fraught with difficulties and may be more trouble than it's worth.