text:
Q: How to enable drop from QTreeWidget to QML Map I've the following class that contains a QML Map:
class MapWidget : public QQuickWidget {

  Q_OBJECT

public:

  MapWidget() = delete;
  MapWidget(QWidget* parent = nullptr);
  MapWidget(const MapWidget&) = delete;
  MapWidget(MapWidget&&) = delete;
  ~MapWidget() = default;

public:

  MapWidget& operator=(const MapWidget&) = delete;
  MapWidget& operator=(MapWidget&&) = delete;

protected:

  void dragEnterEvent(QDragEnterEvent* event) override;
  void dropEvent(QDropEvent* event) override;
};

//// .cpp ////

MapWidget::MapWidget(QWidget* parent) :
  QQuickWidget(parent) {
  setSource(QUrl(QStringLiteral("qrc:/qml/map.qml")));
  setResizeMode(QQuickWidget::SizeRootObjectToView);
  setAcceptDrops(true);
  QQuickItem* mapItem = dynamic_cast<QQuickItem*>(rootObject()->findChild<QQuickItem*>("myMap"));
  mapItem->setAcceptHoverEvents(true);
}

///////////////////////////////////////////////////////////////////////////////
// VIRTUAL PROTECTED SECTION                                                 //
///////////////////////////////////////////////////////////////////////////////

void MapWidget::dragEnterEvent(QDragEnterEvent* event) {
  if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) {
    event->accept();
  }
  else {
    event->ignore();
  }
}

void MapWidget::dropEvent(QDropEvent* event) {
  if (event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) {
    QGeoCoordinate returnedValue;
    auto pos = rootObject()->mapToScene(event->pos());
    QQuickItem* mapItem = dynamic_cast<QQuickItem*>(rootObject()->findChild<QQuickItem*>("myMap"));
    rootObject()->setAcceptHoverEvents(true);
    QMetaObject::invokeMethod(mapItem, "toCoordinate", Q_RETURN_ARG(QGeoCoordinate, returnedValue), Q_ARG(QPointF, pos));
    event->accept();
  }
  else {
    event->ignore();
  }
}

And this is the map.qml:
import QtQuick 2.0
import QtQuick.Window 2.14
import QtPositioning 5.15
import QtLocation 5

Item {
    width: Qt.platform.os == "android" ? Screen.width : 512
    height: Qt.platform.os == "android" ? Screen.height : 512
    visible: true
    property double center_latitude: 59.91
    property double center_longitude: 10.75

    Plugin {
        id: mapPlugin
        name: "osm"
    }

    Map {
        objectName: "myMap"
        anchors.fill: parent
        plugin: mapPlugin
        center: QtPositioning.coordinate(center_latitude, center_longitude)
        zoomLevel: 14
        copyrightsVisible: false
    }
}

I can see the map. Next to it I've a QTreeWidget and I want to drag a QTreeWidgetItem into the map in order to create an item in the place where the mouse is placed.
With the debugger I can see that I enter in dragEnterEvent when I'm dragging the item inside the QML widget, but then when I release the mouse the dropEvent is not called. Also I can see in the widget the block sign, so it seems that the drop is not enabled in the map.
What I'm doing wrong and how can I enable the drop of a QTreeWidgetItem inside the map?

A: I got the solution from this SO comment. Basically you need to call either accept and/or acceptProposedAction in the dragEnterEvent() and dragMoveEvent().
void MapWidget::dragEnterEvent(QDragEnterEvent *event)
{
    qDebug() << Q_FUNC_INFO << event->pos();
    event->accept();
}

void MapWidget::dragMoveEvent(QDragMoveEvent *event)
{
    qDebug() << Q_FUNC_INFO << event->pos();
    event->accept();
}


text:
Q: Java - Copy folder from windows network path I am trying to copy the folder from the windows network share folder which protected by username and password
String url = "smb://40.123.xx.xx/sharefolder/";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, "username", "pas.");
SmbFile dir = new SmbFile(url, auth);
if(dir.exists()) {
File[] directories = new File("\\40.123.xx.xx\\sharefolder")
                .listFiles(file -> file.isDirectory() && file.getName().matches("[0-9]{6}"));

for (File getDirectory : directories) {
Path folder = Paths.get(getDirectory.getAbsolutePath());
                BasicFileAttributes attr = Files.readAttributes(folder, BasicFileAttributes.class);
//          System.out.println("creationTime: " + attr.creationTime());
                System.out.println("creationDate : " + sdf.format(attr.creationTime().toMillis()));
    try {
//      FileUtils.copyDirectoryToDirectory(new File(getDirectory.getAbsolutePath()),new File("F:\\localFolder"));

        } catch (IOException e) {
            e.printStackTrace();
            }

    }
}

But the File[] directories return null instead of return all folders path.
How do I access network folder and copy the files to local path.

A: Your UNC pathname has only one escaped backslash at the beginning so is not valid UNC path for the remote filesystem, so you are scanning \40.123.xx.xx\sharefolder when it should be scanning \\40.123.xx.xx\sharefolder:
System.out.println(new File("\\40.123.xx.xx\\sharefolder"))
\40.123.xx.xx\sharefolder        (WRONG)

System.out.println(new File("\\\\40.123.xx.xx\\sharefolder"))
\\40.123.xx.xx\sharefolder       (CORRECT)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copy files within Azure ADLS gen2 using Azure CLI, Rest API or Python is there any simple way to copy data within Azure ADLS gen2 using Azure CLI, Rest API or Python?
Azure ADLS gen2 API documentation is very limited for now...
https://learn.microsoft.com/en-us/rest/api/storageservices/data-lake-storage-gen2

A: According to my research, we can use Azure CLI or python to move a directory or move a file. For more details, please refer to the document.
For example

*

*Install the storage CLI extension. Please note that the CLI version should be larger than 2.0.67

az extension add -n storage-preview

*Script

# move directory
az storage blob directory move -c my-file-system -d my-new-directory -s my-directory --account-name mystorageaccount

# move a file
az storage blob move -c my-file-system -d my-file-new.txt -s my-file.txt --account-name mystorageaccount

Python
try:

       file_system_client = service_client.get_file_system_client(file_system="my-file-system")
       directory_client = file_system_client.get_directory_client("my-directory")

       new_dir_name = "my-directory-renamed"
       directory_client.rename_directory(rename_destination=directory_client.file_system_name + '/' + new_dir_name)

    except Exception as e:
     print(e)


text:
Q: How to create a widget with a Text and a list? I'm new to Flutter and I don't get what I'm doing wrong. Following some resources didn't really help me find the issue with the following code :
class history_screen extends StatelessWidget {
  const history_screen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    DB_Helper db = DB_Helper.instance;
    final rides = Provider.of<AppState>(context).rides;

    if (rides.isEmpty) {
      return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Icon(
                Icons.edit_off,
                size: height * 0.04,
              ),
              Text(
                "No history available",
                style: TextStyle(fontSize: height * 0.02),
              )
        ],
      )
      );
    }

    return
          RideList(rides: rides);

  }
}

So the above code is working and is rendering me or a message rides.isEmpty or a list given by RideList(rides:rides) if ride.isEmpty is wrong.
Now what I want to do is customize the view when it returns the list, in order to add a title and other objects, so I tried :
  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height;
    DB_Helper db = DB_Helper.instance;
    final rides = Provider.of<AppState>(context).rides;

    if (rides.isEmpty) {
      return Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(
            Icons.edit_off,
            size: height * 0.04,
          ),
          Text(
            "No history available",
            style: TextStyle(fontSize: height * 0.02),
          )
        ],
      ));
    }

    return Center(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          "Ride & Track ",
          style: TextStyle(fontSize: height * 0.02),
        ),
        RideList(rides: rides)
      ],
    ));
  }

but the list isn't rendering anymore, and the text isn't centered

How can I fix this problem ?
[EDIT]
code of RideList:
 @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: rides.length,
        itemBuilder: (context, index) {
          Ride ride = rides[index];
          return RideItem(
            ride: ride,
            onTap: () =>
                Navigator.of(context).push(MaterialPageRoute(builder: (_) {
              return RideDetailScreen(
                ride: ride,
                onDelete: () => _removeRide(context, ride),
              );
            })),
          );
        });
  }

A: Let's first see why is the issue coming. Basically, Column would try to use the minimum space available and ListView needs an infinite space. So, the column is a constrained widget while the listview needs infinite space. And listview will just use its parent's space.
One way is to make shrinkWrap: true and the other way is to wrap ListView with Expanded.

A: So I had to modify RideList:
@override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text("Title"),
        ListView.builder(
            shrinkWrap: true,
            itemCount: rides.length,
            itemBuilder: (context, index) {
              Ride ride = rides[index];
              return RideItem(
                ride: ride,
                onTap: () =>
                    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                  return RideDetailScreen(
                    ride: ride,
                    onDelete: () => _removeRide(context, ride),
                  );
                })),
              );
            }),

      ],
    );
  }


text:
Q: How can I optimize (minimize) the output of a machine leaning model? The situation is the following:
A want to optimize a process which takes wax to create wax products. For each product to be made, there is a different composition of wax, and a set o parameters for the process (machine configurations). During the process, some objects are discarded due to manufacturing defects.
My first idea is to create a supervised machine leaning model that takes the wax composition and machine configurations as inputs, and the number of wasted objects as output (I have the data to do this).
My problem is: after creating that model, how do I  find the optimal process parameters (machine configuration) to minimize the number of wasted objects, for a given wax composition (it can be a new composition, never seen before).
The problem with a better formulation:
I have a vector of features for the machine settings s = [s1, s2, … , sn], a vector of features for the wax composition w = [w1, w2, … , wm] and for different combinations of s and w I have a associated cost J.
I have a database of training examples relating different vectors s and w with a cost J.
With this data, I would like to create a system where I would input a vector w, and the system would output a vector s, such that s minimizes the cost J, for that specific vector w.
Sorry for the lack of a precise formulation.

A: It sounds to me like a linear programming problem (like simplex for example) which does precisely that: minimize(or maximize) an objective function with defined parameters(in your case machine configuration).(This is not directly related to the ML idea)


text:
Q: Comparar Data dentro do Mysql Estou tentando selecionar no banco a data mais proxima da data atual porem nao estou conseguindo um bom resultado.
A inserção é:
$titulo = trim($_POST["titulo"]);
$descricao = trim($_POST["descricao"]);
$data = $_POST['data'];

a consulta é:
SELECT * FROM eventos WHERE data > GETDATE() LIMIT 1

O que eu preciso é pegar a coluna DATA na tabela evento onde a DATA cadastrada seja maior que a data atual.

A: Você pode desenvolver da seguinte forma:
$DataAtual = date("Y-m-d");
$sql = "SELECT * FROM tabela WHERE data > {$DataAtual}";

