问:
kdevtmpfsi using the entire CPU
We are using an EC2(Ubuntu) amazon instance for running Apache.Recently we noticed that there is a process using the entire CPU.

We removed it using the help of the following procedure

```<code>[root@hadoop002 tmp]# systemctl status 25177
● session-5772.scope - Session 5772 of user root
   Loaded: loaded (/run/systemd/system/session-5772.scope; static; vendor preset: disabled)
  Drop-In: /run/systemd/system/session-5772.scope.d
           └─50-After-systemd-logind\x2eservice.conf, 50-After-systemd-user-sessions\x2eservice.conf, 50-Description.conf, 50-SendSIGHUP.conf, 50-Slice.conf, 50-TasksMax.conf
   Active: active (abandoned) since Wed 2020-01-22 16:06:01 CST; 1h 21min ago
   CGroup: /user.slice/user-0.slice/session-5772.scope
           ├─19331 /var/tmp/kinsing
           └─25177 /tmp/kdevtmpfsi

Jan 22 16:06:17 hadoop002 crontab[19353]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19354]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19366]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19374]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19375]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19383]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19389]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19390]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19392]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19393]: (root) LIST (root)
[root@hadoop002 tmp]# ps -ef|grep kinsing
root     19331     1  0 16:06 ?        00:00:04 /var/tmp/kinsing
root     25190 23274  0 17:27 pts/0    00:00:00 grep --color=auto kinsing
[root@hadoop002 tmp]# ps -ef|grep kdevtmpfsi
root     25177     1 99 17:27 ?        00:01:47 /tmp/kdevtmpfsi
root     25197 23274  0 17:28 pts/0    00:00:00 grep --color=auto kdevtmpfsi
[root@hadoop002 tmp]# kill -9 19331
[root@hadoop002 tmp]# kill -9 25177
[root@hadoop002 tmp]# rm -rf kdevtmpfsi
[root@hadoop002 tmp]# cd /var/tmp/
[root@hadoop002 tmp]# ll
total 16692
-rw-r--r-- 1 root root        0 Jan 13 19:45 aliyun_assist_update.lock
-rwxr-xr-x 1 root root    13176 Dec 20 02:14 for
-rwxr-xr-x 1 root root 17072128 Jan 19 17:43 kinsing
drwx------ 3 root root     4096 Jan 13 19:50 systemd-private-f3342ea6023044bda27f0261d2582ea3-chronyd.service-O7aPIg
[root@hadoop002 tmp]# rm -rf kinsing
</code>```

But after a few minutes, It again started automatically. Anyone know how to fix this?

答:
The other answer here is good, and you should do everything mentioned there. But, if the thing keeps coming back, and/or you aren't actually using Docker, you probably have an unpatched RCE vulnerability in phpUnit. The details are here:

https://www.sourceclear.com/vulnerability-database/security/remote-code-execution-rce/php/sid-4487

Our situation was:

Docker is not being used at all.

We had removed all files related to the miner.

We had locked things down using the above touch and chmod commands.

The damn thing kept trying to run at seemingly random times.

After you've locked things down with the touch/chmod changes, it can't actually DO anything, but it's still annoying, and that phpUnit vulnerability is a HUGE hole that needs plugging anyway.

Hope this helps.

Title: kdevtmpfsi using the entire CPU

Body:
We are using an EC2(Ubuntu) amazon instance for running Apache.Recently we noticed that there is a process using the entire CPU.

We removed it using the help of the following procedure

[root@hadoop002 tmp]# systemctl status 25177
● session-5772.scope - Session 5772 of user root
   Loaded: loaded (/run/systemd/system/session-5772.scope; static; vendor preset: disabled)
  Drop-In: /run/systemd/system/session-5772.scope.d
           └─50-After-systemd-logind\x2eservice.conf, 50-After-systemd-user-sessions\x2eservice.conf, 50-Description.conf, 50-SendSIGHUP.conf, 50-Slice.conf, 50-TasksMax.conf
   Active: active (abandoned) since Wed 2020-01-22 16:06:01 CST; 1h 21min ago
   CGroup: /user.slice/user-0.slice/session-5772.scope
           ├─19331 /var/tmp/kinsing
           └─25177 /tmp/kdevtmpfsi

Jan 22 16:06:17 hadoop002 crontab[19353]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19354]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19366]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19374]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19375]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19383]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19389]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19390]: (root) LIST (root)
Jan 22 16:06:17 hadoop002 crontab[19392]: (root) REPLACE (root)
Jan 22 16:06:17 hadoop002 crontab[19393]: (root) LIST (root)
[root@hadoop002 tmp]# ps -ef|grep kinsing
root     19331     1  0 16:06 ?        00:00:04 /var/tmp/kinsing
root     25190 23274  0 17:27 pts/0    00:00:00 grep --color=auto kinsing
[root@hadoop002 tmp]# ps -ef|grep kdevtmpfsi
root     25177     1 99 17:27 ?        00:01:47 /tmp/kdevtmpfsi
root     25197 23274  0 17:28 pts/0    00:00:00 grep --color=auto kdevtmpfsi
[root@hadoop002 tmp]# kill -9 19331
[root@hadoop002 tmp]# kill -9 25177
[root@hadoop002 tmp]# rm -rf kdevtmpfsi
[root@hadoop002 tmp]# cd /var/tmp/
[root@hadoop002 tmp]# ll
total 16692
-rw-r--r-- 1 root root        0 Jan 13 19:45 aliyun_assist_update.lock
-rwxr-xr-x 1 root root    13176 Dec 20 02:14 for
-rwxr-xr-x 1 root root 17072128 Jan 19 17:43 kinsing
drwx------ 3 root root     4096 Jan 13 19:50 systemd-private-f3342ea6023044bda27f0261d2582ea3-chronyd.service-O7aPIg
[root@hadoop002 tmp]# rm -rf kinsing

But after a few minutes, It again started automatically. Anyone know how to fix this?


来源: stackexchange

问:
IPC between a C DLL and Python application to process data
I would like to send over a message structure from a DLL-callback function to a python application so I can log the messages.

For this I would like to use ZeroMQ. Sadly I am unable to get the messages to python using the example provided by ZeroMQ.

DLL:

```<code>// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <zmq.h>
HHOOK tHook;
HMODULE hinstDLL;
void* requester;
void* context;
LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam) {
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        UINT message = data->message;
        switch (message)
        {
        case WM_POINTERUPDATE:
            if (!IS_POINTER_INCONTACT_WPARAM(wParam))
                break;
        case WM_POINTERDOWN:
        case WM_POINTERUP:
            POINTER_INFO pointerInfo = {};
            GetPointerInfo(GET_POINTERID_WPARAM(wParam), &pointerInfo);
            int request_nbr;
            for (request_nbr = 0; request_nbr != 10; request_nbr++) {
                char buffer[10];
                printf("Sending Hello %d…\n", request_nbr);
                zmq_send(requester, data, 5, 0);
                zmq_recv(requester, buffer, 10, 0);
                printf("Received World %d\n", request_nbr);
            }
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
extern "C" __declspec(dllexport) BOOL ConnectServer() {
    printf("Connecting to hello world server…\n");
    static void* context = zmq_ctx_new();
    static void* requester = zmq_socket(context, ZMQ_REQ);
    zmq_connect(requester, "tcp://127.0.0.1:5555");
    printf("connected");
    return TRUE;
}
extern "C" __declspec(dllexport) BOOL DisconnectServer() {
    zmq_close(requester);
    zmq_ctx_destroy(context);
    return TRUE;
}
extern "C" __declspec(dllexport) BOOL SetHook()
{
    tHook = SetWindowsHookEx(WH_GETMESSAGE, meconnect, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
</code>```

Python:

```<code>context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://127.0.0.1:5555")

def message_msg_loop():
    while True:
        #  Wait for next request from client
        message = socket.recv()
        print("Received request: %s" % message)

        #  Do some 'work'
        time.sleep(1)

        #  Send reply back to client
        socket.send(b"World")

def pointer_msg_loop():
    global lib
    lib = cdll.LoadLibrary(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\HOOKDLL.dll')
    print(lib)
    res = lib.ConnectServer()
    res = lib.SetHook()
    pythoncom.PumpMessages()
    res = lib.UnHook()
</code>```

Basically my plan was to detect a certain event through windows messages and pass the message structure from the DLL-callback over to the server in Python, so I can handle the data there and put them into a log file. It does not seem to work though.

答:
In case one has never worked with ZeroMQ,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"
before diving into further details

Simplicity helps us start,
rather than remain headbanging into Complexity First

Best avoid all the complexities :

- set .setsockopt( zmq.LINGER, 0 ) # ALWAYS, never know what version will try to join the Club

- prototype with PUSH/PULL(it a) meets the spec.+b) does not block in a mutual deadlock as all REQ/REP do )
- never share a socket ( yes, the requester ought be a private, non-shared instance )

- always read-in and assert-eval the return-codes from the ZeroMQ API calls ( detect many issues on-spot )

Can you POSACK / prove the both of the module-level declarations

```<code>...
void* requester;
void* context;
LRESULT CALLBACK meconnect(...) {...}
...
</code>```

actually work as expected, or does the ConnectServer(){...}'s internal, in-scope declarations mask both of these globals ?