Desta forma busca os registros que são maiores do que a data atual.
Ou se a $data vier do Post, faça:
$DataAtual = $_POST['data'];
$DataAtual = date("Y-m-d", strtotime($_POST['data'])); // caso a data venha em formato 00/00/0000
$sql = "SELECT * FROM tabela WHERE data > {$DataAtual}";

Lembre-se que o comando data > {$DataAtual} só serve se a data for MAIOR do que a data postada, se for igual ou maior, deve-se usar data >= {$DataAtual}.

Esta documentação pode te ajudar: http://www.w3schools.com/sql/sql_dates.asp

A: Fiz um pequeno ajuste para funcionar em meu sistema
$sql = "SELECT * FROM tabela WHERE data > '".$DataAtual."'";
mas a lógica é a mesma


text:
Q: mostrar datos en una ventana modal Hola tengo problemas para mostrar los datos de una tabla en una modal. Tengo una lista la cual lleno con un arreglo de php llamado resultadoPacientes esto es una array, y tengo una modal que es un formulario en donde al darle la segunda opcion deben enviarse los datos que se muestran en el modal. pero no cuadran los valores correspondientes

        position
        #
        Producto
        Acción

      <?php foreach ($resultadosPaciente as $key => $value) { ?>

          <?php echo $key; ?>
          <?php echo $value->ProdCodigo ; ?>
          <?php echo $value->ProdNombre ; ?>

           <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalCanje" data-codigoCanje="<?php echo $value->ProdCodigo ; ?>" data-tipo="normal">Estado</button>

      <?php } ?>

al momento de darle al boton de estado se me despliega el siguiente modal

Producto de regalo

                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      ×
                  </button>

                 <form id="form-canje-premio">
                  <input type="hidden" name="codigoCanje" id="codigoCanje">

                      Nombre
                      <input
                      type="text" readonly autocomplete="off" class="form-control" value="<?php echo  $value->ProdNombre; ?>" name="nombreProducto" id="nombreProducto">

                      Activo
                      <input
                        type="text" readonly class="form-control" value="<?php echo  $value->ProdActivo; ?>" name="activo" id="activo">

                      Cantidad de Premio
                      <input
                       type="text" readonly class="form-control" value="<?php echo  $value->Bono; ?>" name="cantPremio" id="cantPremio">

                       <input type="radio" name="estadoCanje" id="estadoCanje" value="1" required> Entrega Inmediata

                       <input type="radio" name="estadoCanje" id="estadoCanje" value="2" required> No hay disponibilidad producto
                       <input type="hidden" name="precioUnitario" id="precioUnitario" value="<?php echo  $value->ProdCosto; ?>">
                  <input type="hidden" name="codigoCanje" id="codigoCanje" value="<?php echo $value->CodigoDescuento; ?>">
                  <input type="hidden" name="productoId" id="productoId" value="<?php echo  $value->ProdCodigo; ?>">
                  <input type="hidden" name="tarjetaId" id="tarjetaId" value="<?php echo  $value->TarjetaID; ?>">

                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                  <button type="submit" class="btn btn-primary">Aceptar</button>

                </form>

el problema es que no muestra los valores correspondientes o bueno solo muestra un valor


text:
Q: Fastreport VCL 6.8 Text in crosstab value field giving error I want to add a text field in a crosstab value field but getting error as below

"Variant or safe array index out of bound".

What is the solution. it is working in my old application compiled with vcl 5 but gives error when compiled with vcl 6
Error is displayed when report is run


text:
Q: when provided a value, looking to have the row number of the cell where that value resides Please take a look at the following googleapps script code. the spreadsheet it references has 4 values in it. in a2 is the value "Two". I want that when I run this code, i receive an email with "2" in the subject line. I seem to keep on receiving a "4". Any ideas?
function rowofspecificvalue(){
var sheet = SpreadsheetApp.openById("1rMUrZFie94RLFDKaWVBPsQ-jebL8wNA6qsZWivMBDTk").getActiveSheet();
var data = sheet.getRange("a1:a4").getValues();
for(var i = 0; i<data.length;i++){
if(data[i][1] == "Two"){
 Logger.log((i+1))
  return i+1;
  }
 } MailApp.sendEmail ("fake_email@gmail.com", i, "");
}

Thanks!

A: Write
MailApp.sendEmail("fake_email@gmail.com", i-2, "")

and you will "2" have in subject. Second argument of MailApp.sendEmail() function set up subject of email.


text:
Q: JSON Parsing using Decodable I am trying to parse the following JSON using decodable protocol. I am able to parse string value such as roomName. But I am not able to map/parse owners, admins, members keys correctly. For eg, using below code, I can able to parse if the values in owners/members are coming as an array. But in some cases, the response will come as a string value(see owners key in JSON), but I am not able to map string values.
Note:  Values of admins, members, owners can be string or array (see owners and members keys in JSON)
{
    "roomName": "6f9259d5-62d0-3476-6601-8c284a0b7dde",
    "owners": {
        "owner": "anish@local.mac" //This can be array or string
    },
    "admins": null, //This can be array or string
    "members": {
        "member": [ //This can be array or string
            "steve@local.mac",
            "mahe@local.mac"
        ]
    }
}

Model:
 struct ChatRoom: Codable{
        var roomName: String! = ""
        var owners: Owners? = nil
        var members: Members? = nil
        var admins: Admins? = nil

        enum RoomKeys: String, CodingKey {
            case roomName
            case owners
            case members
            case admins
        }
       init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: RoomKeys.self)
            roomName = try container.decode(String.self, forKey: .roomName)
           if let member = try? container.decode(Members.self, forKey: .members) {
                members = member
            }
            if let owner = try? container.decode(Owners.self, forKey: .owners) {
                owners = owner
            }
            if let admin = try? container.decode(Admins.self, forKey: .admins) {
                admins = admin
            }
    }
}

//Owner Model
struct Owners:Codable{
    var owner: AnyObject?

    enum OwnerKeys:String,CodingKey {
        case owner
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: OwnerKeys.self)
        if let ownerValue = try container.decodeIfPresent([String].self, forKey: .owner){
            owner = ownerValue as AnyObject
        }
        else{
            owner = try? container.decode(String.self, forKey: .owner) as AnyObject
        }
    }

    func encode(to encoder: Encoder) throws {

    }
}

//Member Model
struct Members:Codable{
    var member:AnyObject?

    enum MemberKeys:String,CodingKey {
        case member
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: MemberKeys.self)
        if let memberValue = try container.decodeIfPresent([String].self, forKey: .member){
            member = memberValue as AnyObject
        }
        else{
            member = try? container.decode(String.self, forKey: .member) as AnyObject
        }
    }

    func encode(to encoder: Encoder) throws {

    }
}

A: This should work. I've removed Admin model for simplicity. I'd prefer Owners/Members to be arrays as they can have one or more values which is what they're for, but if you want them to be AnyObject, you can cast them as so like you're already doing in your init(decoder:).
Test data:
var json = """
    {
        "roomName": "6f9259d5-62d0-3476-6601-8c284a0b7dde",
        "owners": {
            "owner": "anish@local.mac"
        },
        "admins": null,
        "members": {
            "member": [
            "steve@local.mac",
            "mahe@local.mac"
            ]
        }
    }
    """.data(using: .utf8)

Models:
struct ChatRoom: Codable, CustomStringConvertible {
    var roomName: String! = ""
    var owners: Owners? = nil
    var members: Members? = nil

    var description: String {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        let data = try? encoder.encode(self)
        return String(data: data!, encoding: .utf8)!
    }

    enum RoomKeys: String, CodingKey {
        case roomName
        case owners
        case members
        case admins
    }
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: RoomKeys.self)
        roomName = try container.decode(String.self, forKey: .roomName)
        members = try container.decode(Members.self, forKey: .members)
        owners = try? container.decode(Owners.self, forKey: .owners)
    }
}

struct Owners:Codable{
    var owner: [String]?

    enum OwnerKeys:String,CodingKey {
        case owner
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: OwnerKeys.self)
        if let ownerValue = try? container.decode([String].self, forKey: .owner){
            owner = ownerValue
        }
        else if let own = try? container.decode(String.self, forKey: .owner) {
            owner = [own]
        }
    }
}

struct Members: Codable {
    var member:[String]?

    enum MemberKeys:String,CodingKey {
        case member
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: MemberKeys.self)
        if let memberValue = try? container.decode([String].self, forKey: .member){
            member = memberValue
        }
        else if let str = try? container.decode(String.self, forKey: .member){
            member = [str]
        }
    }
}

Test:
var decoder = JSONDecoder()
try? print("\(decoder.decode(ChatRoom.self, from: json!))")

Output:
{
  "owners" : {
    "owner" : [
      "anish@local.mac"
    ]
  },
  "members" : {
    "member" : [
      "steve@local.mac",
      "mahe@local.mac"
    ]
  },
  "roomName" : "6f9259d5-62d0-3476-6601-8c284a0b7dde"
}

A: As you are getting some data as Array or String you can parse this underlying Type with the help of an enum. This will reduce some boilerplate codes as well as redundant codes for each Type you define that is able to have Array or String values.
You define an enum like this:
enum ArrayOrStringType: Codable {
    case array([String])
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            self = try .array(container.decode([String].self))
        } catch DecodingError.typeMismatch {
            do {
                self = try .string(container.decode(String.self))
            } catch DecodingError.typeMismatch {
                throw DecodingError.typeMismatch(ArrayOrStringType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload conflicts with expected type"))
            }
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .array(let array):
            try container.encode(array)
        case .string(let string):
            try container.encode(string)
        }
    }
}

And then your models go as:
struct ChatRoom: Codable {
    let roomName: String
    let owners: Owner
    let admins: ArrayOrStringType?  // as you are likely to get null values also
    let members: Member

    struct Owner: Codable {
        let owner: ArrayOrStringType
    }
    struct Member: Codable {
        let member: ArrayOrStringType
    }
}
/// See!! No more customization inside every init(from:)

Now you can parse your data that contains any of your desired type (Array, String)
Test data 1:
// owner having String type
let jsonTestData1 = """
{
    "roomName": "6f9259d5-62d0-3476-6601-8c284a0b7dde",
    "owners": {
        "owner": "anish@local.mac"
    },
    "admins": null,
    "members": {
        "member": [
            "steve@local.mac",
            "mahe@local.mac"
        ]
    }
}
""".data(using: .utf8)!

Test data 2:
// owner having [String] type
let jsonTestData2 = """
{
    "roomName": "6f9259d5-62d0-3476-6601-8c284a0b7dde",
    "owners": {
        "owner": ["anish1@local.mac", "anish2@local.mac"]
    },
    "admins": null,
    "members": {
        "member": [
            "steve@local.mac",
            "mahe@local.mac"
        ]
    }
}
""".data(using: .utf8)!

Decoding process:
do {
    let chatRoom = try JSONDecoder().decode(ChatRoom.self, from:jsonTestData1)
    print(chatRoom)
} catch {
    print(error)
}
// will print
{
  "owners" : {
    "owner" : "anish@local.mac"
  },
  "members" : {
    "member" : [
      "steve@local.mac",
      "mahe@local.mac"
    ]
  },
  "roomName" : "6f9259d5-62d0-3476-6601-8c284a0b7dde"
}

do {
    let chatRoom = try JSONDecoder().decode(ChatRoom.self, from:jsonTestData2)
    print(chatRoom)
} catch {
    print(error)
}
// will print
{
  "owners" : {
    "owner" : [
      "anish1@local.mac",
      "anish2@local.mac"
    ]
  },
  "members" : {
    "member" : [
      "steve@local.mac",
      "mahe@local.mac"
    ]
  },
  "roomName" : "6f9259d5-62d0-3476-6601-8c284a0b7dde"
}

You can even get more out of the structure. Lets say, you want to work with owners only. You will likely try to get the values as Swifty way:
do {
    let chatRoom = try JSONDecoder().decode(ChatRoom.self, from:json)
    if case .array(let owners) = chatRoom.owners.owner {
        print(owners) // ["anish1@local.mac", "anish2@local.mac"]
    }
    if case .string(let owners) = chatRoom.owners.owner {
        print(owners) // "anish@local.mac"
    }
} catch {
    print(error)
}

Hope this structuring helps a lot more than other typical ways. Plus this is having the explicit consideration of your expected types. Neither it relies on one type (Array only) nor Any/AnyObject type.

A: I recreated yours models and tested with your JSON and it worked fine. If your backend returns different types in the different cases (business rules), maybe the best way is create separate variables for each case.(imho)
// Model
import Foundation
struct ChatRoom : Codable {
    let roomName : String?
    let owners : Owners?
    let admins : String?
    let members : Members?

    enum CodingKeys: String, CodingKey {

        case roomName = "roomName"
        case owners
        case admins = "admins"
        case members
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        roomName = try values.decodeIfPresent(String.self, forKey: .roomName)
        owners = try Owners(from: decoder)
        admins = try values.decodeIfPresent(String.self, forKey: .admins)
        members = try Members(from: decoder)
    }

}

-
// Member Model
    import Foundation
    struct Members : Codable {
        let member : [String]?

        enum CodingKeys: String, CodingKey {

            case member = "member"
        }

        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            member = try values.decodeIfPresent([String].self, forKey: .member)
        }

    }

-
// Owner Model

import Foundation
struct Owners : Codable {
    let owner : String?

    enum CodingKeys: String, CodingKey {

        case owner = "owner"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        owner = try values.decodeIfPresent(String.self, forKey: .owner)
    }

}


text:
Q: Overflow Scroll within a responsive layout I have this layout:

And here is the CSS:
#container {
    background-color: black;
    display:block;
    position:absolute;
    height:auto;
    width:auto;
    bottom:0;
    top:0;
    left:0;
    right:0;
    overflow:hidden;
    background-size:auto 100%;
    margin:50px;
}
#sidebar {
    background-color: purple;
    min-width: 250px;
    width:250px;
    max-width: 20%;
    height:100%;
    overflow:hidden;
    float:left;
}
#logo {
    height: 100px;
    background-color: orange;
}
#box {
    bottom: 20px;
    font-family: sans-serif;
    font-size: 10px;
    color: grey;
    margin: 20px;
    padding: 10px;
    background-color: white;
    overflow-y: scroll;
    text-align: justify;
}
#content {
    display:inline;
    width:75%;
    margin-left: 300px;
    padding: 0px;
    margin:0px;
    text-align: center;
    background-color: green;
    overflow-y: scroll;
}
#gallery {
    margin-left: auto;
    margin-right: auto;
    display: table;
    background-color: blue;
}
.thumb {
    width: 200px;
    height: 150px;
    display: inline-block;
    background-color: black;
    margin: 20px;
    border: 7px solid white;
    overflow:hidden;
    background-color: yellow;
}

I need the content of the #box and either #gallery or #content to be scrollable vertically.
Because my layout is responsible and the overflow of the #container is hidden I think there must be some problem with these features.
Here I created a jsFIddle to illustrate the problem.

A: You can add this in CSS #box
max-height : 100px ; /*for example*/

EDIT :
for you can use
overflow: auto;

in DIV you want to scroll


text:
Q: How do I use PLINQ to process chunks of an array I need to take a large array of doubles, and process it in chunks using a processor intensive function.
My original array is extremely large, about 200MB of doubles of signal data.
I need to take it in chunks of 5000 doubles each, process those with some very processor intensive math using a function that returns a single double.  Each of those functions results is needed to create an ordered array that is used later.
I think this would be optimal for parallelism using PLINQ, but I am not quite sure how to go about doing it.
The naive implementation that I wrote looks like this :
        var processedList = new List<double>();

        var chunk = new List<double>;
        foreach (var rawSample in drop.RawSamples)
        {
            chunk.Add(rawSample);

            if (chunk.Count == 5000)
            {
                // Do long processing here
                processedList.Add(LongProcessingFunction(chunk));

                chunk.Clear();
            }
        }

        // Do something later with the list of processed values.....

So, where do I start with PLINQ?  I need to be able to do the long, intensive function using all the cores of the processor.
I see there is a Take(n) function for IEnumerable.....  Can I use this?
Can I use AsParallel here?
Thanks!

A: First, if you're dealing with this amount of data, you should avoid processing it element by element, if you can. In your code, you could do that by iterating integers in 5000 increments and using something like Array.Copy().
Or, even better, don't do any copying at all, let LongProcessingFunction accept an array (or IList<T>, or IReadOnlyList<T>, if you're on .Net 4.5; but using an interface does have some overhead) and an offset into that array.
If you then want to make your code parallel, you can use ParallelEnumerable.Range() with AsOrdered() (which is necessary to have the results in the correct order) and Select():
double[] result = ParallelEnumerable.Range(0, drop.RawSamples.Length / chunkSize)
    .AsOrdered()
    .Select(i => LongProcessingFunction(drop.RawSamples, i * chunkSize))
    .ToArray();

A: I would suggest to implement a partitioner on your indexed source which will partition your source into chunks of 5000 elements. Each of them can then be processed paraallelly using AsParallel.
class Program
{
    static void Main(string[] args)
    {

        IList<double> rawData =  [Your raw data here];

        IList<double> result =
            rawData
                .Partition(5000)
                .AsParallel()
                .AsOrdered()
                .Select(chunk => LongProcessingFunction(chunk))
                .ToList();
    }

    private static double LongProcessingFunction(IList<double> chunk)
    {
        throw new NotImplementedException();
    }
}

public static class MyExtensions
{
    public static IEnumerable<List<T>> Partition<T>(this IList<T> source, Int32 size)
    {
        for (int i = 0; i < Math.Ceiling(source.Count / (Double)size); i++)
        {
            yield return new List<T>(source.Skip(size*i).Take(size));
        }
    }
}


text:
Q: What should I choose in this situation? Why are your hands so dirty ?
Well,I________ in the garden
1-Worked      2-
Have worked    3-
Have been working

A: "I have worked in the garden" gives no feeling for when you worked there, other than at some time in the past. You may have worked there last year, which does not explain why your hands are dirty now. If the sentence read "I have worked in the garden today" it might explain why your hands are dirty now.
"I have been working in the garden" gives the feeling that you have worked there until recently, which would explain why your hands are dirty.


text:
Q: How to record audio in browser on iOS? All tutorials I found make use of getUserMedia(), which doesn't exist in iOS Browsers. Is there any other way to record Audio in the Browser on iOS?

A: Since iOS 11, getUserMedia is supported in iOS browsers.
You can use this simple example:
constraints = { audio: true, video: true };
navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess);

var handleSuccess = function (stream) {

    var context = new AudioContext();
    var processor = context.createScriptProcessor(1024, 1, 1);
    var input = context.createMediaStreamSource(stream);

    processor.connect(context.destination);
    input.connect(processor);

    processor.onaudioprocess = function (e) {
        // Get sound packets from microphone
        // e.inputBuffer.getChannelData(0) will now have sound packets
    };
};


text:
Q: What show am I remembering about aliens taking over Earth? I think in this show aliens have taken over the earth and essentially humans are working with/for them - but although things seem better the aliens are really farming people for food. I remember three specific scenes/plot lines and I believe both are from the same show: there is some sort of maternity/fertility clinic and video billboards urge women to come to it; there is a teen or young woman who is pregnant and some character close to her tells her not to go to that clinic; there is a woman (doctor? scientist?) maybe working at this clinic and she discovers the doctor is involved with giving the babies to the aliens. Next scene - a lower level area (maybe in clinic) is discovered where people are being processed - hanging on hooks like cattle; there is a fight there as good guys try to save people and stop this.
Last scene, people are sent (voluntarily?) to what is supposed to be a good place to live and work, maybe sold as sort of a farm or something, and good guys discover it the people who go there are killed; I think they have to show the facility to someone who does not believe this is happening.
I can't remember any actors, and my googling efforts have run out of key words etc. It is NOT "V" - I think I saw this within the past few years, should be something made between 2000 and 2017. I am sure I watched it as home, and it was more likely a series or miniseries than a feature film. Maybe a short lived series?

A: Thanks to Joelogon! I just read recaps of Season 4 of The Strain and everything fell into place. I had a few random images from The Lottery series mixed into my memories which had caused me additional confusion. But bottom line is the bad guys were Strigori vampires, not aliens - plus a few human baddies. So glad to be able to stop obsessing about this now!!!
Thanks to all who gave input!

A: The V TV series was remade in 2009 and aired until as it turns out until 2011. https://www.imdb.com/title/tt1307824/ It is the only series that I know of that covers an alien invasion of Earth in order to use humans as a food source. I will continue to do some research but I am unaware of any other such series being made other than V. First in 1984 and then again in 2009.


text:
Q: Divide Array to something like Masonry Grid What I need to help with:

*

*I need to create a function toColumns that will be able to
divide photos Array to (chunks) Array according to the example below.

*Another function fromColumns as a reverse function.

It will remind the Masonry Grid for photos.
Example:

*

*toColumns([1, 2, 3, 4], 3) -> [[4, 1], [3], [2]]

*toColumns([1, 2, 3, 4], 2) -> [[4, 2], [3, 1]]

*toColumns([1, 2, 3, 4], 1) -> [[4, 3, 2, 1]]

*toColumns([1, 2, 3, 4], 5) -> [[4], [3], [2], [1]] - if we do not have enough photos