```<code>extern "C" __declspec(dllexport) BOOL ConnectServer() {
    printf("Connecting to hello world server…\n");
    static void* context = zmq_ctx_new();                   // shadows out void* context
    static void* requester = zmq_socket(context, ZMQ_REQ); //  shadows out void* requester
    zmq_connect(requester, "tcp://127.0.0.1:5555");
    printf("connected");
    return TRUE;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to send over a message structure from a DLL-callback function to a python application so I can log the messages.

For this I would like to use ZeroMQ. Sadly I am unable to get the messages to python using the example provided by ZeroMQ.

DLL:

// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <zmq.h>
HHOOK tHook;
HMODULE hinstDLL;
void* requester;
void* context;
LRESULT CALLBACK meconnect(int code, WPARAM wParam, LPARAM lParam) {
    if (code == HC_ACTION) {
        LPMSG data = (LPMSG)lParam;
        UINT message = data->message;
        switch (message)
        {
        case WM_POINTERUPDATE:
            if (!IS_POINTER_INCONTACT_WPARAM(wParam))
                break;
        case WM_POINTERDOWN:
        case WM_POINTERUP:
            POINTER_INFO pointerInfo = {};
            GetPointerInfo(GET_POINTERID_WPARAM(wParam), &pointerInfo);
            int request_nbr;
            for (request_nbr = 0; request_nbr != 10; request_nbr++) {
                char buffer[10];
                printf("Sending Hello %d…\n", request_nbr);
                zmq_send(requester, data, 5, 0);
                zmq_recv(requester, buffer, 10, 0);
                printf("Received World %d\n", request_nbr);
            }
        }
    }
    return(CallNextHookEx(tHook, code, wParam, lParam));
}
extern "C" __declspec(dllexport) BOOL ConnectServer() {
    printf("Connecting to hello world server…\n");
    static void* context = zmq_ctx_new();
    static void* requester = zmq_socket(context, ZMQ_REQ);
    zmq_connect(requester, "tcp://127.0.0.1:5555");
    printf("connected");
    return TRUE;
}
extern "C" __declspec(dllexport) BOOL DisconnectServer() {
    zmq_close(requester);
    zmq_ctx_destroy(context);
    return TRUE;
}
extern "C" __declspec(dllexport) BOOL SetHook()
{
    tHook = SetWindowsHookEx(WH_GETMESSAGE, meconnect, hinstDLL, 0);

    if (tHook == NULL)
        return FALSE;
    else
        return TRUE;
}
extern "C" __declspec(dllexport) BOOL UnHook()
{
    return UnhookWindowsHookEx(tHook);
}

BOOL APIENTRY DllMain(HMODULE hModule,
    DWORD  ul_reason_for_call,
    LPVOID lpReserved
)
{
    switch (ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hinstDLL = hModule;
        break;
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
    case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}

Python:

context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://127.0.0.1:5555")

def message_msg_loop():
    while True:
        #  Wait for next request from client
        message = socket.recv()
        print("Received request: %s" % message)

        #  Do some 'work'
        time.sleep(1)

        #  Send reply back to client
        socket.send(b"World")

def pointer_msg_loop():
    global lib
    lib = cdll.LoadLibrary(r'C:\Users\Braun\Documents\BA_Thesis\ba-oliver-braun-logging-tool-code\MessagesDll\x64\Release\HOOKDLL.dll')
    print(lib)
    res = lib.ConnectServer()
    res = lib.SetHook()
    pythoncom.PumpMessages()
    res = lib.UnHook()

Basically my plan was to detect a certain event through windows messages and pass the message structure from the DLL-callback over to the server in Python, so I can handle the data there and put them into a log file. It does not seem to work though.

Body:
In case one has never worked with ZeroMQ,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"
before diving into further details

Simplicity helps us start,
rather than remain headbanging into Complexity First

Best avoid all the complexities :

- set .setsockopt( zmq.LINGER, 0 ) # ALWAYS, never know what version will try to join the Club

- prototype with PUSH/PULL(it a) meets the spec.+b) does not block in a mutual deadlock as all REQ/REP do )
- never share a socket ( yes, the requester ought be a private, non-shared instance )

- always read-in and assert-eval the return-codes from the ZeroMQ API calls ( detect many issues on-spot )

Can you POSACK / prove the both of the module-level declarations

...
void* requester;
void* context;
LRESULT CALLBACK meconnect(...) {...}
...

actually work as expected, or does the ConnectServer(){...}'s internal, in-scope declarations mask both of these globals ?

extern "C" __declspec(dllexport) BOOL ConnectServer() {
    printf("Connecting to hello world server…\n");
    static void* context = zmq_ctx_new();                   // shadows out void* context
    static void* requester = zmq_socket(context, ZMQ_REQ); //  shadows out void* requester
    zmq_connect(requester, "tcp://127.0.0.1:5555");
    printf("connected");
    return TRUE;
}


问:
MySQL 1005 Error - What's wrong with the query?
I'm unable to see the issue with this CREATE TABLE sentences. I've double checked but can't find the error.

```<code>-- -----------------------------------------------------
-- Table `agentes`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `agentes` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `codAgente` VARCHAR(8) NOT NULL ,
  `clave` VARCHAR(8) NOT NULL ,
  `nombre` VARCHAR(50) NOT NULL ,
  `apellido1` VARCHAR(50) NOT NULL ,
  `apellido2` VARCHAR(50) NOT NULL ,
  `email` VARCHAR(100) NOT NULL ,
  `usuarioDA` VARCHAR(45) NULL ,
  `passDA` VARCHAR(100) NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB
COLLATE = latin1_spanish_ci;