Why 4 with 1? - Graphically (3 columns)
|-----------|
| 4 | 3 | 2 |
|-----------|
| 1 |   |   |
|-----------|

Why 4 with 2 and 3 with 1? - Graphically (2 columns)
---------
| 4 | 3 |
---------
| 2 | 1 |
---------

Code: (https://jsfiddle.net/f3r2r28s/)
const photos = [{
  id: 1,
  height: '50px',
  photo: 'A'
}, {
  id: 2,
  height: '100px',
  photo: 'B'
}, {
  id: 3,
  height: '150px',
  photo: 'C'
}, {
  id: 4,
  height: '200px',
  photo: 'D'
}];

let response = [];

const toColumns = (photos, columns) => {
  /*
    Response:
        response = [
          [
            {
              id: 4,
              photo: 'D',
            },
            {
              id: 1,
              photo: 'A',
            }
          ],
          [
            {
              id: 3,
              photo: 'C',
            },
          ],
          [
            {
              id: 2,
              photo: 'B',
            },
          ],
      ];
  */
};

toColumns(photos, 3);

A: hope this is what you want
const toColumns = (photos, columns) => {
    photos = photos.reverse()
    let response = []
    for(let i = 0, l = photos.length; i < l; i++){
        let j = i % columns
        response[j] = response[j] || []
        response[j].push(photos[i])
    }
    return response
}
const fromColumns = (columns) => {
    let result = []
    let i = j = 0, l = columns.length
    while (1){
        if(!columns[i][j]) break
        result.push(columns[i][j])
        if(++i >= l){
            i = 0
            j++
        }
    }
    return result.reverse()
}
let photos = [1,2,3,4]
console.log(toColumns(photos, 3)) // [ [ 4, 1 ], [ 3 ], [ 2 ] ]
console.log(toColumns(photos, 2)) // [ [ 4, 2 ], [ 3, 1 ] ]
console.log(toColumns(photos, 1)) // [ [ 4, 3, 2, 1 ] ]
console.log(toColumns(photos, 5)) // [ [ 4 ], [ 3 ], [ 2 ], [ 1 ] ]
console.log(fromColumns(toColumns(photos, 2))) // [ 1, 2, 3, 4 ]


text:
Q: How to do TDD with Typescript in Visual Studio Code? I want to setup TDD in Visual Studio Code for typescript. I am working on an angular2 application and i am writing my code in typescript. How can  i setup Visual Studio Code so that it runs Karma as well as Typescript compiler in the background and the results are shown in the output window?

A: TDD - is just a concept of development.
So the answer for your question - you need to create configuration for your building tools which take care of your testing for VSC. Here - VS Code tasks configuration you can find guide, how to integrate such building tools like Grunt or Gulp with VS Code.
But if you don't have building process yet you need first of all create all stuff which will help you in Test Driven Development. So you need watcher which looks at your code and run particular test once code changed. There different ways to do that, hope this small article will move you ahead.


text:
Q: Find $\lim_{\epsilon\to 0}\frac{1}{\epsilon^3}\int\limits_{0}^{\infty}\sin(\epsilon\cdot f(t))d\mu(t)$ given $\int\limits_{0}^{\infty}f=0$ Let $(\mathbb {R},\mathcal B, \mu)$ be finite measure space, where $\mathcal B$ is the Borel sigma-algebra on $\mathbb R$.
Let $f$ be an integrable function such that $$ \int\limits_{0}^{\infty}f(x)d\mu = 0.$$
Also assume $f^2$ is integrable, i.e $\int\limits_\mathbb {R} f^2d\mu<\infty.$
find $$\lim_{\epsilon \to 0}\frac{1}{\epsilon ^ 3}\int\limits_{0}^{\infty}\sin(\epsilon\cdot f(t))d\mu(t)$$

A: If $f\in L^4$ then the answer is $-\frac{1}{6} \int_0^{\infty} f^3 d\mu$. There is consequently no consistent answer when we only know that $f^2$ is integrable.
Indeed, if $f\in L^4$ then write
$$ \sin\left(\epsilon f\left(t\right) \right) = \epsilon f\left(t\right) - \frac{1}{6} \epsilon^3 f\left(t\right)^3 + \frac{\sin\left(c_t\right)}{24} \epsilon^4 f\left(t\right)^4, $$
and integrate:
$$ \frac{1}{\epsilon^3} \int_0^{\infty} \sin\left(\epsilon f\left(t\right)\right) d\mu = -\frac{1}{6} \int_0^{\infty} f^3 d\mu + \frac{\epsilon}{24} \int_0^{\infty} \sin\left(c_t\right)f^4\left(t\right) d\mu\left(t\right)  . $$
The error term (i.e. the last term on the right) can be bounded as follows, using $\left|\sin\left(c_t\right)\right| \leq 1$:
$$ \frac{\epsilon}{24} \left|\int_0^{\infty} \sin\left(c_t\right)f^4\left(t\right) d\mu\left(t\right)\right| \leq \left(\frac{\int_0^{\infty} f^4 d\mu}{24}\right) \epsilon \xrightarrow[\epsilon\searrow 0]{}0, $$
since $f^4$ is integrable.

A: The limit may be $+\infty$. Let $\mu$ be the Lebesgue measure. Let $f(t) = \epsilon_t\frac{1}{t^{.49}}$ where $\epsilon_t = 0$ for $t \le 0$ and $t \ge 1$, $\epsilon_t = 1$ for $0 < t \le t_*$, and $\epsilon_t = -1$ for $t_* < t < 1$, where $t_* = \frac{1}{2^{100/51}} \approx .25689$ is such that $\int_\mathbb{R} f(t)dt = 0$. Take $\epsilon > 0$ very small. Then, for $t < \epsilon^{1/.49}$, we have $\sin(\epsilon\frac{\epsilon_t}{t^{.49}}) \sim \epsilon\frac{\epsilon_t}{t^{.49}}$, so $\int_{\epsilon^{1/.49}}^1 \sin(\epsilon f(t))dt \sim \int_{\epsilon^{1/.49}}^1 \epsilon\frac{\epsilon_t}{t^{.49}}dt = -\epsilon\int_0^{\epsilon^{1/.49}} \frac{1}{t^{.49}}dt = -\frac{100}{51}\epsilon^{100/49}$.
Ok, I actually have to go now, but the leftover region is of size $\epsilon^{1/.49} = \omega(\epsilon^3)$, which is bad. The situation for $f(t) = \epsilon_t\frac{1}{t^{1/8}}$ is very different, since then $\sin(\epsilon f(t)) \sim \epsilon f(t)$ for all $t > \epsilon^8$, so the leftover error is at most $\epsilon^8$, which is small enough.


text:
Q: How to expand 2nd argument if it's a glob pattern? I'm trying to write a script that counts the number of matches of some pattern in a list of files and outputs its findings. Essentially I want to call the command like this:
count-per-file.sh str_needle *.c
and get output like:
Main.c: 12
Foo.c: 1

The script:
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
#   count-per-file.sh SEARCH_PATTERN GLOB_EXPR
for file in "$2"; do
    count=$(grep -a "$1" "$file" | wc -l)
    if [ $count -gt 0 ]; then
        echo "$file: $count"
    fi
done

The problem is if I call it like so I don't know how to loop over the file list, so this outputs nothing:
count-per-file.sh str_needle *.c

I found this answer but it deals the glob pattern being the only argument to the script, whereas in my script the first argument is the search pattern, and the rest are the files expanded from the glob.

A: As suggested I used shift which seems to 'pop' the first argument. Here's my working script:
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
#   count-per-file.sh SEARCH_PATTERN GLOB_EXPR
search_pattern="$1"
shift

for file in "$@"; do
    count=$(grep -aiE "$search_pattern" "$file" | wc -l)
    if [ $count -gt 0 ]; then
        echo "$file: $count"
    fi
done

A: You can use substring parameter expansion with an start index like this to skip the first n-1 values in $@
"${@:n}"
e.g.
for FILE in "${@:2}"
do
  echo $FILE
done

N.B. Your script doesn't get a 'glob pattern' as the second argument.
The shell that calls your script expands the glob to a space separated list of files before your script sees it and passes this to your script as the parameter list. This is why you can use standard substring range expansion.

A: I think this is what you want
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
#   count-per-file.sh SEARCH_PATTERN GLOB_EXPR
for file in $2; do                               #UNQUOTE THIS TO EXPAND GLOB
    count=$(grep -a "$1" "$file" | wc -l)
    if [ $count -gt 0 ]; then
        echo "$file: $count"
    fi
done

Then pass the glob in in quotes so it doesn't expand on the command line
count-per-file.sh str_needle '*.c'

A: You can add the quotes while passing *.c and remove quotes while using them in for loop and it will work..
[root@client1 ~]# cat  count-per-file.sh
#!/bin/bash
# Count occurences of pattern in files.
#
# Usage:
#   count-per-file.sh SEARCH_PATTERN GLOB_EXPR
for file in $2; do
    count=$(grep -a "$1" $file | wc -l)
    if [ $count -gt 0 ]; then
        echo "$file: $count"
    fi
done
[root@client1 ~]# bash count-per-file.sh str_needle "*.c"
file.c: 1
Main.c: 12
[root@client1 ~]#


text:
Q: SearchBox in GWT Maps V3 Api (branflake2267/GWT-Maps-V3-Api version 3.8.1) I am develop an app using GWT Maps Api V3. I try create Place search box  like example of Google Maps JavaScript API(link Place search box - Google Maps JavaScript API  )
I have viewed the javascript code, they create SeachBox by using google.maps.places.SearchBox But in GWT Maps Api V3 ( version 3.8.1, GWT-Maps-V3-Api ), there is no class name SearchBox. I think i can create a SearchBox by using autocomplete and a html input field. But i can not place my nput field inside my map. So, my question is: what is the right way to create a SearchBox with GWT Maps V3 Api?
Thank for any help.

A: I have solved my problem by using  method (on branflake2267/GWT-Maps-V3-Api version 3.8.1)

void com.google.gwt.maps.client.MapWidget.setControls(ControlPosition controlPosition, Widget widget)

First, i create a textbox
private TextBox placeSearchTextField = new TextBox();

and use setControls:
mapWidget.setControls(ControlPosition.TOP_LEFT, placeSearchTextField );

add autocomple
private void drawAutoComplete() {

    Element element = placeSearchTextField.getElement();

    AutocompleteType[] types = new AutocompleteType[2];
    types[0] = AutocompleteType.ESTABLISHMENT;
    types[1] = AutocompleteType.GEOCODE;

    AutocompleteOptions options = AutocompleteOptions.newInstance();
    options.setTypes(types);

    final Autocomplete autoComplete = Autocomplete.newInstance(element, options);

    autoComplete.addPlaceChangeHandler(new PlaceChangeMapHandler() {
      public void onEvent(PlaceChangeMapEvent event) {

        PlaceResult result = autoComplete.getPlace();

        PlaceGeometry geomtry = result.getGeometry();
        LatLng center = geomtry.getLocation();

        GWT.log("place changed center=" + center);
      }
    });

    mapWidget.getMap().addBoundsChangeHandler(new BoundsChangeMapHandler() {
        public void onEvent(BoundsChangeMapEvent event) {
          LatLngBounds bounds = mapWidget.getMap().getBounds();
          autoComplete.setBounds(bounds);
        }
      });
}

with some css, I get the result


text:
Q: How to upload a video to Facebook as "Premiere" This answer describes how to upload a video to Facebook as a scheduled video.
I am now looking how to publish a video as a "Premiere".
Differences between live, scheduled video, and premieres:

*

*A live video is being broadcast via RTMP, concurrently.

*A scheduled video is pre-uploaded in its entirety. After the
scheduled time, the user can skip to any point in the video.

*A "premiere" is pre-uploaded in its entirety. After the scheduled
time, Facebook simulates a broadcast. The user cannot skip ahead.

What's the proper parameter to set up the video as "Premiere"?


text:
Q: Validating XML parsed with ElementTree, possible? Am I correct in that ElementTree does not support DTD or XSD? Is there a means of plugging anything into ElementTree to support validation, preferrably via XML Schema?

A: I would try using the lxml library; it supports etree representations and validation.


text:
Q: Nginx Reverse Proxying to Node.js with Rewrite I have several apps running behind an Nginx reverse proxy, one of which is a Node server with Express.js. I'm proxying domain.com/demo/app/<path> to localhost:7003/<path> using this Nginx config:
http {

    ...

    server {

        listen 80;
        server_name domain.com;

        ...

        location /demo/app {

            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Scheme $scheme;

            rewrite ^/demo/app/?(.*) /$1 break;
            proxy_pass http://localhost:7003;
        }

        ...
    }
}

This works great and app receives requests as if it was rooted at /. The problem is app handles its own static files and might make requests for routes such as css/app.css or images/image.jpg. But because of the reverse proxy, these actually exist at /demo/app/css/app.css and /demo/app/images/image.jpg respectively.
I've solved this by getting Nginx to pass to Node a custom header indicating the root path, which the Node server prepends to the URLs of all subsequent requests. But now my code is littered with these root path strings. For example, part of my back-end templates:
link(rel='stylesheet', href="#{basePath}/css/base.css")
link(rel='stylesheet', href="#{basePath}/css/skeleton.css")
link(rel='stylesheet', href="#{basePath}/css/layout.css")

What's a more elegant way to handle this? Isn't there a way to get Nginx to recognize requests coming from an upstream server and automatically forward them to that server?

A: I have made nginx serve static files without even passing those requests to node by adding location directive to the app's nginx configuration file (which is included in nginx.conf):
location ~ /(img|js)/ {
    rewrite ^(.*)$ /public/$1 break;
}

location / {
    proxy_pass http://localhost:3000/;
    ...
}

In case request comes to /img or /js directory nginx serves files from /public/img or /public/js directory respectively. All other requests are proxied to node.
You can add more directories if you need (like /css or /views, if you store templates there that you want to use both in node and in browser) and have any directory structure inside those directories, nginx just prepends /public to them and gets files from there without your node app even knowing about it.


text:
Q: C continious allocation with different type I need to recreate a memory organizer using the fisrt-fit model :
We allocate continuous memory and then we need to allocate precise block.
We know with the help of a linked list which block is free.
The problem is that i need to store the linked list inside our big continuous memory and whenever i try to do it on the the middle of the bloc i got a segment core dump.
Here is my code :
  char mem_heap[HEAP_SIZE]; //allocated the big continuous memory block
  //HEAP_SIZE = 1<<20

  typedef struct fb1 {   //The linked list structure
     size_t size ;
     struct fb *next ;
  }fb ,*pfb;

  pfb liste ; // a pointer to the linked list

  void mem_init(){  // function which initialize the linked list

      pfb newlist = (pfb) mem_heap ;

      newlist->next = NULL ;
      newlist->size = HEAP_SIZE  ;
      liste = newlist ;
    }

//test of a function which try to free a block of memory located at the
// memory address zone and of size size.
void mem_free(void *zone, size_t size){

  pfb tmp = (pfb) zone ;
  tmp->size = size ;
  tmp->next = liste ;

}

the line tmp->size produce a segment core dump error.
I don't know why it is working at initialization and not here


text:
Q: Make a MustOverride (abstract) member with EF 4? I have an abstract class Contact.
It leads to two subclasses:

*

*Company (Title)

*Person (FirstName, LastName)

I want to add a computed 'Title' col in the Person table, that return FirstName + ' ' + LastName, which will give me better search options.
So I want to create the Contact table have an abstract property Title, which each of these two implements, and so, I will be able to use:
Dim contacts = From c In context.Contacts
               Where c.Title.Contains("Nash")

I am pretty sure this is impossible, the question is what is the efficient alternative way?
In my scenario I have a ListBox showing all the Contacts of both Company and Person types, I have a search TextBox and I want the Service query (GetContacts(searchQuery As String)) to query the filtered set against the DB.
Update
After Will's answer, I decided to create in the Person table a computed col as above.
The question is what what be the most efficient way to imlpement the WCF-RIA query method:
Public Function GetContacts(searchQuery As String) As IQueryable(Of Contact)
  'Do here whatever it takes to retieve from Contacts + People
  'and mix the results of both tables ordered by Title
End Function

A: Unfortunately, while there is a way to do this with partial classes, I am 99% sure you cannot mix linq queries that touch entity properties and "POCO" properties defined in a partial class.
The Linq to Entity context will actually convert these queries to sql, and it cannot handle situations where a particular method isn't directly supported by the context.  A common example for L2E is the inability to use enums in your query.  Like knowing how to handle enums, the context certainly doesn't know how to handle your POCO properties when converting to raw sql.
An option you might want to investigate is to create a the computed column within your database, or to run your queries, do the traditional ToArray() in order to trigger enumeration, and then examine the computed column in memory.  This might not be a good solution, depending on the size of your table, however.

So, essentially, you wish to search two disparate types (backed by two different tables) and then combine the results for display to the user.
I would have to say that polymorphism is NOT the best solution.  The desire to show them in the UI shouldn't force a design decision all the way down into your type definitions.
I have done something similar a few times before in WPF.  I've done it two ways; by using polymorphism in the form of facade types which wrap the models and which can be treated by a common base type, and by treating all the different types in the collection as System.Object.
The first way is okay when you need type safety and the ability to treat different types the same way.  The wrappers extend a common base class and are coded to "know" how to handle each of their wrapped types correctly.
The second way is okay when you don't need type safety, such as when exposing a collection to a WPF View where you are displaying them in an ItemsControl, which can figure out the correct DataTemplate to use by the type of each instance in the collection.
I'm not sure which way is best for you, but whichever it is, you should query both your Company and Person tables separately, Union the two result sets, then sort them appropriately.
Pseudocode:
//Wrapper version
var results  = Company
               .Where(x=>x.Title.Contains(searchTerm))
               .Select(x=> new CompanyWrapper(x))
               Cast<BaseWrapper>().Union(
                  Person
                      .Where(x=>x.ComputedTitle.Contains(searchTerm))
                      .Select(x=> new PersonWrapper(x))
                      .Cast<BaseWrapper>());

//System.Object version
var results  = Company
               .Where(x=>x.Title.Contains(searchTerm))
               Cast<object>().Union(
                  Person
                      .Where(x=>x.ComputedTitle.Contains(searchTerm))
                      .Cast<object>());

In both cases, you may not have to downcast specifically.  Again, the first gives you type safety if you need it in the UI, the second is simpler and requires less code on the backend but is only useful if you don't require type safety in the UI.
As for sorting, once you've searched and combined your result, you can OrderBy to sort the result, however you will have to provide a function which can perform the ordering.  This function will differ depending on which version you choose.


text:
Q: Find the least number b for divisibility What is the smallest positive integer $b$ so that 2014 divides $5991b + 289$?
I just need hints--I am thinking modular arithmetic?
This question was supposed to be solvable in 10 minutes...

A: Using the Extended Euclidean Algorithm as implemented in the Euclid-Wallis Algorithm:
$$
\begin{array}{r}
&&2&1&38&2&25\\\hline
1&0&1&-1&39&-79&2014\\
0&1&-2&3&-116&235&-5991\\
5991&2014&1963&51&25&1&0\\
\end{array}
$$
Therefore, $2014\cdot235-5991\cdot79=1\implies5991\cdot79+1\equiv0\pmod{2014}$.
Multiply the last equivalence by $289$ to get the equivalence
$$
5991\cdot b+289\equiv0\pmod{2014}
$$
for $b\equiv289\cdot79\pmod{2014}$.

A: As 2014 divides the expression we have
$$5991b+289=0 \pmod {2014}$$
$$5991b=1725 \pmod { 2014}$$
Now as you said you only want hint you just need to find modulo inverse of 5991 $\pmod{2014}$ and multiply both sides to get $b$. ( Note as 5991 and 2014 are co-prime the inverse modulo of 5991 $\pmod{2014}$ exists). Also If you are new to modular arithmetic then look up modulo inverse, when it exists and extended euclid gcd method to find it. Hope it helps.

A: ${\rm mod}\ 2014\!:\ b\equiv \dfrac{-289}{5991}\overset{\large\frown}\equiv\dfrac{0}{2014}\overset{\large\frown}\equiv\dfrac{-289}{-51}\overset{\large\frown}\equiv\dfrac{813}{25}\overset{\large\frown}\equiv\dfrac{-677}{-1}\ $ by fractional ext. Euclidean.


text:
Q: Fill a GridLayout in Java with Objects from a 2DArray? I am learning Java and am trying to implement MineSweeper as a learning experience. I've got most of the logic working, but I am running into trouble with my recursive checkMine() method. I think the problem is my understanding, or misunderstanding rather, of how the GridLayout interacts with 2D arrays.
What I need to be able to do is to construct a 2D array full of Mines--which are an object extending JButton--and assign each element of the array to its own GridLayout location. Currently, I have the game working, but the numbers are not displaying the correct number of bombs, and I believe after debugging this could only be an issue with my implementation of the 2D Array with the GridLayout.
QUESTION: Is it possible to fill a GridLayout with individual elements of a 2D array? If not, what would be the best way for me to do this?

A: dAssuming your class extends java.applet.Applet
// Columns, Rows
Mines[][] mineGrid;

// Add stuff to the `mineGrid` array

// Set the height to the number of rows, length to number of columns
setLayout(new GridLayout(mineGrid.length, mineGrid[0].length);
// For each row
for(int rowIndex = 0; rowIndex < mineGrid.length; rowIndex++) {
    // For each column
    for(int colIndex = 0; colIndex < mineGrid[0].length; colIndex++) {
        // Add the button, because of GridLayout it starts @ the top row, goes across left to right, down a row, across left to right, etc.
        add(mineGrid[rowIndex][colIndex];
    }
}


text:
Q: Keras - combine multiple model into one model and use predict_prob to calculate variance I'm using Keras and built 5 different models for binary classification. on each model, I'm using the predict_proba to get the probability of the classification.
The 5 models are logistic regression:
def build_logistic_model(input_dim, output_dim):
    model = Sequential()
    model.add(Embedding(input_dim, embed, input_length=max_length))
    model.add(Flatten())
    model.add(Dense(output_dim, input_dim=embed, activation='softmax'))

so, now I have a list of 5 models. and I want to merge the output of those model into a new Keras model and to get out the AVG and STD of the probability of those 5 models.
is there a way to do it so, in the end, I will get 1 model that merge into him those 5 models? I will send input to those 5 models and will get the avg and std?

A: You can create a new model like that:
from keras import backend as K

def std_layer(input):
    return K.std(input)

model_input = Input(shape=input_dim)

def get_avg_std_model(models, model_input):

    outputs = [model.outputs[0] for model in models]
    avg = Average()(outputs)
    a = Concatenate()(outputs)
    std = Lambda(std_layer)(a)
    model = Model(model_input, [avg, std], name='get_avg_std')

    return model

models = [model1 , model2, model3, model4, model5]

get_avg_std = get_avg_std_model(models, model_input)

You will need to define all your models like that :
model_input = Input(shape=input_dim)

def model_example(model_input):

    x = Dense(1)(model_input)

    model1 = Model(inputs=model_input, outputs=x)

    return model

model1 = model_example(model_input)
model1.compile(optimizer='adadelta', loss='mse')

All that should gives you what you need !
Keep me in touch.


text:
Q: How to create a tree-like structure from a JavaScript Object This is the Object sample I'm given:
Input :

{
      "People": [
          {
              "id": "12",
              "parentId": "0",
              "text": "Man",
              "level": "1",
              "children": null
          },
          {
              "id": "6",
              "parentId": "12",
              "text": "Boy",
              "level": "2",
              "children": null
          },
                  {
              "id": "7",
              "parentId": "12",
              "text": "Other",
              "level": "2",
              "children": null
          },
          {
              "id": "9",
              "parentId": "0",
              "text": "Woman",
              "level": "1",
              "children": null
          },
          {
              "id": "11",
              "parentId": "9",
              "text": "Girl",
              "level": "2",
              "children": null
          }
      ] }

I want to transform it to a JSON format like this:
{
    "People": [
        {
            "id": "12",
            "parentId": "0",
            "text": "Man",
            "level": "1",
            "children": [
                {
                    "id": "6",
                    "parentId": "12",
                    "text": "Boy",
                    "level": "2",
                    "children": null
                },
                {
                    "id": "7",
                    "parentId": "12",
                    "text": "Other",
                    "level": "2",
                    "children": null
                }
            ]
        }
}

Any Ideas/Help would be appreciated

A: You could use an object for the reference to either child or parent and collect the children and parents to get only the person for the root.

var data = { John: "James", Samar: "Michel", Albert: "Michel", Michel: "James", James: "Sarah" },
    parents = new Set,
    children = new Set,
    references = {},
    result;

Object
    .entries(data)
    .forEach(([child, parent]) => {
        references[child] = references[child] || [];
        references[parent] = references[parent] || [];
        references[parent].push({ [child]: references[child] });
        parents.add(parent);
        children.add(child);
    });

result = [...parents]
    .filter(p => !children.has(p))
    .map(p => ({ [p]: references[p] }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: OMG this seemingly simple stuff took so long

const users = {
        "John": "James",
        "Samar": "Michel",
        "Albert": "Michel",
        "Michel": "James",
        "James": "Sarah"
    }

    const findRoots = () => Object.keys(users).filter(k => !(users[k] in users)).map(k => users[k])

    const findSubordinates = (boss) => Object.keys(users).filter(k => users[k] === boss)

    const traverseBoss = (boss) => {
        let subs = findSubordinates(boss)

        let subsCollection = []

        subs.forEach(s => {
            subsCollection.push({
                [s]: traverseBoss(s)
            })
        })

        return subsCollection
    }

    const result = {}
    findRoots().forEach(root => result[root] = traverseBoss(root))

    console.log(result)


text:
Q: Idiomatic way of branching json parsing in kotlin Let's say that we have a JsonNode object jsonNodeObj that needs to be parsed to one of multiple classes ClassA, ClassB, ClassC, etc. I could do the following (couldn't be more ugly):
val mapper = ObjectMapper()
try {
  mapper.treeToValue(jsonNodeObj, ClassA::class.java)
} catch (e1: Exception) {
  try {
    mapper.treeToValue(jsonNodeObj, ClassB::class.java)
  } catch (e2: Exception) {
    try {
      mapper.treeToValue(jsonNodeObj, ClassC::class.java)
    } catch (e3: Exception) {
      ...
    }
  }
}

Is there a better way like using when somehow?

A: There is definitely a better way to do this. You can define a function that returns true on success and false on exception like so:
inline fun <reified T : Any> ObjectMapper.treeToValueOrNull<T>(node : TreeNode) : T?
    = try { treeToValue(node, T::class.java) }
    catch (ex : Exception) { null }

This works because in Kotlin try-catch-statements can have a return value. Now, you can use when to process the json:
lateinit var object : Any
when {
    mapper.treeToValueOrNull<ClassA>(jsonNodeObj)?.let { object = it } != null
        -> dosthA(object as ClassA)
    mapper.treeToValueOrNull<ClassB>(jsonNodeObj)?.let { object = it } != null
        -> dosthB(object as ClassB)
    mapper.treeToValueOrNull<ClassC>(jsonNodeObj)?.let { object = it } != null
        -> dosthC(object as ClassC)
}

pdvrieze found an even shorter solution:
val object = mapper.treeToValueOrNull<ClassA>(jsonNodeObj)
          ?: mapper.treeToValueOrNull<ClassB>(jsonNodeObj)
          ?: mapper.treeToValueOrNull<ClassC>(jsonNodeObj)


text:
Q: Cannot import tensorflow in Spyder but it imports in python I installed  Anaconda on my machine and created a separate environment for tensorflow. Installed tensorflow and keras ok but both packages cannot be imported. The error is:
In [1]: import tensorflow
Traceback (most recent call last):

  File "<ipython-input-1-88d96843a926>", line 1, in <module>
    import tensorflow

ModuleNotFoundError: No module named 'tensorflow'

Dependencies that were installed during the install like scipy and yaml can be imported.
When I run python3 from the command line I can import keras and tensorflow correctly. This fails when I try to import tensorflow in Spyder.
I rebooted, uninstalled and installed again. I am sure that I am in the correct environment. Does somebody know what I do wrong?


text:
Q: chatter feeds: identify concrete system generated updates on accounts feed I want to identify some chatter system generated updates (on accounts feed) which appear on screen with an specific title (i.e. You don't have permission to view this task) in order to be able to delete them.
In order to do this, I tried to run some queries on developer console, both on AccountFeed object and FeedItem object. When I run he queries, I get some interesting information, but all the fields like title, content ... are just empty.
Find some example queries below:
SELECT Id, Body, CommentCount, ContentData, ContentDescription, ContentFileName, ContentSize, ContentType, CreatedById, CreatedDate, InsertedById, IsDeleted, LastModifiedDate, LikeCount, LinkUrl, ParentId, RelatedRecordId, SystemModstamp, Title, Type FROM FeedItem

SELECT Id,Body, ParentId, ContentData, CommentCount, ContentDescription, ContentFileName, ContentSize, CreatedById, CreatedDate, InsertedById, IsDeleted, LastModifiedDate, LikeCount, LinkUrl, RelatedRecordId, SystemModstamp, Title, Type FROM AccountFeed

I would want to gather all the records with that specific text, but don't find how to filter them using SOQL.
Until now, I've been able to delete them filtering by account and then deleting each record using developer console.
What am I missing?
Thanks


text:
Q: .env with debugging breakpoint using vscode and dotenv npm I'm using a nodejs server side api, setting up environment variables with  dotenv  npm package, and running the code from npm scripts in package.json as below:
"scripts": {
   "local": "cross-env NODE_ENV=local nodemon ./bin/www"
}

What I need is to configure my .vscode/launch.json file.
Currently it looks like:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": []
}

Kindly guide me. Thanks,
Gopal.R

*

*dotenv npm package

*Visual Studio Code - Launch configurations

A: I had the same question for typescript debugging and I found answer here. Need to specify runtimeArgs and envFile parameters to make it work.
Example of launch.json for TypeScript debugging:
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}/src/server.ts",
            "preLaunchTask": "tsc: build - tsconfig.json",
            "outFiles": [
                "${workspaceFolder}/built/**/*.js"
            ],
            "runtimeArgs": [
                "--require=dotenv/config"
            ],
            "envFile": "${workspaceFolder}/.env"
        }
    ]
}

A: You would want to set the .dotenv environmental variable up like:
NODE_ENV=local

Then to require it in your debugger, you would want to add it into your launch.json configurations like:
"runtimeArgs": [
    "--require=dotenv/config"
]

Here it is in context:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch | local with dotenv config",
            "program": "${workspaceFolder}/bin/www/your_script.js",
            "runtimeArgs": [
                "--require=dotenv/config"
            ]
        }
    ]
}

--require=dotenv/config is the equivalent of running require('dotenv').config() in your script or node -r dotenv/config your_script.js if you're using the command line.
Here are some alternate examples of where environmental variables can be placed in the config.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch | local using env file",
            "program": "${workspaceFolder}/bin/www/your_script.js",
            "envFile": "${workspaceFolder}/.env"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "Launch | local without dotenv",
            "program": "${workspaceFolder}/bin/www/your_script.js",
            "env" : {
                "NODE_ENV" : "local"
            }
        }
    ]
}

Note: This code hasn't been tested... so feedback is welcome.


text:
Q: Sorting a ListView using an ObjectDataSource with a LinkButton and ViewState I am using a ListView to display paginated data:
<asp:ListView ID="listOfItems" runat="server" DataSourceID="ItemsDataSource" EnableModelValidation="True" InsertItemPosition="FirstItem" ItemPlaceholderID="ItemRowContainer">
    <LayoutTemplate>

                <custom:TablePaginationControl ID="TablePaginationControl1" runat="server" ControlID="listOfItems" ShowPageSizeList="true" />

                        <asp:LinkButton ID="SortByName" runat="server" CommandArgument="Name" CommandName="SortMainList" OnCommand="SortItems" Text="<%$ Resources:Name %>"></asp:LinkButton>

                    ...

    </LayoutTemplate>
    ...