-- -----------------------------------------------------
-- Table `cola`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `colas` (
  `idCola` INT NOT NULL AUTO_INCREMENT ,
  `cliente` INT NOT NULL ,
  `nombre` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`idCola`) ,
  INDEX `fk_colas_clientes1` (`cliente` ASC) ,
  CONSTRAINT `fk_colas_clientes1`
    FOREIGN KEY (`cliente` )
    REFERENCES `clientes` (`idCliente` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `relColaExt`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `relColaExt` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `codAgente` VARCHAR(8) NOT NULL ,
  `cola` VARCHAR(45) NOT NULL ,
  `prioridad` INT NOT NULL ,
  PRIMARY KEY (`id`) ,
  UNIQUE INDEX `id` (`id` ASC) ,
  INDEX `fk_relColaExt_agentes1` (`codAgente` ASC) ,
  INDEX `fk_relColaExt_colas1` (`cola` ASC) ,
  CONSTRAINT `fk_relColaExt_agentes1`
    FOREIGN KEY (`codAgente` )
    REFERENCES `agentes` (`codAgente` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_relColaExt_colas1`
    FOREIGN KEY (`cola` )
    REFERENCES `colas` (`nombre` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;
</code>```

It throws #1005 - Can't create table './centralita/relColaExt.frm' (errno: 150) creating the relColaExt table.

It's a Foreign Key issue but I'm not able to see what's wrong. Can someone help me, please?

答:
According to this comment on MySQL manual page on Foreign keys, it may be due to different encoding of the VARCHAR columns. In table agentes you defined a collation but in relColaExt you did not.

Try using the same collation on every table (by defining it or by letting the default kick in).

ContentLicense: CC BY-SA 3.0

Body:
I'm unable to see the issue with this CREATE TABLE sentences. I've double checked but can't find the error.

-- -----------------------------------------------------
-- Table `agentes`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `agentes` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `codAgente` VARCHAR(8) NOT NULL ,
  `clave` VARCHAR(8) NOT NULL ,
  `nombre` VARCHAR(50) NOT NULL ,
  `apellido1` VARCHAR(50) NOT NULL ,
  `apellido2` VARCHAR(50) NOT NULL ,
  `email` VARCHAR(100) NOT NULL ,
  `usuarioDA` VARCHAR(45) NULL ,
  `passDA` VARCHAR(100) NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB
COLLATE = latin1_spanish_ci;

-- -----------------------------------------------------
-- Table `cola`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `colas` (
  `idCola` INT NOT NULL AUTO_INCREMENT ,
  `cliente` INT NOT NULL ,
  `nombre` VARCHAR(45) NOT NULL ,
  PRIMARY KEY (`idCola`) ,
  INDEX `fk_colas_clientes1` (`cliente` ASC) ,
  CONSTRAINT `fk_colas_clientes1`
    FOREIGN KEY (`cliente` )
    REFERENCES `clientes` (`idCliente` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `relColaExt`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `relColaExt` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `codAgente` VARCHAR(8) NOT NULL ,
  `cola` VARCHAR(45) NOT NULL ,
  `prioridad` INT NOT NULL ,
  PRIMARY KEY (`id`) ,
  UNIQUE INDEX `id` (`id` ASC) ,
  INDEX `fk_relColaExt_agentes1` (`codAgente` ASC) ,
  INDEX `fk_relColaExt_colas1` (`cola` ASC) ,
  CONSTRAINT `fk_relColaExt_agentes1`
    FOREIGN KEY (`codAgente` )
    REFERENCES `agentes` (`codAgente` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_relColaExt_colas1`
    FOREIGN KEY (`cola` )
    REFERENCES `colas` (`nombre` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

It throws #1005 - Can't create table './centralita/relColaExt.frm' (errno: 150) creating the relColaExt table.

It's a Foreign Key issue but I'm not able to see what's wrong. Can someone help me, please?


问:
Frida - Function to dump/inspect object
I'm trying to write a function using Frida that takes a Java object instance as an argument and returns a JS object with all the values and types of the Java object fields, possibly recursively.

For instance, if we have something like:

```<code>public class Person {
  private String fullName;
  private int age;
  private List hobbies,

  public Person(String fullName, int age, List hobbies) {
    ...
  }

  public void hello() {
    ...
  }
}
</code>```

I'd like to be able (in a Frida JS script) to run something like

```<code>Java.use("Person").hello.implementation = function() {
  console.log(JSON.stringify(dumpObject(this, 2)));  // dump recursively 2 levels deep
  this.hello();
}
</code>```

and see something like:

```<code>{
  "instance":"0x1234",
  "type":"Person",
  "fields' [
    {
     "name":"fullName",
     "declaredType":"java.lang.String",
     "actualType":"java.lang.String",
     "value":"John Smith",
    },
    {
     "name":"age",
     "declaredType":"int",
     "actualType":"int",
     "value":25,
    },
    {
     "name":"hobbies",
     "declaredType":"java.util.List",
     "actualType":"java.util.ArrayList",
     "value":{
        "instance":"0x4567",
        "type":"java.util.ArrayList",
        "fields": [
           ... all the fields of this ArrayList instance, 2 levels deep
        ],
     },
    },
  ]
}
</code>```

I tried several different approaches, but I keep having lots of errors and problems. Before I dig deeper, is anyone aware of some existing implementation that would save me quite a bit of time? I Googled extensively, but could only find scripts that dump class methods and field names, nothing that intelligently looks at values, including corner cases requiring _name access, static members, recursive dumping, etc...

Thanks!

答:
If you have JSON library loaded in memory (or you can load it dynamically w/ Module.load) you can invoke deserialize and pass the Java instance.

If you want to do it w/ Frida you can use Java class API to enumerate fields & methods, here is a boilerplate to start from.

var BreakException = {};

function describeJavaClass(klass) {
  var limit = 100;
  Java.enumerateLoadedClassesSync().forEach(klass => {
    if (--limit < 0) throw BreakException;
    var instances = [];
    Java.choose(klass, {
      onComplete: function () {
        if (instances.length != 0)
          console.log(JSON.stringify(instances, null, 2));
      },
      onMatch: function (instance) {
        var _class = instance.class;
        var c = {
          instance: instance,
          class: klass,
          methods: [],
          fields: {}
        };
        _class.getDeclaredFields().forEach(f => {
          var _field = f.toString().split('.').pop();
          var val = instance[_field].value;
          c.fields[f] = val ? val.toString() : val;
          instances.push(c);
        });
        _class.getDeclaredMethods().forEach(method => {
          c.methods.push(method.toString());
        });

      }
    });
  });
}

Java.perform(describeJavaClass);

```

Title: Frida - Function to dump/inspect object

Body:
I'm trying to write a function using Frida that takes a Java object instance as an argument and returns a JS object with all the values and types of the Java object fields, possibly recursively.

For instance, if we have something like:

public class Person {
  private String fullName;
  private int age;
  private List hobbies,

  public Person(String fullName, int age, List hobbies) {
    ...
  }

  public void hello() {
    ...
  }
}

I'd like to be able (in a Frida JS script) to run something like

Java.use("Person").hello.implementation = function() {
  console.log(JSON.stringify(dumpObject(this, 2)));  // dump recursively 2 levels deep
  this.hello();
}

and see something like:

{
  "instance":"0x1234",
  "type":"Person",
  "fields' [
    {
     "name":"fullName",
     "declaredType":"java.lang.String",
     "actualType":"java.lang.String",
     "value":"John Smith",
    },
    {
     "name":"age",
     "declaredType":"int",
     "actualType":"int",
     "value":25,
    },
    {
     "name":"hobbies",
     "declaredType":"java.util.List",
     "actualType":"java.util.ArrayList",
     "value":{
        "instance":"0x4567",
        "type":"java.util.ArrayList",
        "fields": [
           ... all the fields of this ArrayList instance, 2 levels deep
        ],
     },
    },
  ]
}

I tried several different approaches, but I keep having lots of errors and problems. Before I dig deeper, is anyone aware of some existing implementation that would save me quite a bit of time? I Googled extensively, but could only find scripts that dump class methods and field names, nothing that intelligently looks at values, including corner cases requiring _name access, static members, recursive dumping, etc...

Thanks!


问:
Bash: how to look for the next positional parameter in "case" code without hard-coding its value?
Given the "case" code snippet:

```<code>case $3 in
        -a)
            if [ "$4" == #some regex to match pattern ]; then
                #do some additional work
            else
                #proceed as usual
            fi
            ;;
</code>```

How could I better express my intention to look for a positional parameter which is located right next on the right-hand side of the current position $3 (or $3++, if that makes sense), instead of hard-coding it to $4 in the "if" statement?

EDIT:

the simplest usage of my script would look like this:

```<code>./script.sh company region -a LIST-123
</code>```

the first two mandatory positional arguments (company & region) are fixed.
Starting from the position $3, users have to provide at least one mandatory argument in the format of a preceding dash and a single letter (-a, -b, -c etc).
The single-letter mandatory arguments can have an optional argument (LIST-123 in the example above). If the optional argument is not provided, the script should resume as usual.

I want users to be able provide multiple mandatory-optional argument pairs. like this:

```<code>./script.sh company region -a LIST-123 -b LIST-456 -c LIST-789
</code>```

Also, to have flexibility to provide the mandatory single-letter args in any order:

```<code>./script.sh company region -c LIST-789 -b LIST-456 -a LIST-123
</code>```

And to be able to provide optional arguments only to certain mandatory single-letter args, but not all:

./script.sh company region -c LIST-789 -b -a LIST-123

答:
Here an example of using shift.

```<code>#!/usr/bin/env bash

while (($#)); do
  case $1 in
    country) echo "$1" is given
      ;;
    region) echo "$1" is given
      ;;
    -a)
      printf 'Current first parameter is: %s\n' "$1"
      shift
      printf '%s %s\n' "Next to -a is" "$1";;
    -b)
      printf 'Current first parameter is: %s\n' "$1"
      shift
      printf '%s %s\n' "Next to -b is" "$1"
      ;;
    *)
      printf '%s\n' "Unknown option $1" >&2
      exit 1
  esac
  shift
done
</code>```

Now run the script with the following option and arguments.

```<code>./myscript country region -b bar -a foo
</code>```

output

```<code>country is given
region is given
Current first parameter is: -b
Next to -b is bar
Current first parameter is: -a
Next to -a is foo
</code>```

I gave you the base solution, you just need to adapt it to your needs.

Like I said the mandatory can be with option too, so regardless where it end up in the arguments (first, middle, last) It can be process properly.

Body:
Given the "case" code snippet:

case $3 in
        -a)
            if [ "$4" == #some regex to match pattern ]; then
                #do some additional work
            else
                #proceed as usual
            fi
            ;;

How could I better express my intention to look for a positional parameter which is located right next on the right-hand side of the current position $3 (or $3++, if that makes sense), instead of hard-coding it to $4 in the "if" statement?

EDIT:

the simplest usage of my script would look like this:

./script.sh company region -a LIST-123

the first two mandatory positional arguments (company & region) are fixed.
Starting from the position $3, users have to provide at least one mandatory argument in the format of a preceding dash and a single letter (-a, -b, -c etc).
The single-letter mandatory arguments can have an optional argument (LIST-123 in the example above). If the optional argument is not provided, the script should resume as usual.

I want users to be able provide multiple mandatory-optional argument pairs. like this:

./script.sh company region -a LIST-123 -b LIST-456 -c LIST-789

Also, to have flexibility to provide the mandatory single-letter args in any order:

./script.sh company region -c LIST-789 -b LIST-456 -a LIST-123

And to be able to provide optional arguments only to certain mandatory single-letter args, but not all:

./script.sh company region -c LIST-789 -b -a LIST-123

Body:
Here an example of using shift.

#!/usr/bin/env bash

while (($#)); do
  case $1 in
    country) echo "$1" is given
      ;;
    region) echo "$1" is given
      ;;
    -a)
      printf 'Current first parameter is: %s\n' "$1"
      shift
      printf '%s %s\n' "Next to -a is" "$1";;
    -b)
      printf 'Current first parameter is: %s\n' "$1"
      shift
      printf '%s %s\n' "Next to -b is" "$1"
      ;;
    *)
      printf '%s\n' "Unknown option $1" >&2
      exit 1
  esac
  shift
done

Now run the script with the following option and arguments.

./myscript country region -b bar -a foo

output

country is given
region is given
Current first parameter is: -b
Next to -b is bar
Current first parameter is: -a
Next to -a is foo

I gave you the base solution, you just need to adapt it to your needs.

Like I said the mandatory can be with option too, so regardless where it end up in the arguments (first, middle, last) It can be process properly.


问:
Metrics Plugin issue in Eclipse
I have installed Metrics Plguin 1.3.8 in eclipse 3.7 indigo.After intalling and giving my system a restart I cant see any Metrics option in Project properties.

Any one have any idea on this.

答:
In my case, metrics was not enabled.
so
1.) right click on the project in package explorer
2.) click on properties
3.) select metric
4.) enable the metrics
5.) click on apply and close

thats it ..

Title: Metrics Plugin issue in Eclipse


问:
SQL query for group by result in different column
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22
```

<p>I Want Result like</p>

<pre class="lang-none prettyprint-override"><code>Column1 Value1 Value2
A       10      40
B       20      30
C       11      22
</code>```

Is there any query or store Procdure to get such Output

答:
It can also be done dynamically as bellow since you are not sure of the number of columns by modifying @LukStorms answer</p>

```<code>create table #MyTable (Column1 VARCHAR(2), [Value] INT)
insert into #MyTable values
('A',10),('B',20),('C',11),
('A',40), ('B',30), ('C',22)

 DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(CONCAT('Value', ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [Value])))
            FROM #MyTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query =  'SELECT
                *
              FROM
            ( SELECT Column1, [Value],
            CONCAT(''Value'', ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [Value])) AS ColValue
                FROM #MyTable
            ) Src
            PIVOT (
                MAX([Value]) FOR ColValue IN ('+@cols+')
) Pvt'

 exec(@query)

 drop table #MyTable
</code>```

Body:
I Have table having 2 columns

Column1 Value
   A     10
   B     20
   C     11
   A     40
   B     30
   C     22

I Want Result like

Column1 Value1 Value2
A       10      40
B       20      30
C       11      22

Is there any query or store Procdure to get such Output

Body:
It can also be done dynamically as bellow since you are not sure of the number of columns by modifying @LukStorms answer

create table #MyTable (Column1 VARCHAR(2), [Value] INT)
insert into #MyTable values
('A',10),('B',20),('C',11),
('A',40), ('B',30), ('C',22)

 DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(CONCAT('Value', ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [Value])))
            FROM #MyTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query =  'SELECT
                *
              FROM
            ( SELECT Column1, [Value],
            CONCAT(''Value'', ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [Value])) AS ColValue
                FROM #MyTable
            ) Src
            PIVOT (
                MAX([Value]) FOR ColValue IN ('+@cols+')
) Pvt'

 exec(@query)

 drop table #MyTable


问:
How to stop (deallocate) kubernetes nodes in azure without deleting the cluster?
I would like to stop and deallocate the nodes in a kubernetes cluster in azure so It cannot be billed during weekends for example.  I just can set to a minimun of 1 node using the az CLI

Any idea will be appreciated

答: If your are using scale sets (used for autoscaling and multiple node pools) you can deallocate the scale sets via ui (search in the resource the scale sets are created) or via az cli az-vmss-deallocate</p>


问:
How to call multiple Javascript function using onclientclick
I have a asp button code is:

```<code><asp:Button ID="Button1" runat="server"
Text="Submit" onclick="btn_click"

onclientclick= "javascript:returnisvalid
(document.getelementbyid
('*somevalue*'));" />
</code>```

What I need is now I need to call another function to prevent double clicking of the button which I created is

```<code>Function disablesave(savebutton){
Savebutton.disabled=true;
Savebutton.value=true;

}
</code>```

How can I validate the form and call this function on single onclientclick? Can anyone guide me on this?

答:
You can call multiple functions by separate them with semicolon ;, or comma ,

```<code>onclientclick="function1(); function2();"
</code>```

You can also call them connected with logical operations if you need to validate all of them, for example:

```<code>onclientclick="return (function1() && function2());"
</code>```

or even as

```<code>onclientclick="function1(); return function2();"
</code>```

alternative to avoid double submissions and only with javascript used you can go to the form and add your logic there using the onsubmit

```<code><form id="form1" runat="server" onsubmit="return disableForm(this);">
</code>```

Then on the javascript function disableForm() add your logic procedures.

Body:
I have a asp button code is:

<asp:Button ID="Button1" runat="server"
Text="Submit" onclick="btn_click"

onclientclick= "javascript:returnisvalid
(document.getelementbyid
('*somevalue*'));" />

What I need is now I need to call another function to prevent double clicking of the button which I created is

Function disablesave(savebutton){
Savebutton.disabled=true;
Savebutton.value=true;

}

How can I validate the form and call this function on single onclientclick? Can anyone guide me on this?

Body:
You can call multiple functions by separate them with semicolon ;, or comma ,

onclientclick="function1(); function2();"

You can also call them connected with logical operations if you need to validate all of them, for example:

onclientclick="return (function1() && function2());"

or even as

onclientclick="function1(); return function2();"

alternative to avoid double submissions and only with javascript used you can go to the form and add your logic there using the onsubmit

<form id="form1" runat="server" onsubmit="return disableForm(this);">

Then on the javascript function disableForm() add your logic procedures.


问:
Unit test for method containing switch case statement and insert to db
I have a method that contains a switch case block which iterates through an excel file to obtain values to write to a db.
I need to write a unit test for this method but I have no idea where to start.
Below is the method of which I need to write the unit test for. If anyone could advise me it would be greatly appreciated.

```<code>    public void loadAccount() throws Exception {
    Connection conn = null;
    PreparedStatement insert = null;
    Properties props = new Properties();

    try {
        conn = connMan.allocateConnection();
        conn.setAutoCommit(false);
        insert = conn.prepareStatement(INSERT_SQL_TOP_ACCOUNTS);

        FileInputStream inputStream = new FileInputStream("path");
        props.load(inputStream);
        String excelFilePath = props.getProperty("Account");
        FileInputStream iStream = new FileInputStream(new File(excelFilePath));

        Workbook workbook = new XSSFWorkbook(iStream);
        Sheet firstSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();

        // Current date for entry into db
        java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
        insert.setDate(1, sqlDate);

        // Skips the header row
        iterator.next();

        // Iterate through the first sheet and get the cell values
        while (iterator.hasNext()) {

            Row nextRow = iterator.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();

            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();
                int columnIndex = cell.getColumnIndex();

                switch (columnIndex) {
                case 0:
                    String institution = cell.getStringCellValue();
                    insert.setString(2, institution);
                    break;
                case 1:
                    // Formatting data because of alphanumeric mix in row
                    DataFormatter formatter = new DataFormatter();
                    String dept = formatter.formatCellValue(cell);
                    insert.setString(3, dept);
                    break;
                case 2:
                    int hits = (int) cell.getNumericCellValue();
                    insert.setInt(4, hits);
                    break;
                case 3:
                    int visitors = (int) cell.getNumericCellValue();
                    insert.setInt(5, visitors);
                    break;
                }
            }
            insert.addBatch();
        }
        int[] insertCount = insert.executeBatch();
        int successInserted = 0;
        for (int item : insertCount) {
            if (item == 1) {
                successInserted++;
            }
        }

        log.info("There're " + insertCount.length + " need to be inserted, with successfully [" + successInserted
                + "] inserted");
        conn.commit();
    } catch (Exception e) {
        log.error("Exception in loadAccount:" + e);
        try {
            conn.rollback();
        } catch (SQLException e1) {
            log.error("Exception when rollback the loading.", e1);
            throw e1;
        }
        throw e;
    } finally {
        connMan.closeStatement(insert);
        try {
            if (conn != null) {
                connMan.deallocateConnection(conn);
            }
        } catch (SQLException e) {
            log.error("Exception in loadAccount:" + e);
            throw e;
        }
    }
}
</code>```

答:
First of all to faciliate easy testing, you should make sure (as in "refactor until") your method does only one thing (reading an excel file, extracting values and writing to a db are at least three things). Going the Test-Driven-Development-Path would have left you with these separate methods in first place.

Then you should grab your prefered mocking framework and mock away the db access since using a real db would be an integration test and not an unit test.

After that you should test your new methods one by one. Preferably you added one 'mastermind' that faciliates calling the other methods and collectiong results so you could test your methods without invoking the others. Call your methods with fixed values (preferably edge and error cases) and use your prefered unit testing framework to assert the returns.

Body:
I have a method that contains a switch case block which iterates through an excel file to obtain values to write to a db.
I need to write a unit test for this method but I have no idea where to start.
Below is the method of which I need to write the unit test for. If anyone could advise me it would be greatly appreciated.

    public void loadAccount() throws Exception {
    Connection conn = null;
    PreparedStatement insert = null;
    Properties props = new Properties();

    try {
        conn = connMan.allocateConnection();
        conn.setAutoCommit(false);
        insert = conn.prepareStatement(INSERT_SQL_TOP_ACCOUNTS);

        FileInputStream inputStream = new FileInputStream("path");
        props.load(inputStream);
        String excelFilePath = props.getProperty("Account");
        FileInputStream iStream = new FileInputStream(new File(excelFilePath));

        Workbook workbook = new XSSFWorkbook(iStream);
        Sheet firstSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();

        // Current date for entry into db
        java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());
        insert.setDate(1, sqlDate);

        // Skips the header row
        iterator.next();

        // Iterate through the first sheet and get the cell values
        while (iterator.hasNext()) {

            Row nextRow = iterator.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();

            while (cellIterator.hasNext()) {

                Cell cell = cellIterator.next();
                int columnIndex = cell.getColumnIndex();

                switch (columnIndex) {
                case 0:
                    String institution = cell.getStringCellValue();
                    insert.setString(2, institution);
                    break;
                case 1:
                    // Formatting data because of alphanumeric mix in row
                    DataFormatter formatter = new DataFormatter();
                    String dept = formatter.formatCellValue(cell);
                    insert.setString(3, dept);
                    break;
                case 2:
                    int hits = (int) cell.getNumericCellValue();
                    insert.setInt(4, hits);
                    break;
                case 3:
                    int visitors = (int) cell.getNumericCellValue();
                    insert.setInt(5, visitors);
                    break;
                }
            }
            insert.addBatch();
        }
        int[] insertCount = insert.executeBatch();
        int successInserted = 0;
        for (int item : insertCount) {
            if (item == 1) {
                successInserted++;
            }
        }

        log.info("There're " + insertCount.length + " need to be inserted, with successfully [" + successInserted
                + "] inserted");
        conn.commit();
    } catch (Exception e) {
        log.error("Exception in loadAccount:" + e);
        try {
            conn.rollback();
        } catch (SQLException e1) {
            log.error("Exception when rollback the loading.", e1);
            throw e1;
        }
        throw e;
    } finally {
        connMan.closeStatement(insert);
        try {
            if (conn != null) {
                connMan.deallocateConnection(conn);
            }
        } catch (SQLException e) {
            log.error("Exception in loadAccount:" + e);
            throw e;
        }
    }
}


问:
appendChild is not a function, cant add text to multi divs
In my case I have 8 divs and I want to dynamically via javascript add text to each of these. When I do that with using querySelector (for one div) it works, but for querySelectorAll (each of these) it doesn't.
code:</p>

```<code>html
            <div class=" bookapp__container">
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
                    <div class="bookapp__container__item item"></div>
            </div>

</code>```

```<code>javascript

let myParagraph = document.createElement('p');
myParagraph.innerHTML = 'Some text';
let myItems = document.querySelectorAll('.item');
myItems.appendChild(myParagraph);
</code>```

答:
you'll have to loop through myItem instead of trying to use appendChild on that.

```<code>myItems.forEach(item => item.appendChild(myParagraph))
</code>```

Body:
In my case I have 8 divs and I want to dynamically via javascript add text to each of these. When I do that with using querySelector (for one div) it works, but for querySelectorAll (each of these) it doesn't.
code:

html

javascript

let myParagraph = document.createElement('p');
myParagraph.innerHTML = 'Some text';
let myItems = document.querySelectorAll('.item');
myItems.appendChild(myParagraph);

Body:
you'll have to loop through myItem instead of trying to use appendChild on that.

myItems.forEach(item => item.appendChild(myParagraph))


问:
Delete columns depending on cell values in a matrix and get rid of subscript out of bounds error
I have a problem where I must delete certain columns in an Excel file depending on some cell values using R.

I imported the Excel file

```<code>data = as.matrix(read.csv('data.csv', header = FALSE))
</code>```

Dimensions of the matrix are: dim(data) = 106474 * 81

What I need to do

If a value in any of the cells [row = 1, column = i] = 'A' -> delete column

If a value in any of the cells [row = 1, column = i] = 'B' -> delete column

If a value in any of the cells [row = 2, column = i] > 30 -> delete column

What I did so far

```<code>for (i in 1:ncol(data)) {
  if (data[1,i]=='A') {
    data =  data [,-i]
  } else if (data[1,i]=='B') {
    data =  data [,-i]
  } else if (data[2,i] > 30) {
    data =  data [,-i]
  }
}
</code>```

Problems I ran into are as follows:

When I read the matrix to r, it read everything as characters? how to convert data[2,i] row to
numeric. I have provided how I converted it to numeric. But is there any better way?

```<code>row2 = as.numeric(as.matrix(fly_data[2,]))
fly_data[2,] <- row2
</code>```

My for loop end abruptly and it doesn't run to the full length of

```<code>ncol(data)
</code>```

It always gives the

Error in data[1, i] : subscript out of bounds

答:
Maybe you can try the code below

```<code>r <- subset(data, select = -which(as.character(unlist(data[1,]))%in% c("A","B") | as.numeric(as.character(unlist(data[2,])))>30))
</code>```

such that

```<code>> r
   X2 X3 X7
r1  D  C  C
r2  6 24 25
</code>```

DATA

```<code>data <- structure(list(X1 = structure(2:1, .Names = c("r1", "r2"), .Label = c("7",
"A"), class = "factor"), X2 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("6", "D"), class = "factor"), X3 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("24", "C"), class = "factor"), X4 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("13", "A"), class = "factor"), X5 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("27", "B"), class = "factor"), X6 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("17", "A"), class = "factor"), X7 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("25", "C"), class = "factor"), X8 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("35", "C"), class = "factor"), X9 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("13", "B"), class = "factor"), X10 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("27", "B"), class = "factor")), class = "data.frame", row.names = c("r1",
"r2"))

> data
   X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
r1  A  D  C  A  B  A  C  C  B   B
r2  7  6 24 13 27 17 25 35 13  27
</code>```