</asp:ListView>

The datasource definition:
<asp:ObjectDataSource ID="ItemsDataSource" runat="server" EnablePaging="True" InsertMethod="AddItems" SelectCountMethod="SelectItemsCount" SelectMethod="SelectItems" TypeName="SHLCentral.TheLibrary.Web.View.DocumentManagementControl, ClientPortal.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cd2852a10d692fb9" UpdateMethod="UpdateItems">
    ...
</asp:ObjectDataSource>

The revelant code behind is made of these two methods:
public IEnumerable<ListDocumentsResult> SelectItems(
    int maximumRows,
    int startRowIndex)
{
    var results = Controller.ListDocuments(new ListDocumentsRequest());

    PropertyInfo sortProperty;
    try
    {
        sortProperty = typeof (ListDocumentsResult).GetProperty((string) ViewState["mainListSortColumn"]);
    }
    catch
    {
        sortProperty = null;
    }
    Func<ListDocumentsResult, object> sortFunction = sortProperty == null
                            ? (Func<ListDocumentsResult, object>) (ldr => ldr.LastUpdatedDate)
                            : (ldr => sortProperty.GetValue(ldr, new object[0]));

    return
        (sortProperty == null || !((bool) ViewState["mainListSortAsc"])
             ? results.OrderByDescending(sortFunction)
             : results.OrderBy(sortFunction))
            .Skip(startRowIndex)
            .Take(maximumRows);
}

protected void SortItems(object sender, CommandEventArgs e)
{
    if (e.CommandName == "SortMainList")
    {
        var sortColumn = (string) e.CommandArgument;
        if ((string)ViewState["mainListSortColumn"] == sortColumn)
        {
            ViewState["mainListSortAsc"] = !(bool)ViewState["mainListSortAsc"];
        }
        else
        {
            ViewState["mainListSortAsc"] = true;
            ViewState["mainListSortColumn"] = sortColumn;
        }
        DataBind();
    }
}

So my intention this: when the users clicks on the LinkButton contained in the "Name" column header (I left out all but one column for clarity), the SortItems method is called: it sets the sorted column name and sort order into the ViewState, then reloads the ListView using the DataBind method. In the Select method of the ObjectDataSource, we read this ViewState values and use them to order the data.
Putting breakpoints on all these methods, I can see there is this sequence of calls when I click the LinkButton:

*

*OnLoad

*SortItems

*SelectItems
The problem I have is that when I get to the SelectItems method, the ViewState is totally empty (it has 0 keys): if I set a breakpoint on the Load method of the page, I see the control containing all this is only loaded once. The DataBind method does not seem to trigger any loading of the control, it seems to be just triggering the SelectItems method of a new instance of the control (meaning that if, instead of using ViewState, I set an instance field in the SortItems method, the field is null when getting in the SelectItems method).
I am sure that the ViewState is active on the page (I can find the ViewState keys on the browser side using a Firefox extension for instance).
There is something not quite clear to me about the life cycle of the page/control. Could someone explain what it is to me?

A: There exist much, much simpler approach.
First, instead of a custom CommandName, you put a built-in name into the sort link button. The name is Sort.
You have then
   <asp:LinkButton ID="SortByName" runat="server" CommandArgument="Name" CommandName="Sort" />

Then, on your ObjectDataSource you add the SortParameterName to be something like OrderBy:
   <ObjectDataSource .... SortParameterName="OrderBy" />

Then you modify your data provider method to be:
 public IEnumerable<ListDocumentsResult> SelectItems(
   string OrderBy,
   int maximumRows,
   int startRowIndex)