Body:
I have a problem where I must delete certain columns in an Excel file depending on some cell values using R.

I imported the Excel file

data = as.matrix(read.csv('data.csv', header = FALSE))

Dimensions of the matrix are: dim(data) = 106474 * 81

What I need to do

If a value in any of the cells [row = 1, column = i] = 'A' -> delete column

If a value in any of the cells [row = 1, column = i] = 'B' -> delete column

If a value in any of the cells [row = 2, column = i] > 30 -> delete column

What I did so far

for (i in 1:ncol(data)) {
  if (data[1,i]=='A') {
    data =  data [,-i]
  } else if (data[1,i]=='B') {
    data =  data [,-i]
  } else if (data[2,i] > 30) {
    data =  data [,-i]
  }
}

Problems I ran into are as follows:

When I read the matrix to r, it read everything as characters? how to convert data[2,i] row to
numeric. I have provided how I converted it to numeric. But is there any better way?

row2 = as.numeric(as.matrix(fly_data[2,]))
fly_data[2,] <- row2

My for loop end abruptly and it doesn't run to the full length of

ncol(data)

It always gives the

Error in data[1, i] : subscript out of bounds

Body:
Maybe you can try the code below

r <- subset(data, select = -which(as.character(unlist(data[1,]))%in% c("A","B") | as.numeric(as.character(unlist(data[2,])))>30))

such that

> r
   X2 X3 X7
r1  D  C  C
r2  6 24 25

DATA

data <- structure(list(X1 = structure(2:1, .Names = c("r1", "r2"), .Label = c("7",
"A"), class = "factor"), X2 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("6", "D"), class = "factor"), X3 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("24", "C"), class = "factor"), X4 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("13", "A"), class = "factor"), X5 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("27", "B"), class = "factor"), X6 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("17", "A"), class = "factor"), X7 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("25", "C"), class = "factor"), X8 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("35", "C"), class = "factor"), X9 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("13", "B"), class = "factor"), X10 = structure(2:1, .Names = c("r1",
"r2"), .Label = c("27", "B"), class = "factor")), class = "data.frame", row.names = c("r1",
"r2"))

> data
   X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
r1  A  D  C  A  B  A  C  C  B   B
r2  7  6 24 13 27 17 25 35 13  27


问:
Unable to SSH in Azure VM created with Packer
So, I am creating an Azure image using Packer.

```<code>{
  "builders": [{
    "type": "azure-arm",

    "client_id"      : "{{user `client_id`}}",
    "client_secret"  : "{{user `client_secret`}}",
    "subscription_id": "{{user `subscription_id`}}",
    "tenant_id"      : "{{user `tenant_id`}}",

    "managed_image_resource_group_name": "{{user `resource_group`}}",
    "managed_image_name": "CentOS7_w_GitlabCE_{{timestamp}}",

    "os_type"        : "Linux",
    "image_publisher": "OpenLogic",
    "image_offer"    : "CentOS",
    "image_sku"      : "7.3",
    "image_version"  : "latest",

    "location": "{{user `location`}}",
    "vm_size" : "Standard_DS2_v2"
  }],
  "provisioners": [
    {
      "type": "ansible",
      "playbook_file": "./gitlab/ansible/install-gitlab.yml",
      "extra_arguments": [
        "-vvvv"
      ]
    }
  ]
}
</code>```

The image is created nicely and lives inside my resource group in Azure.

Then, I feed its details in Terraform to create a Scale Set.

```<code>data "azurerm_image" "image" {
  count = "${var.create_gitlab ? 1 : 0}"

  //notice: the image must have been created beforehand by Packer (inside the specific resource group)
  name                = "${var.vm_img_built_via_packer}"
  resource_group_name = "${var.resource_group}"
}

resource "azurerm_virtual_machine_scale_set" "vmss" {

...other stuff....

  storage_profile_image_reference {
    // reference the id of the custom image created with Packer
    id = "${data.azurerm_image.image.id}"
  }

  os_profile {
    computer_name_prefix = "${var.prefix}-vm"
    admin_username       = "someuser"
  }

  os_profile_linux_config {
    disable_password_authentication = true

    ssh_keys {
      path     = "/home/someuser/.ssh/authorized_keys"
      key_data = "${file(var.someuser_ssh_pubkey)}"
    }
  }

...other stuff...

}
</code>```

When I launch the VMSS I get Permission denied (publickey,gssapi-keyex,gssapi-with-mic). when I try to SSH in a VM.

However, if I use the same Centos image but directly from Azure, I can SSH in a VM.

Also, what makes me mad is that when I create a Centos image via Packer, without provisioning it with Ansible (really just a Centos image), and use it with the scale set ... I also CANNOT SSH in it.

Feels like Packer makes something nasty.

答:
Looks like you are skipping deprovision step https://packer.io/docs/builders/azure-arm.html#deprovision which is mandatory to empty network and local accounts configurations and to reuse image after.

For Linux you need to execute this command:

/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync
```

Look on example here : https://github.com/hashicorp/packer/blob/master/examples/azure/linux_custom_image.json

Azure docs: https://learn.microsoft.com/en-us/azure/virtual-machines/linux/capture-image#step-1-deprovision-the-vm

Body:
So, I am creating an Azure image using Packer.

{
  "builders": [{
    "type": "azure-arm",

    "client_id"      : "{{user `client_id`}}",
    "client_secret"  : "{{user `client_secret`}}",
    "subscription_id": "{{user `subscription_id`}}",
    "tenant_id"      : "{{user `tenant_id`}}",

    "managed_image_resource_group_name": "{{user `resource_group`}}",
    "managed_image_name": "CentOS7_w_GitlabCE_{{timestamp}}",

    "os_type"        : "Linux",
    "image_publisher": "OpenLogic",
    "image_offer"    : "CentOS",
    "image_sku"      : "7.3",
    "image_version"  : "latest",

    "location": "{{user `location`}}",
    "vm_size" : "Standard_DS2_v2"
  }],
  "provisioners": [
    {
      "type": "ansible",
      "playbook_file": "./gitlab/ansible/install-gitlab.yml",
      "extra_arguments": [
        "-vvvv"
      ]
    }
  ]
}

The image is created nicely and lives inside my resource group in Azure.

Then, I feed its details in Terraform to create a Scale Set.

data "azurerm_image" "image" {
  count = "${var.create_gitlab ? 1 : 0}"

  //notice: the image must have been created beforehand by Packer (inside the specific resource group)
  name                = "${var.vm_img_built_via_packer}"
  resource_group_name = "${var.resource_group}"
}

resource "azurerm_virtual_machine_scale_set" "vmss" {

...other stuff....

  storage_profile_image_reference {
    // reference the id of the custom image created with Packer
    id = "${data.azurerm_image.image.id}"
  }

  os_profile {
    computer_name_prefix = "${var.prefix}-vm"
    admin_username       = "someuser"
  }

  os_profile_linux_config {
    disable_password_authentication = true

    ssh_keys {
      path     = "/home/someuser/.ssh/authorized_keys"
      key_data = "${file(var.someuser_ssh_pubkey)}"
    }
  }

...other stuff...

}

When I launch the VMSS I get Permission denied (publickey,gssapi-keyex,gssapi-with-mic). when I try to SSH in a VM.

However, if I use the same Centos image but directly from Azure, I can SSH in a VM.

Also, what makes me mad is that when I create a Centos image via Packer, without provisioning it with Ansible (really just a Centos image), and use it with the scale set ... I also CANNOT SSH in it.

Feels like Packer makes something nasty.

Body:
Looks like you are skipping deprovision step https://packer.io/docs/builders/azure-arm.html#deprovision which is mandatory to empty network and local accounts configurations and to reuse image after.

For Linux you need to execute this command:

/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync

Look on example here : https://github.com/hashicorp/packer/blob/master/examples/azure/linux_custom_image.json

Azure docs: https://learn.microsoft.com/en-us/azure/virtual-machines/linux/capture-image#step-1-deprovision-the-vm


问:
Template friendly string to numeric in C++
In C++ standard library there are functions to convert from string to numeric types:

```<code>stoi
stol
stoll
stoul
stoull
stof
stod
stold
</code>```

but I find it tedious to use them in template code. Why there are no template functions something like:

```<code>template<typename T>
T sto(...)
</code>```

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?

答:
Solution compatible with all (even older C++ compilers like C++-98 ones) is to use boost::lexical_cast which is a template to convert between numeric and string types in both ways.

Example:

```<code>short myInt = boost::lexical_cast<short>(*argv);
std::string backToString = boost::lexical_cast<std::string>(myInt);
</code>```

See: https://www.boost.org/doc/libs/1_42_0/libs/conversion/lexical_cast.htm

Body:
In C++ standard library there are functions to convert from string to numeric types:

stoi
stol
stoll
stoul
stoull
stof
stod
stold

but I find it tedious to use them in template code. Why there are no template functions something like:

template<typename T>
T sto(...)

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?

Body:
Solution compatible with all (even older C++ compilers like C++-98 ones) is to use boost::lexical_cast which is a template to convert between numeric and string types in both ways.

Example:

short myInt = boost::lexical_cast<short>(*argv);
std::string backToString = boost::lexical_cast<std::string>(myInt);

See: https://www.boost.org/doc/libs/1_42_0/libs/conversion/lexical_cast.htm


问:
How to insert Java Date and Timestamp value to mysql databas in spring
I am trying to create a register page to add flight details, while trying to insert Date and Time in mysql database, but i am getting error rejected value [22-02-2020]; and rejected value [12:00]; , could some one guide me how to resolve this.

My Flight Model class

```<code>@Entity
@Table(name="FLIGHT")
public class Flight {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int ID;
    private String flightnumber;
    @Column(name="operatingairlines")
    private String operatingAirlines;
    @Column(name="departurecity")
    private String departureCity;
    @Column(name="arrivalcity")
    private String arivalCity;
    @Column(name="departuredate")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dateOfDeparture;
    @Column(name="departuretime")
    private Timestamp estimatedTravelTime;

    public int getID() {
        return ID;
    }

    public void setID(int iD) {
        ID = iD;
    }

    public String getFlightnumber() {
        return flightnumber;
    }

    public void setFlightnumber(String flightnumber) {
        this.flightnumber = flightnumber;
    }

    public String getOperatingAirlines() {
        return operatingAirlines;
    }

    public void setOperatingAirlines(String operatingAirlines) {
        this.operatingAirlines = operatingAirlines;
    }

    public String getDepartureCity() {
        return departureCity;
    }

    public void setDepartureCity(String departureCity) {
        this.departureCity = departureCity;
    }

    public String getArivalCity() {
        return arivalCity;
    }

    public void setArivalCity(String arivalCity) {
        this.arivalCity = arivalCity;
    }

    public Date getDateOfDeparture() {
        return dateOfDeparture;
    }

    public void setDateOfDeparture(Date dateOfDeparture) {
        this.dateOfDeparture = dateOfDeparture;
    }

    public Timestamp getEstimatedTravelTime() {
        return estimatedTravelTime;
    }

    public void setEstimatedTravelTime(Timestamp estimatedTravelTime) {
        this.estimatedTravelTime = estimatedTravelTime;
    }

    @Override
    public String toString() {
        return "Flight [ID=" + ID + ", flightnumber=" + flightnumber + ", operatingAirlines=" + operatingAirlines
                + ", departureCity=" + departureCity + ", arivalCity=" + arivalCity + ", dateOfDeparture="
                + dateOfDeparture + ", estimatedTravelTime=" + estimatedTravelTime + "]";
    }

}
</code>```

Login Controller

package com.tcdc.FlightReservation.controller;

```<code>@Controller
public class LoginController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/showform")
    public String showRegistration() {
        return "register";
    }

    @PostMapping("/registerUser")
    public String SaveRegister(@ModelAttribute("user") User user) {
        //user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        System.out.println(user);
        userRepository.save(user);
        return "login";
    }

    @GetMapping("/showlogin")
    public String showLogin() {
        //userRepository.
        return "login";
    }

    @PostMapping("/LoginProcess")
    public String LoginProcess(@RequestParam("email") String email, @RequestParam("password") String password) {

        User user = userRepository.findByEmail(email);
        System.out.println(user);
        if((user.getPassword().equals(password))&&(user.getRole().contentEquals("0"))) {
            return "findFlights";
        }
        else if((user.getPassword().equals(password))&&(user.getRole().contentEquals("1"))) {
            return "AddFlight";
        }
        else {
        return "login";
        }

    }

}
</code>```

FlightController

```<code>@Controller
public class FlightController {

    @Autowired
    FlightServices flightServices;

    @Autowired
    FlightRepository flightRepository;

    @PostMapping("/flightResult")
    public String findFlights(@RequestParam("from") String from,@RequestParam("to") String to,@RequestParam("departureDate") @DateTimeFormat(pattern="dd-MM-yyyy") Date departureDate, Model model) {

        //flightRepository.findFlight(from,to,departureDate);
        System.out.println(from+" "+to+" "+departureDate);
        List<Flight> flist = flightServices.searchFlight(from,to,departureDate);
        model.addAttribute("flightdetails", flist);
        System.out.println(flist);
        return "FlightResults";
    }