The data source will provide the value automatically based on the command argument (Name) and it will automatically append DESC whenever you click the command button for the second time (it is because the ListView persists the state of sort order in its viewstate automatically, you don't have to reinvent this!)
Then, you don't need this ugly delegates to order by strings for linq. Instead, download the Dynamic Linq library:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
find the Dynamic.cs file, include it in your project and it will add a bunch of additional linq operators, including the OrderBy which accepts strings and which automatically supports DESC (!).
You then just
 public IEnumerable<ListDocumentsResult> SelectItems(
   string OrderBy,
   int maximumRows,
   int startRowIndex)
 {

     Controller.ListDocuments(new ListDocumentsRequest())
        .OrderBy(OrderBy)
        .Skip(startRowIndex)
        .Take(maximumRows);
 }

This is just as simple!
Be warned though that there's a small bug (or an inconvenience) in the dynamic linq - it throws an exception when the sort order is empty.
Find then this code (line 47 and down)
    public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) {
        if (source == null) throw new ArgumentNullException("source");
        if (ordering == null) throw new ArgumentNullException("ordering");

and change it manually to
    public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) {
        if ( string.IsNullOrEmpty( ordering ) ) return source;
        if (source == null) throw new ArgumentNullException("source");
        if (ordering == null) throw new ArgumentNullException("ordering");

Done.

A: If the SelectMethod is not static, the ObjectDataSource control will create a new instance of the type specified in TypeName and call the method on that instance.
You either need to add a parameter for the sort expression to your select method and set the SortParameterName property on the ObjectDataSource, or you need to handle the ObjectCreating event and set the ObjectInstance to the existing control instance.


text:
Q: How do I get a collection object in pyarango? I can get a database object with the code:
import pyArango.database as DAT
db = DAT.Database(connection, dbName)

and according to the documentation, I can get a collection with the code:
import pyArango.collection as COL
collection = COL.Collection(database, jsonData)

How do I format jsonData to return my collection? I could not find how to do this in the documentation. My collection has name="testCollection"
Thanks!

A: I believe I figured it out. Collections should be instantiated by the database object, which is instantiated by the connection object.
import pyArango.connection as CON
db = CON.Connection(username=<user>, password=<password>).databases[<DB name>]
collection = db.collections['testCollection']

This works as intended, and returns:
ArangoDB collection name: testCollection, id: 14217, type: document, status: loaded


text:
Q: Trying to send b64encoded PNG image to JavaScript client via asyncio websockets server using Python I am trying to send a base64 encoded PNG images to a JavaScript client via asyncio websockets server in python. Right now I am just looping through images from memory to create a "video player" on the JavaScript side and its working... however, the first image that comes through throws a RuntimeError on my python server. it then operates as expected so very hard to pinpoint the problem..
ERROR:asyncio:Task exception was never retrieved
future: <Task finished coro=<WebSocketCommonProtocol.send() done, defined at /usr/local/lib/python3.7/dist-packages/websockets/protocol.py:521> exception=RuntimeError('Task <Task pending coro=<WebSocketCommonProtocol.send() running at /usr/local/lib/python3.7/dist-packages/websockets/protocol.py:567> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.7/asyncio/tasks.py:440] created at /usr/lib/python3.7/asyncio/tasks.py:361> got Future <Future pending> attached to a different loop') created at /usr/lib/python3.7/asyncio/tasks.py:361>
source_traceback: Object created at (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 885, in _bootstrap
    self._bootstrap_inner()
  File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "../comm/mqtt.py", line 320, in __process_messages
    response_data = self._msg_callback_dispatch[t](in_msg.body)
  File "SiteManagerOp.py", line 385, in on_image_callback
    coro = asyncio.run(self.tx_UI_device_image(data.get('did'), data.get('img')), debug=True)
  File "/usr/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.7/asyncio/base_events.py", line 571, in run_until_complete
    self.run_forever()
  File "/usr/lib/python3.7/asyncio/base_events.py", line 539, in run_forever
    self._run_once()
  File "/usr/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once
    handle._run()
  File "/usr/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "Manager.py", line 181, in tx_UI_device_image
    await self.sockserver.send_to_clients(json.dumps(img_msg))
  File "/home/mendel/webserver/SocketServer.py", line 39, in send_to_clients
    await asyncio.wait([client.send(message) for client in self.clients])
  File "/usr/lib/python3.7/asyncio/tasks.py", line 361, in wait
    fs = {ensure_future(f, loop=loop) for f in set(fs)}
  File "/usr/lib/python3.7/asyncio/tasks.py", line 361, in <setcomp>
    fs = {ensure_future(f, loop=loop) for f in set(fs)}
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/websockets/protocol.py", line 567, in send
    await self.write_frame(True, opcode, data)
  File "/usr/local/lib/python3.7/dist-packages/websockets/protocol.py", line 1077, in write_frame
    await self._drain()
  File "/usr/local/lib/python3.7/dist-packages/websockets/protocol.py", line 318, in _drain
    await self._drain_helper()
  File "/usr/local/lib/python3.7/dist-packages/websockets/protocol.py", line 299, in _drain_helper
    await waiter
RuntimeError: Task <Task pending coro=<WebSocketCommonProtocol.send() running at /usr/local/lib/python3.7/dist-packages/websockets/protocol.py:567> cb=[_wait.<locals>._on_completion() at /usr/lib/python3.7/asyncio/tasks.py:440] created at /usr/lib/python3.7/asyncio/tasks.py:361> got Future <Future pending> attached to a different loop

Python Code:
#storing images to memory..
img_data = []
i=1
while i < 300:
    with open(f"pngs/out{i}.png", "rb") as f:
        img_data.append(base64.b64encode(f.read()).decode('utf-8'))
        i+=1

#non-async call back for recieving images
def on_image_callback(self, data=None):
    print (f"rx image:", data.get('did'))
    coro = asyncio.run(self.tx_UI_device_image(data.get('did'), data.get('img')), debug=True)

#async initiates send_to_client as JSON payload..
async def tx_UI_device_image(self, did, img):
    img_msg = {'image':{'did':did, 'img_data':img}}
    print ("img size: ", len(img))
    await self.sockserver.send_to_clients(json.dumps(img_msg))

#socket server handler...
class WebsocketServer:
    def __init__(self, host, port, onconnect_callback, rxdata_callback):
        self.start_server = websockets.serve(self.ws_handler, host, port)
        self.loop = asyncio.get_event_loop()
        self.onconnect = onconnect_callback
        self.ondata_Rx = rxdata_callback
        self.clients = set()

    def start(self):
        self.loop.run_until_complete(self.start_server)
        self.loop.run_forever()

    async def register(self, ws: WebSocketServerProtocol) -> None:
        self.clients.add(ws)
        logging.info(f'{ws.remote_address} connects.')
        await self.onconnect()

    async def unregister(self, ws: WebSocketServerProtocol) -> None:
        self.clients.remove(ws)
        logging.info(f'{ws.remote_address} disconnects.')

    async def send_to_clients(self, message: str) -> None:
        if self.clients:
            await asyncio.wait([client.send(message) for client in self.clients])

    async def ws_handler(self, ws: WebSocketServerProtocol, uri: str) -> None:
        await self.register(ws)
        try:
            await self.distribute(ws)
        finally:
            await self.unregister(ws)

    async def distribute(self, ws: WebSocketServerProtocol) -> None:
        async for message in ws:
            await self.ondata_Rx(json.loads(message))

JavaScript:
s.onmessage = function(e) {
    //console.log("got: " + e.data);
    var data = JSON.parse(e.data);
    for (var key in data) {
      if (data.hasOwnProperty(key)) { // this will check if key is owned by data object and not by any of it's ancestors
        if (key == "image"){
          console.log(data[key].did);
          var image = new Image();
          image.src =('data:image/png;base64,' + data[key].img_data);

          var player = document.getElementById(data[key].did + '-player');
          player.setAttribute('src', image.src)
        }
    }
}

I believe the problem is the asyncio.run call in a different thread affecting the event_loop or creating a new one rather, but I can't find any other way around this. It works with a much smaller message payload or if i just send a bunch of chars like ('A' * 300000)
What is causing this error and how do I resolve or workaround?
UPDATE: Found Solution
instead of calling asyncio.run() anytime i needed to call something outside of an async function - I used asyncio.run_coroutine_threadsafe(<coroutine>, loop=self.socketserver.loop)

A: Instead of calling asyncio.run() anytime you call something outside of an async function (or i.e in a different thread) - use this instead and specify the event loop you want to target:
asyncio.run_coroutine_threadsafe(<coroutine>, loop=self.socketserver.loop)


text:
Q: Issue with Yii's listData I have a model called managers, I want to create a drop down list that pulls the managers names based on the managers id. I am using the code below
echo $form->dropDownList
(
  $model,'country',
  CHtml::listData(Country::model()->findAll(), 'id', 'value1','value2'),
  array('empty'=>;'--please select--')
);

The drop down list actually gives me the desired names('value') but wont display the default empty array value, how can I get the 'please select' bit displaying?

A: echo $form->dropDownList
(
  $model,'country',
  CHtml::listData(Country::model()->findAll(), 'id', 'value1','value2'),
  array('prompt'=>'--please select--')
);

The prompt keyword should do the trick.  That's how I display it.


text:
Q: How do I get the value of clustered record with Weka in Java?                         Cluster
Attribute                     0         1         2

C_AGE
  mean                   28.7493   36.4999   61.6494
  std. dev.               9.0175    4.3302    25.745

C_BIRTH_MONTH
  June                         9         1         1
  May                     4.9999    5.0001         1
  January                 4.9999         1    1.0001
  July                    3.5588         1    2.4412
  April                        1         1         5
  [total]                23.5587    9.0001   10.4412

This is the output I got from the Weka Java API, I wonder is it possible to obtain the value of the attribute from the clusters? eg: getting 28.7493 from cluster 0 in Java.

A: I am assuming here that you are using the EM Clustering Algorithm here.
You could use the EM.GetClusterModelsNumericAtts() function to obtain the mean and standard deviation information.
Hope this helps!


text:
Q: How is named credentials & auth provider with connected app used? Can i have scenario where it is needed? I have seen people use auth. providers that has client secret and id of connected app and authenticated using named credentials. The named credentials stores the oauth refresh token but I am not getting why this flow is needed or what do we gain here.
All suggestions appreciated.

A: From the Named Credentials documentation, an important summary:

By separating the endpoint URL and authentication from the callout definition, named credentials make callouts easier to maintain. For example, if an endpoint URL changes, you update only the named credential. All callouts that reference the named credential simply continue to work.

Named Credentials insulate your code from specific endpoint URLs and from authentication details, and also provide secure storage for secret authentication parameters. The latter is a capability that is otherwise only possible by using a Protected Custom Setting in a managed package, which not every org has the capacity or inclination to do. Otherwise, you're stuck with storing highly sensitive authentication parameters, such as OAuth refresh tokens, in locations where anyone with View Setup and Configuration permission can get at them. Named Credentials makes that security problem go away.
Put shortly, they abstract away a lot of complex, difficult, and risky (from a security standpoint) implementation details so that your code doesn't have to handle them, and they improve the maintainability and security of your outbound connections.

A: I have written an article on why and how to use this with Google API! No need for an Auth handler apex class or visualforce page. Everything is handled by Salesforce. You don't have to bother with authentication.
https://medium.com/@ennoucas/working-with-salesforce-named-credentials-example-with-google-calendar-api-61fa6588167a


text:
Q: Testing after_create hooks with rspec I have code in my model (RoR 3.0.x) that is more or less like this:
class Message

    after_create :notify

    protected

    def notify
        if visible?
            Notifier.message_from_portfolio( user, self ).deliver
        else
            Notifier.invisible_message_from_portfolio( user, self ).deliver
        end
    end

end

And I'm using the latest rspec gem to test it.
The problem is that I'm not able to test the notify method: if I test it directly I can't because it's protected, if I create a message and set expectations it doesn't work because apparently even though rspec runs the notify metod I'm not able to catch the calls in time.
My spec is:
describe :notification do
    it "should send the whole message by email when visible" do
        u = Factory.create( :user, :account_type => 1 )
        message = u.messages.build( :body => "Whatever", :author => "Nobody", :email => "test@example.com" )
        Notifier.should_receive( :message_from_portfolio )
        message.save
    end
end

The object Notifier never receives message_from_portfolio. What am I doing wrong? Suggestions?

A: Factory.create has already saved message, so it is not being created, just saved. Substitute it with Factory.build and all should be fine.

A: Are you sure the callback is being reached? after_create doesn't get executed if the instance is invalid.
You could set an expectation for debugging purposes:
message.should_receive(:after_create)

Or maybe visible? returns false? To check for that you could use a negative expectation:
Notifier.should_not_receive(:invisible_message_from_portfolio)


text:
Q: I have executed a node js server on cPanel, it is succefully executing but still my server is not accessible using public IP address of my server I have executed a nodejs server on port 8080 on cPanel using SSH access.
I have provided public IP address of my server as a host name for node js server.
But still I m not able to access the server by entering the public IP address and port number in browser URL.

Code:
 'use strict';
  const Hapi = require('hapi');
  const server = Hapi.server({
  port: 8080,
  host: '1.1.1.1' //servers public IP adrress
  });
  server.route({
    method: 'GET',
    path: '/',
    handler: (request, h) => {
      return 'Hello, world!';
      }
    });

  const init = async () => {
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
  };
  process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
  });

init();

A: I have solved this problem.
The problem was the port on which I was trying to run this application was not open to outside accessors.
I contacted to support team of cloud server on which I have deployed my application, and then they have opened the port.
And after opening the port now it is accessible to outside accessors.
Thank you for your time and efforts.


text:
Q: How to append an element loaded via ajax to another previously loaded via ajax? How can I add an HTML element received via AJAX to another HTML element previously added via AJAX? I tried to use .append but not working:
Example:
$.ajax({ (...), success: function() { $('.padding').append('
Foo
') } });

This above working well, because .padding is initially loaded on the page. But when I try
$.ajax({ (...), success: function(data) { $('#request').append('
Bar
') } });

not working. Why and how can I do it the right way?
Below, my .padding content:

 P2017003

                <button class="ui button">

                    Voltar
                </button>

                    <button id="detalhes" class="ui active button">
                        Detalhes
                    </button>
                    <button id="acompanhar" class="ui button">
                        Acompanhar
                    </button>

                <button class="ui button">Imprimir</button>

            P-2017-003

A: I've rigged up this setup to simulate your situation. I've never once encountered the situation where the div with id request is not present in the DOM.

function getDataA() {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts/1'
  }).then(result => {
    $('.padding').append('
Call A finished
');
  });
}

function getDataB() {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts/2'
  }).then(result => {
    if ($('#request').length === 0) {
      console.log('no request element found');
    }
    $('#request').append('
Call B finished
');
  });
}

getDataA()
  .then(getDataB);

My guess is your second call is done before the first call. Perhaps your code is something like this:
getDataA();
getDataB();

Now you're depending on which call finishes first. When call B finishes first your code breaks and when call A finishes first you're in luck.
You could run both requests in parallel if you want, it will require using $.when().

function getDataA() {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts/1'
  });
}

function getDataB() {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts/2'
  });
}

$.when(getDataA(), getDataB())
  .then(function(resultA, resultB) {
    $('.padding').append('
Call A finished
');
    $('#request').append('
Call B finished
');
  });

I've tried it with your provided HTML and I still am not able to reproduce the situation.

function getDataA() {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts/1'
  }).then(result => {
    $('.padding').append(`

 P2017003

                <button class="ui button">

                    Voltar
                </button>

                    <button id="detalhes" class="ui active button">
                        Detalhes
                    </button>
                    <button id="acompanhar" class="ui button">
                        Acompanhar
                    </button>

                <button class="ui button">Imprimir</button>

            P-2017-003

    `);
    const
      trigger = document.getElementById('detalhes');
    trigger.addEventListener('click', getDataB);
  });
}

function getDataB() {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/posts/2'
  }).then(result => {
    if ($('#request').length === 0) {
      console.log('no request element found');
    }
    $('#request').append('
Call B finished
');
  });
}

const
  trigger = document.getElementById('fill-padding');
trigger.addEventListener('click', getDataA);

<button id="fill-padding" type="button">Fill padding</button>

A: So, the issue is that jQuery hasn't update it's internal structures yet.
Sometimes this happens when appending elements, and trying to find them right away.
Instead do one of the 3:

*

*Use jQuery.find() instead (eg: $("body").find("#id"))

*Store the element html as a jQuery object:
var html = 'Hi';
var elem = $(html);

*"Accumulate' the html all at once, and append it all at once.
var html = '';
$.ajax({ (...), success: function() {
        html += 'Foo';
        $.ajax({ (...), success: function(data) {
                html += 'Bar';
                $('.padding').append(html);
            }
        });
    }
});


text:
Q: store procedure in trans sql vs pl sql In oracle (pl-sql) I have
s as (select * from ruleassigns$all where [snapshot] = p_Id);

inside a stored procedure. I want to port it into sql server (trans-sql), but when I write the same it gives me error on the structure of the statement. Please help!
I am wondering something like
declare @s = (select * from ruleassigns$all where [snapshot] = p_Id);

but that's not correct either.

A: Since this query is returning multiple values you'd probably want to use a Declare @table.
The syntax will be
Declare @s Table (p_id SomeDataType(probably int?))

You can use @s just like any other table.
SELECT * FROM @s

Note: I personally like the feel of temporary tables. They feel like normal tables.
You'd write:
CREATE TABLE #tableName (p_id SomeDataType)

and at the end of your SP you'd do DROP TABLE #tableName