    @PostMapping("/SaveFlight")
    public String SaveFlight(@ModelAttribute("flight") Flight flight) {

        flight.getDateOfDeparture();

                    //flightRepository.save(flight);

        return "FlightResults";
    }

}
</code>```

Error

```<code>2020-02-19 20:02:35.580  WARN 3048 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'flight' on field 'dateOfDeparture': rejected value [22-02-2020]; codes [typeMismatch.flight.dateOfDeparture,typeMismatch.dateOfDeparture,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [flight.dateOfDeparture,dateOfDeparture]; arguments []; default message [dateOfDeparture]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateOfDeparture'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '22-02-2020'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [22-02-2020]]
Field error in object 'flight' on field 'estimatedTravelTime': rejected value [12:00]; codes [typeMismatch.flight.estimatedTravelTime,typeMismatch.estimatedTravelTime,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [flight.estimatedTravelTime,estimatedTravelTime]; arguments []; default message [estimatedTravelTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'estimatedTravelTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.sql.Timestamp] for value '12:00'; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]]
</code>```

Mysql Table details

```<code>ID                    int(11)   NO  PRI
flightnumber        varchar(50) NO
operatingairlines   varchar(50) NO
departurecity       varchar(50) NO
arrivalcity         varchar(50) NO
departuredate        date       NO
departuretime        timestamp  NO      CURRENT_TIMESTAMP
</code>```

答:
You can do something like this. Just use Date with following annotation.

```<code>@Column(name="departuretime")
@Temporal(TemporalType.TIMESTAMP)
private Date estimatedTravelTime;
</code>```

Body:
I am trying to create a register page to add flight details, while trying to insert Date and Time in mysql database, but i am getting error rejected value [22-02-2020]; and rejected value [12:00]; , could some one guide me how to resolve this.

My Flight Model class

@Entity
@Table(name="FLIGHT")
public class Flight {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int ID;
    private String flightnumber;
    @Column(name="operatingairlines")
    private String operatingAirlines;
    @Column(name="departurecity")
    private String departureCity;
    @Column(name="arrivalcity")
    private String arivalCity;
    @Column(name="departuredate")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date dateOfDeparture;
    @Column(name="departuretime")
    private Timestamp estimatedTravelTime;

    public int getID() {
        return ID;
    }

    public void setID(int iD) {
        ID = iD;
    }

    public String getFlightnumber() {
        return flightnumber;
    }

    public void setFlightnumber(String flightnumber) {
        this.flightnumber = flightnumber;
    }

    public String getOperatingAirlines() {
        return operatingAirlines;
    }

    public void setOperatingAirlines(String operatingAirlines) {
        this.operatingAirlines = operatingAirlines;
    }

    public String getDepartureCity() {
        return departureCity;
    }

    public void setDepartureCity(String departureCity) {
        this.departureCity = departureCity;
    }

    public String getArivalCity() {
        return arivalCity;
    }

    public void setArivalCity(String arivalCity) {
        this.arivalCity = arivalCity;
    }

    public Date getDateOfDeparture() {
        return dateOfDeparture;
    }

    public void setDateOfDeparture(Date dateOfDeparture) {
        this.dateOfDeparture = dateOfDeparture;
    }

    public Timestamp getEstimatedTravelTime() {
        return estimatedTravelTime;
    }

    public void setEstimatedTravelTime(Timestamp estimatedTravelTime) {
        this.estimatedTravelTime = estimatedTravelTime;
    }

    @Override
    public String toString() {
        return "Flight [ID=" + ID + ", flightnumber=" + flightnumber + ", operatingAirlines=" + operatingAirlines
                + ", departureCity=" + departureCity + ", arivalCity=" + arivalCity + ", dateOfDeparture="
                + dateOfDeparture + ", estimatedTravelTime=" + estimatedTravelTime + "]";
    }

}

Login Controller

package com.tcdc.FlightReservation.controller;

@Controller
public class LoginController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/showform")
    public String showRegistration() {
        return "register";
    }

    @PostMapping("/registerUser")
    public String SaveRegister(@ModelAttribute("user") User user) {
        //user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        System.out.println(user);
        userRepository.save(user);
        return "login";
    }

    @GetMapping("/showlogin")
    public String showLogin() {
        //userRepository.
        return "login";
    }

    @PostMapping("/LoginProcess")
    public String LoginProcess(@RequestParam("email") String email, @RequestParam("password") String password) {

        User user = userRepository.findByEmail(email);
        System.out.println(user);
        if((user.getPassword().equals(password))&&(user.getRole().contentEquals("0"))) {
            return "findFlights";
        }
        else if((user.getPassword().equals(password))&&(user.getRole().contentEquals("1"))) {
            return "AddFlight";
        }
        else {
        return "login";
        }

    }

}

FlightController

@Controller
public class FlightController {

    @Autowired
    FlightServices flightServices;

    @Autowired
    FlightRepository flightRepository;

    @PostMapping("/flightResult")
    public String findFlights(@RequestParam("from") String from,@RequestParam("to") String to,@RequestParam("departureDate") @DateTimeFormat(pattern="dd-MM-yyyy") Date departureDate, Model model) {

        //flightRepository.findFlight(from,to,departureDate);
        System.out.println(from+" "+to+" "+departureDate);
        List<Flight> flist = flightServices.searchFlight(from,to,departureDate);
        model.addAttribute("flightdetails", flist);
        System.out.println(flist);
        return "FlightResults";
    }

    @PostMapping("/SaveFlight")
    public String SaveFlight(@ModelAttribute("flight") Flight flight) {

        flight.getDateOfDeparture();

                    //flightRepository.save(flight);

        return "FlightResults";
    }

}

Error

2020-02-19 20:02:35.580  WARN 3048 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'flight' on field 'dateOfDeparture': rejected value [22-02-2020]; codes [typeMismatch.flight.dateOfDeparture,typeMismatch.dateOfDeparture,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [flight.dateOfDeparture,dateOfDeparture]; arguments []; default message [dateOfDeparture]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'dateOfDeparture'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column @org.springframework.format.annotation.DateTimeFormat java.util.Date] for value '22-02-2020'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [22-02-2020]]
Field error in object 'flight' on field 'estimatedTravelTime': rejected value [12:00]; codes [typeMismatch.flight.estimatedTravelTime,typeMismatch.estimatedTravelTime,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [flight.estimatedTravelTime,estimatedTravelTime]; arguments []; default message [estimatedTravelTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'estimatedTravelTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.sql.Timestamp] for value '12:00'; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]]

Mysql Table details

ID                    int(11)   NO  PRI
flightnumber        varchar(50) NO
operatingairlines   varchar(50) NO
departurecity       varchar(50) NO
arrivalcity         varchar(50) NO
departuredate        date       NO
departuretime        timestamp  NO      CURRENT_TIMESTAMP

Body:
You can do something like this. Just use Date with following annotation.

@Column(name="departuretime")
@Temporal(TemporalType.TIMESTAMP)
private Date estimatedTravelTime;


答:
querySelectorAll returns a collection so you need to iterate over that and append child. Also note a node cannot have multiple parent, so you need to create new p during each iteration

document.querySelectorAll('.item').forEach((item) => {
  let myParagraph = document.createElement('p');
  myParagraph.innerHTML = 'Some text';
  item.appendChild(myParagraph);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=" bookapp__container">
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
</div></code>```

Title: appendChild is not a function, cant add text to multi divs

Body:
querySelectorAll returns a collection so you need to iterate over that and append child. Also note a node cannot have multiple parent, so you need to create new p during each iteration

document.querySelectorAll('.item').forEach((item) => {
  let myParagraph = document.createElement('p');
  myParagraph.innerHTML = 'Some text';
  item.appendChild(myParagraph);
})

<div class=" bookapp__container">
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
  <div class="bookapp__container__item item"></div>
</div>


问:
How to force Office UI Fabric ChoiceGroup to align horizontal
I am trying to build a SPFx webpart containing a ChoiceGroup. When I set the css style to ms-sm12 the choices are aligned vertical:

```<code>Show assigned to:
o anyone
* me
o nobody
</code>```

I like them to align horizontal in one row:

```<code>Show assigned to: o anyone * me o nobody
</code>```

When I set the style to ms-sm6, it aligns them "mixed":
The Slider and Toggle are set to ms-sm3

```<code>Show assigned to: o anyone
* me
o nobody
</code>```

With ms-sm4 it looks like:

With ms-sm3, ms-sm2, ms-sm1 it looks like (the title getting more and more squashed and all options in one column:

How can I force / encourage the options to be rendered horizontal?

答:
add styles property to ChoiceGroup styles={{ flexContainer: { display: "flex" } }}

add styles property to options styles: { choiceFieldWrapper: { display: 'inline-block', margin: '0 0 0 10px' }}

done!

Body:
I am trying to build a SPFx webpart containing a ChoiceGroup. When I set the css style to ms-sm12 the choices are aligned vertical:

Show assigned to:
o anyone
* me
o nobody

I like them to align horizontal in one row:

Show assigned to: o anyone * me o nobody

When I set the style to ms-sm6, it aligns them "mixed":
The Slider and Toggle are set to ms-sm3

Show assigned to: o anyone
* me
o nobody

With ms-sm4 it looks like:

With ms-sm3, ms-sm2, ms-sm1 it looks like (the title getting more and more squashed and all options in one column:

How can I force / encourage the options to be rendered horizontal?


问:
Is there PHP mysql_real_escape_string for postgresql?
Is there PHP mysql_real_escape_string for postgresql?
if yes then how ? please Give the Examples? & also the work of this string</p>

答: Alternatively you could use prepared statements (pg_prepare) and placeholders ($1, $2, etc), and then give the arguments for the query in pg_execute. This would be my preferred way as it's not only cleaner, but also safer in the long run since there's no chance for SQL injections if you always use placeholders in prepared statements.


问:
replacing nested for loop with lapply()
I have sen this example to explain how to replace an nested for loop with the lapply() function. However i do not fully understand what is happening in the nested for loop?

according to my understanding, the for loop creates for every country for all years two new variables called tempX and tempY, but what happens in the last line of the argument in the for loop?

what is the purpose of variable1 and variable2 ?

```<code># Generate random data:
allCountries <- LETTERS[1:10]
allYears <- 1990:2012

myData <- expand.grid(allCountries, allYears)  # create a dataframe with all possible combinations
colnames(myData) <- c("Country", "Year")
myData$variable1 <- rnorm(nrow(myData))
myData$variable2 <- rnorm(nrow(myData))

# Silly function to perform
myFunction <- function(x, y){
  x * y - x / y
}

### Doubly-nested loop ###
myData$computedFigure <- NA  # Make an "empty" variable in my data.frame

for(ii in allCountries){
  for(jj in allYears){
    tempX <- myData[myData$Country == ii & myData$Year == jj, c("variable1")]
    tempY <- myData[myData$Country == ii & myData$Year == jj, c("variable2")]
    # "Save" results into appropriate location in my data.frame
    myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
  }
}

### Simple lapply() approach ###
computedFigureList <- lapply(1:nrow(myData), function(x){
  tempX <- myData[x, c("variable1")]
  tempY <- myData[x, c("variable2")]
  # "Save" results into appropriate location in my data.frame
  myFunction(tempX, tempY)
})

myData$computedFigure2 <- unlist(computedFigureList)
with(myData, plot(computedFigure, computedFigure2))
</code>```

答:
In the last line of the loop myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
, the function myFunctionis applied and recorded in the computedFigure column.

variable1 and variable2 are set randomly to illustrate the data in myData (x and y) in myFunction.

The for loops are exploring the combinations in countries and years...
The two codes (for loop and lappy) will not generate exactly the same result. The lapply will generate a list just with the result of the myFunction. The for loops will generate a dataframe.

Title: replacing nested for loop with lapply()

Body:
I have sen this example to explain how to replace an nested for loop with the lapply() function. However i do not fully understand what is happening in the nested for loop?

according to my understanding, the for loop creates for every country for all years two new variables called tempX and tempY, but what happens in the last line of the argument in the for loop?

what is the purpose of variable1 and variable2 ?

# Generate random data:
allCountries <- LETTERS[1:10]
allYears <- 1990:2012

myData <- expand.grid(allCountries, allYears)  # create a dataframe with all possible combinations
colnames(myData) <- c("Country", "Year")
myData$variable1 <- rnorm(nrow(myData))
myData$variable2 <- rnorm(nrow(myData))

# Silly function to perform
myFunction <- function(x, y){
  x * y - x / y
}

### Doubly-nested loop ###
myData$computedFigure <- NA  # Make an "empty" variable in my data.frame

for(ii in allCountries){
  for(jj in allYears){
    tempX <- myData[myData$Country == ii & myData$Year == jj, c("variable1")]
    tempY <- myData[myData$Country == ii & myData$Year == jj, c("variable2")]
    # "Save" results into appropriate location in my data.frame
    myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
  }
}

### Simple lapply() approach ###
computedFigureList <- lapply(1:nrow(myData), function(x){
  tempX <- myData[x, c("variable1")]
  tempY <- myData[x, c("variable2")]
  # "Save" results into appropriate location in my data.frame
  myFunction(tempX, tempY)
})

myData$computedFigure2 <- unlist(computedFigureList)
with(myData, plot(computedFigure, computedFigure2))


问:
Efficient way to get a matrix of high and low expressions for multiple variables to be used for simulations
I want to have a matrix including one high (1 sd above average) and low (1 sd below median) expression for each variable out of multiple variables.

In one variant, for each variable I would like to have one high expression, while all other variables are low.

In addition, I would like to have a variant in which all other variables are set to 0 and then there is a high and a low expression for each variable.

I want to use it for model predictions.

For three variables I would already need for variant 1:

```<code>pred_da <- data.frame(var1 = c(median(da$var1)+1*sd(da$var1), median(da$var1)-1*sd(da$var1), median(da$var1)-1*sd(da$var1)), var2 = c(median(da$var2)-1*sd(da$var2), median(da$var2)+1*sd(da$var2), median(da$var2)-1*sd(da$var2)), var3 = c(median(da$var3)-1*sd(da$var3), median(da$var3)-1*sd(da$var3), median(da$var3)+1*sd(da$var3)))
</code>```

For variant 2 it would be even more...

There should be a more efficient way to do it?

答:
I think Adam B.'s solution puts the medians instead of median - sd as results (see code below in reproducible example).

Also, your example code uses median +/- sd, while the text defines "high" as 1 sd above average (not median), so it is not clear which one you want. I went with median in both cases.

You can achieve the same quite easily with base R by filling a matrix with the "low" expression for each column  and adding the "high" expression in the diagonal:

# data (common to all versions)
set.seed(1)
da <-
  data.frame(
    ID = 1:10,
    var1 = rnorm(10, 0, 1),
    var2 = rpois(10, 2),
    var3 = rexp(10, 1),
    stringsAsFactors = FALSE
  )
varnames <- colnames(da)[-1]

# my version
mat <- data.matrix(da[, -1])
median_da <- apply(mat, 2, median)
sds <- apply(mat, 2, sd)
lower <- median_da - sds
higher <- median_da + sds
res_mat <-
  matrix(
    rep(lower, each = length(varnames)),
    nrow = length(varnames),
    dimnames = list(seq_along(varnames), varnames)
  )
diag(res_mat) <- higher
data.frame(res_mat)
#>         var1       var2       var3
#> 1  1.0371615 -0.4337209 -0.1102957
#> 2 -0.5240104  2.4337209 -0.1102957
#> 3 -0.5240104 -0.4337209  1.3406680

## your version:
pred_da <-
  data.frame(
    var1 = c(
      median(da$var1) + 1 * sd(da$var1),
      median(da$var1) - 1 * sd(da$var1),
      median(da$var1) - 1 * sd(da$var1)
    ),
    var2 = c(
      median(da$var2) - 1 * sd(da$var2),
      median(da$var2) + 1 * sd(da$var2),
      median(da$var2) - 1 * sd(da$var2)
    ),
    var3 = c(
      median(da$var3) - 1 * sd(da$var3),
      median(da$var3) - 1 * sd(da$var3),
      median(da$var3) + 1 * sd(da$var3)
    )
  )

# check for equality of results:
all.equal(data.frame(res_mat), pred_da, check.attributes = FALSE)
#> [1] TRUE

# Adam B.'s version:
library(tidyverse)

median_da <- da %>%
  select(- ID) %>%
  mutate_all(~ median(.x)) %>%
  slice(1)

sds <- da %>%
  select(- ID) %>%
  summarise_all(sd)

add_sd <- function(varname, sd) {

  median <- median_da %>%
    pluck(varname)

  median_da %>%
    mutate(!!varname := median + sd)

}

preds_da <- map2(varnames, sds, ~ add_sd(varname = .x, sd = .y)) %>% bind_rows()
preds_da
#>        var1     var2      var3
#> 1 1.0371615 1.000000 0.6151862
#> 2 0.2565755 2.433721 0.6151862
#> 3 0.2565755 1.000000 1.3406680
median_da
#>        var1 var2      var3
#> 1 0.2565755    1 0.6151862
```

Body:
I want to have a matrix including one high (1 sd above average) and low (1 sd below median) expression for each variable out of multiple variables.

In one variant, for each variable I would like to have one high expression, while all other variables are low.

In addition, I would like to have a variant in which all other variables are set to 0 and then there is a high and a low expression for each variable.

I want to use it for model predictions.

For three variables I would already need for variant 1:

pred_da <- data.frame(var1 = c(median(da$var1)+1*sd(da$var1), median(da$var1)-1*sd(da$var1), median(da$var1)-1*sd(da$var1)), var2 = c(median(da$var2)-1*sd(da$var2), median(da$var2)+1*sd(da$var2), median(da$var2)-1*sd(da$var2)), var3 = c(median(da$var3)-1*sd(da$var3), median(da$var3)-1*sd(da$var3), median(da$var3)+1*sd(da$var3)))

For variant 2 it would be even more...

There should be a more efficient way to do it?


问:
Can't send email with nodemailer and outlook
i try to send an email with nodemailer and outlook but after multi try and multiple forum i visited, i found nothing.
I try all the solution i've seen but nothing work. can you help me please

this is my code :

```<code>{
 const path = require('path');
  var message=fs.readFileSync(path.join(__dirname+'../../../asset/templateMail/mail.html')).toString();
  message=message.replace('${user}', user.confirmation_code.toString());

  var nodemailer = require("nodemailer");

  const transporter = nodemailer.createTransport(

       {
       //service :"Outlook365",
         //pool:true,
      host: 'SMTP.office365.com',
      port: '587',
      secure:false,
      auth: { user: "it-factory-flex@outlook.fr", pass:  process.env.NODEMAILLERPASS },
      //secureConnection: false,
      //requireTLS:true,
      //tls: { ciphers: 'SSLv3' }

    }

  );

  var mailOptions = {
    name:"FlexOffice",
    from: "it-factory-flex@outlook.com",
    to: user.email,
    subject: "FlexOffice: Code d'inscription",
    html: message
  }
  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
    console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }

  });
}
</code>```

all the commented part are my test
and i always got this:

```<code>Error: Connection timeout
at SMTPConnection._formatError (/home/romain/bred/flex-server/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
at SMTPConnection._onError (/home/romain/bred/flex-server/node_modules/nodemailer/lib/smtp-connection/index.js:770:20)
at Timeout.<anonymous> (/home/romain/bred/flex-server/node_modules/nodemailer/lib/smtp-connection/index.js:235:22)
</code>```

答: solved, due to my network who block the flux.</p>

Body:
i try to send an email with nodemailer and outlook but after multi try and multiple forum i visited, i found nothing.
I try all the solution i've seen but nothing work. can you help me please

this is my code :

{
 const path = require('path');
  var message=fs.readFileSync(path.join(__dirname+'../../../asset/templateMail/mail.html')).toString();
  message=message.replace('${user}', user.confirmation_code.toString());

  var nodemailer = require("nodemailer");

  const transporter = nodemailer.createTransport(

       {
       //service :"Outlook365",
         //pool:true,
      host: 'SMTP.office365.com',
      port: '587',
      secure:false,
      auth: { user: "it-factory-flex@outlook.fr", pass:  process.env.NODEMAILLERPASS },
      //secureConnection: false,
      //requireTLS:true,
      //tls: { ciphers: 'SSLv3' }

    }

  );

  var mailOptions = {
    name:"FlexOffice",
    from: "it-factory-flex@outlook.com",
    to: user.email,
    subject: "FlexOffice: Code d'inscription",
    html: message
  }
  transporter.sendMail(mailOptions, function(error, info){
    if (error) {
    console.log(error);
    } else {
      console.log('Email sent: ' + info.response);
    }

  });
}

all the commented part are my test
and i always got this:

Error: Connection timeout
at SMTPConnection._formatError (/home/romain/bred/flex-server/node_modules/nodemailer/lib/smtp-connection/index.js:784:19)
at SMTPConnection._onError (/home/romain/bred/flex-server/node_modules/nodemailer/lib/smtp-connection/index.js:770:20)
at Timeout.<anonymous> (/home/romain/bred/flex-server/node_modules/nodemailer/lib/smtp-connection/index.js:235:22)


问:
Selecting updated rows between two tables
Good day,

I have to identical table structures. One is base table and second has incremental changes. I wish to have resulting table so that I pick he rows from the update, if present. Otherwise from old table.

Like so

```<code>table a: | Table b: | Result table:
key val  |  key val | key val
1   a    |  2   bb  |  1   a
2   b    |  4   dd  |  2   bb
3   c    |  5   ee  |  3   c
4   d    |          |  4   dd
                       5   ee
</code>```

I tried selecting B table values on inner join and full outer join where a.key is NULL or b.key is NULL and union. (Code not tested to functionality yet.)

```<code>select * from
(
  (select table_B.* from
    TABLE_A
      inner join
    TABLE_B
    on TABLE_A.key = TABLE_B.key
  )
  UNION
  (select * from
    TABLE_A
     full outer join
    TABLE_B
  on TABLE_A.key = TABLE_B.key
  where TABLE_A.key is NULL or TABLE_A.key is NULL
  )
)
</code>```

Is there an easier way to do this? I got the feeling that there has to be a more robust way to do this.

EDIT: I'm currently implementing this in the SPARK SQL context, but have had similar issues in the SQL server environment. Yet, I'm looking for a general idea.

答:
From my understanding this would help</p>

```<code>select key, val from Tableb
union
select key, val from Tablea a
where not exists(select 1 from Tableb where a.key = b.key)
</code>```

Body:
Good day,

I have to identical table structures. One is base table and second has incremental changes. I wish to have resulting table so that I pick he rows from the update, if present. Otherwise from old table.

Like so

table a: | Table b: | Result table:
key val  |  key val | key val
1   a    |  2   bb  |  1   a
2   b    |  4   dd  |  2   bb
3   c    |  5   ee  |  3   c
4   d    |          |  4   dd
                       5   ee

I tried selecting B table values on inner join and full outer join where a.key is NULL or b.key is NULL and union. (Code not tested to functionality yet.)

select * from
(
  (select table_B.* from
    TABLE_A
      inner join
    TABLE_B
    on TABLE_A.key = TABLE_B.key
  )
  UNION
  (select * from
    TABLE_A
     full outer join
    TABLE_B
  on TABLE_A.key = TABLE_B.key
  where TABLE_A.key is NULL or TABLE_A.key is NULL
  )
)

Is there an easier way to do this? I got the feeling that there has to be a more robust way to do this.

EDIT: I'm currently implementing this in the SPARK SQL context, but have had similar issues in the SQL server environment. Yet, I'm looking for a general idea.

Body:
From my understanding this would help

select key, val from Tableb
union
select key, val from Tablea a
where not exists(select 1 from Tableb where a.key = b.key)


问:
Checking membership in an array without for loop in matlab
I want to simplify this code to working without for loop.

```<code>for i=1:N
    for j=1:N
        if ismember(j,A)

           PID(i,i)=TFP(i,j)+ PID(i,i);

        end
    end
end
</code>```

in which A is a matrix that contains some labels. I previously stored TFP in the form of N*N sparse double. So, I came up with the following solution but I couldn't find a way to implement membership condition (Specified by ?) in that.

```<code>PID = sum(TFP).*(?);
</code>```

Can it be implemented without a loop?

答:
Instead of summing the result of element-wise multiplication you can use matrix multiplication. It computes the sum of products without creating a temporary array:</p>

```<code>J = ismember(1:N, A).';
PID = diag(TFP * J);
</code>```

Body:
I want to simplify this code to working without for loop.

for i=1:N
    for j=1:N
        if ismember(j,A)

           PID(i,i)=TFP(i,j)+ PID(i,i);

        end
    end
end

in which A is a matrix that contains some labels. I previously stored TFP in the form of N*N sparse double. So, I came up with the following solution but I couldn't find a way to implement membership condition (Specified by ?) in that.

PID = sum(TFP).*(?);

Can it be implemented without a loop?

Body:
Instead of summing the result of element-wise multiplication you can use matrix multiplication. It computes the sum of products without creating a temporary array:

J = ismember(1:N, A).';
PID = diag(TFP * J);


问:
Get DropDownList selected value
I have a DropDownList that I fill on Page_Load. When I try to get the selected value string id = myDropDownList.SelectedValue.ToString(); Every time I only got the 1st Value, but when I change the value of the DropDownList and check for the string id It always shows my the 1st value.

This is my Page_Load

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (commesseDataSource.Count != 0)
        {
            initComboCommesse();
        }

        if (Session["Matricola"] != null)
            matricolaDip = Convert.ToInt32(Session["Matricola"]);

        if (Session["LivLogin"] != null)
            livlogin = Convert.ToInt32(Session["Matricola"]);

    }
</code>```

this Is how I bind the DropDown

```<code>private void initComboCommesse()
    {
        myDropDownList.DataTextField = "Value";
        myDropDownList.DataValueField = "Key";
        myDropDownList.DataSource = commesseDataSource;
        myDropDownList.DataBind();
    }
</code>```

I've already tried to

```<code> protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
 {
      string id = myDropDownList.SelectedValue.ToString(); // I always get the 1st value of the Drop Down
 }
</code>```

And also

```<code> protected void myDropDownList_TextChanged(object sender, EventArgs e)
 {
      string id = myDropDownList.SelectedValue.ToString(); // I always get the 1st value of the Drop Down
 }
</code>```

But none of these had worked, I would like to know how to get the selected value of the DropDownList, every time I selected a new value In the DropDownList

答:
Try This:

When You Insert In your DropDownList Value In Database then you need to change:

```<code>string id = myDropDownList.SelectedItem.Value.ToString();
</code>```

Title: Get DropDownList selected value

Body:
I have a DropDownList that I fill on Page_Load. When I try to get the selected value string id = myDropDownList.SelectedValue.ToString(); Every time I only got the 1st Value, but when I change the value of the DropDownList and check for the string id It always shows my the 1st value.

This is my Page_Load

protected void Page_Load(object sender, EventArgs e)
    {
        if (commesseDataSource.Count != 0)
        {
            initComboCommesse();
        }

        if (Session["Matricola"] != null)
            matricolaDip = Convert.ToInt32(Session["Matricola"]);

        if (Session["LivLogin"] != null)
            livlogin = Convert.ToInt32(Session["Matricola"]);

    }

this Is how I bind the DropDown

private void initComboCommesse()
    {
        myDropDownList.DataTextField = "Value";
        myDropDownList.DataValueField = "Key";
        myDropDownList.DataSource = commesseDataSource;
        myDropDownList.DataBind();
    }

I've already tried to

 protected void myDropDownList_SelectedIndexChanged(object sender, EventArgs e)
 {
      string id = myDropDownList.SelectedValue.ToString(); // I always get the 1st value of the Drop Down
 }

And also

 protected void myDropDownList_TextChanged(object sender, EventArgs e)
 {
      string id = myDropDownList.SelectedValue.ToString(); // I always get the 1st value of the Drop Down
 }

But none of these had worked, I would like to know how to get the selected value of the DropDownList, every time I selected a new value In the DropDownList

Body:
Try This:

When You Insert In your DropDownList Value In Database then you need to change:

string id = myDropDownList.SelectedItem.Value.ToString();