text:
Q: Obtener valor que regresa una petición AJAX Buenas tardes, tengo el siguiente escenario. Este mi login.html

<!DOCTYPE html>

 <title></title>
 <link rel="stylesheet" href="estilos/estilos.css"/>
 <meta charset="utf-8">

Ingresar

 <form action="Controlador/login.php" method="post" id="formlogin">

       Usuario:
       <input type="text" name="usuario" id="usuario">

       Password:
       <input type="password" name="password" id="pass">

       <input id="botonl" type="submit">

                 ¡Registrate!

     </form>

Este manda las variables usuario y password a Controlador/login.php que es donde, enviadas las 2 variables se procesan para comprobar el ingreso exitoso del usuario.

<?php
 require_once('../Modelo/class.conexion.php');
 require_once('../Modelo/class.consultas.php');

 $usuario = $_POST['usuario'];
 $pass = $_POST['password'];

 if(strlen($usuario) > 0 && strlen($pass) > 0){
  $consultas = new Consultas();
  $mensaje = $consultas->verificarUsuario($usuario, $pass);
   if (is_string($mensaje)) {
    echo $mensaje;
   }else{
    session_start();
    foreach ($mensaje as $resultado) {
         $user = $resultado['nickname'];
         $rango = $resultado['rango'];
    }
     $_SESSION['usuario'] = $user;
                 $_SESSION['rango'] = $rango;

                if ($_SESSION['rango']=='Administrador'){
                                         echo "Administrador";
     //echo "header('Location: ../manga.html');";
    }elseif ($_SESSION['rango']=='starter') {
     header("Location: ../login.html");
    }elseif ($_SESSION['rango']=='Viper') {
     header("Location: ../index.html");
    }
   }
  }else{
  echo "Por favor rellena ambos campos";
 }
?>

El método verificarUsuario , es el siguiente:

public function verificarUsuario($nombre_usuario,$password_usuario){
 $modelo = new Conexion();
     $conexion = $modelo->get_conexion();
 $sql = "select nickname, password, idUsuario, rango
   from usuarios
   where nickname = :nombre_usuario
   and password = :password_usuario";
 $statement = $conexion->prepare($sql);
 $statement->bindParam(':nombre_usuario', $nombre_usuario);
 $statement->bindParam(':password_usuario', $password_usuario);
 if(!$statement){
  return "Error verifique parametros";
 }else{
  $statement->execute();
  if($statement->rowCount() > 0){
   return $statement->fetchAll(PDO::FETCH_ASSOC);
  }else{
   return "no hay usuarios con registrados con esos datos";
  }
 }
   }

Hasta ahí todo bien, ahora como mi login.html tiene esa referencia a mi archivo JS donde con JQuery y Ajax intento hacer que dependiendo del rango de usuario logueado lo mande a una pagina u otra.
Teniendo el siguiente fragmento de código JS

$('#botonl').click(function(event) {
  event.preventDefault();
  usuario = $('#usuario').val();
  password = $('#pass').val();

  $.ajax({
   url: 'Controlador/login.php',
   type: 'POST',
   data: {usuario, password},
   beforeSend:function(){
    console.log("Se esta procesando tu peticion");
   }
  })
  .done(function(data) {
   console.log("success");
                         alert(data);
   if (data == 'Administrador') {
    document.location.href = "manga.html";
    alert(data);
   }
   else{
    alert("ERROR POR QUE TE ODIO");
   }
   }
  })
  .fail(function() {
   console.log("error");
  })
  .always(function() {
   console.log("complete");
  });
 });

El código no funciona correctamente, por ejemplo, si ingreso como un usuario Administrador, me manda el alert con el mensaje "Administrador" mas sin embargo en el if entra al else y me manda el alert "ERROR PORQUE TE ODIO", por lo tanto no me redirige hacia donde se tiene establecido, y con los otros casos, en el alert me trae todo el código html de dichas páginas.
Cualquier ayuda u observación será bien recibida, muchas gracias.

A: Vale tendrías que hacer la prueba pero creo que solo esta mal tu $.ajax
al enviar tu data porque este debería de enviar un objeto json y tu no estas haciendo eso:
Entonces lo que esta mal es:

data: {var1, var2},

Este debería ser
data: {var1:var1, var2:var2},
Esto solo porque tu obtienes los datos en login.php de esta forma:
$usuario = $_POST['var1'];
$pass = $_POST['var2'];

Lo conveniente es tener todo en orden y con su nombre como debería de ser, para que otros desarrolladores puedan entender tu código.
Podrias cambiar el data de tu ajax por:
data: {usuario:var1, password:var2},
Y Obtenerlos en login.php asi:
$usuario = $_POST['usuario'];
$pass = $_POST['password'];

Espero que esto resuelva tu problema.

A: Por si a alguien le sirve puede tomar esto como apoyo.
Mi codigo HTML.

<!DOCTYPE html>

 <title></title>
 <link rel="stylesheet" href="estilos/estilos.css"/>
 <meta charset="utf-8">

Ingresar

   <form action="Controlador/login.php" method="POST" id="formLogin">

     Usuario:
     <input type="text" name="usuario" id="usuario">

     Password:
     <input type="password" name="password" id="pass">

     <input id="botonIngresar" type="submit">

     ¡Registrate!

   </form>

El código PHP: Aquí lo que hice mejor, fue que dependiendo de la condición que se cumpliera, esta regresará en la petición AJAX un json_encode generado en este archivo PHP.

<?php
 require_once('../Modelo/class.conexion.php');
 require_once('../Modelo/class.consultas.php');

 $usuario = $_POST['usuario'];
 $pass = $_POST['password'];

 if(strlen($usuario) > 0 && strlen($pass) > 0){
  $consultas = new Consultas();
  $mensaje = $consultas->verificarUsuario($usuario, $pass);
   if (empty($mensaje)) {
    //echo ("No hay usuario registrados con esos datos");
    $error = ['No existen usuarios registrados con esos datos'];

    $arrayJson = json_encode($error);
    print_r($arrayJson);
   }else{
    foreach ($mensaje as $resultado) {
         $user = $resultado['nickname'];
         $id = $resultado['idUsuario'];
      $pass = $resultado['password'];
        $rango = $resultado['rango'];
        $estadoCuenta = $resultado['estadoCuenta'];
    }

    if ($estadoCuenta == 'ban') {
     $error = ['Usted no tiene acceso al sistema, contacte a la administración'];

     $arrayJson = json_encode($error, JSON_UNESCAPED_UNICODE);
     print_r($arrayJson);
    }else{
     session_start();

     $_SESSION['idUsuario'] = $id;
      $_SESSION['usuario'] = $user;
          $_SESSION['password'] = $pass;
          $_SESSION['rango'] = $rango;

          $arrayJson = json_encode($mensaje);
     print_r($arrayJson);
    }
  }
 }else{
  //echo "Por favor rellena ambos campos";
  $error = ['Por favor rellena ambos campos'];

  $arrayJson = json_encode($error);
  print_r($arrayJson);
 }
?>

Y este es el código de mi archivo JS

$(document).ready(function() {
 //EFECTUAR INGRESO AL SISTEMA MEDIANTE PETICION AJAX
 $('#botonIngresar').click(function(event) {
  event.preventDefault();
  usuario = $('#usuario').val();
  password = $('#pass').val();
  var rangoUsuario;

  $.ajax({
   url: 'Controlador/login.php',
   type: 'POST',
   dataType: 'JSON',
   data: {usuario, password},
   beforeSend:function(){
    console.log("Se esta procesando tu peticion");
   }
  })
  .done(function(data) {
   console.log("success");
     $.each(data, function(index, val) {
      if (val.estadoCuenta == 'ok') {
       if (val.rango == 'Administrador') {
        document.location.href = "admin.php"
       }else if(val.rango == 'Viper' || val.rango == 'starter'){
        document.location.href = "index.php"
       }else if(val == 'No existen usuarios registrados con esos datos'){
        alert(val);
       }else if(val == 'Por favor rellena ambos campos'){
        alert(val);
       }
      }else{
       alert(val);
      }
     });
  })
  .fail(function() {
   console.log("error");
  })
  .always(function() {
   console.log("complete");
  },'json');
 });
});

Espero que le sea de utilidad a alguien más. Saludos.


text:
Q: writeTextElement() of QXmlStreamWriter crashed when writting the content of a big file Here is the qt code that crash:
Writing the content of a 130MB binary file will crash, but writing a 2MB binary file will not.
Is there any solution for writeTextElement to write big file content? Thanks
env: qt opensource 4.8.7
Visual Studio 2010
Windows 10
big file: https://1drv.ms/u/s!Ap_EAuwC9QkXijOmXqxp9DEav3gm?e=iha0uI
test project:  https://1drv.ms/u/s!Ap_EAuwC9QkXijWzOlpaWmtzOdtz?e=fDpo93
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QXmlStreamWriter>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QByteArray mContentBuffer;

    QFile file("C:\\Work\\bigfile.xar");

    if(!file.open(QFile::ReadOnly))
    {
        return -1;
    }

    mContentBuffer = file.readAll();
    file.close();

    QFile profile("C:\\Work\\profile.xml");

    if(!profile.open(QFile::WriteOnly|QFile::Truncate))
    {
        return -1;
    }

    QXmlStreamWriter stream(&profile);

    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    stream.writeStartElement("Profile");

    stream.writeTextElement("Content", mContentBuffer.toBase64());

    stream.writeEndElement(); // Profile
    stream.writeEndDocument();

    return a.exec();
}

A: The minimal reproducible example was a life saver.
Several things seem to be required to solve your issue in a clean way.

*

*Mainly, the file must be read in chunks.To be precise and as mentioned in that other question, in chunks whose size is a multiple of 3 bytes (I have hardcoded 9000 below).You will need to look for the value that gives you the best performance while guaranteeing it never fails yourself.

*Instead of writing in the XML in 1 go, I made it so the XML file is being written each chunk at a time.To achieve that, the code creates the node first, then uses the writeCharacters method to write text in it.

*Note the if (mContentBuffer.isEmpty()) right before writing. It is indeed specified in Qt Assistant that the read function has no way of reporting errors; returning an empty QByteArray can mean either that no data was currently available for reading, or that an error occurred. Considering the while loop, it can only be an error, so we abort everything.BTW, I think but have not tested that you can just end the document, and the XML stream writer will close everything it needs to have a valid XML.

*Just to make it clean, I reordered the lines of codes so that the XML file is opened before the xar file. I also added QtCore/ on every include. Not sure that last point is going to be useful on your real code.

This code implements all the above changes.It should not crash and while you will not be able to test the output on the 130MB file, you should be able to test your code vs mine on the 2MB file you has successfully read from before.
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtCore/QXmlStreamWriter>

int main(int argc, char* argv[])
{
    QCoreApplication a(argc, argv);

    QFile profile("C:\\Work\\profile.xml");
    if (!profile.open(QFile::WriteOnly | QFile::Truncate))
        return -1;

    QXmlStreamWriter stream(&profile);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    stream.writeStartElement("Profile");
    stream.writeStartElement("Content");

    QFile file("C:\\Work\\bigfile.xar");
    if (!file.open(QFile::ReadOnly))
        return -1;

    while (!file.atEnd()) {
        QByteArray mContentBuffer = file.read(9000);
        if (mContentBuffer.isEmpty()) {
            stream.writeEndDocument();
            file.close();
            profile.close();
            return -1;
        }
        stream.writeCharacters(mContentBuffer.toBase64());
    }
    file.close();

    stream.writeEndElement(); // </Content>
    stream.writeEndElement(); // </Profile>
    stream.writeEndDocument();

    return a.exec();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: gradle Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'
*

*I'm building ghidra according to the installation guide.
Everything goes fine Until I get here.

*Once I call $ gradle buildGhidra I get the following error:

> Could not target platform: 'Java SE 11' using tool chain: 'JDK 8 (1.8)'

This seems weird because I do have java 11:
$ java --version
openjdk 11.0.8 2020-07-14
OpenJDK Runtime Environment (build 11.0.8+10-post-Ubuntu-0ubuntu118.04.1)
OpenJDK 64-Bit Server VM (build 11.0.8+10-post-Ubuntu-0ubuntu118.04.1, mixed mode, sharing)

What am I missing?

A: Gradle uses the java distribution defined in your JAVA_HOME environment variable - it does not look at the java executable in your path. So make sure this variable points to a valid JDK 11 path. You can verify if it is set up correctly by running gradle --version, e.g.
$ echo %JAVA_HOME%
C:\Work\JDKs\jdk-11.0.8+10

$ gradle --version

------------------------------------------------------------
Gradle 6.6
------------------------------------------------------------

Build time:   2020-08-10 22:06:19 UTC
Revision:     d119144684a0c301aea027b79857815659e431b9

Kotlin:       1.3.72
Groovy:       2.5.12
Ant:          Apache Ant(TM) version 1.10.8 compiled on May 10 2020
JVM:          11.0.8 (AdoptOpenJDK 11.0.8+10)
OS:           Windows 10 10.0 amd64

(Notice the JVM part above.)

A: I got this problem when trying to build using gradle through Intellij.
In my case I had two JDK's JDK1.8 and JDK 11 installed and configured in Intellij.
For Gradle it was taking JDK1.8 as default JVM.
I solved the issue using below steps :

*

*Open Intellij

*Go to Preferences

*Go to "Build, Execution, Deployment" -> "Build Tools" -> Gradle

*Search for "Gradle JVM". Change it to desired JVM

*Try to rebuild the app

A: Are you using an IDE? Make sure that in your Gradle settings, Gradle is using the same java version as your project, this can be easily configured in Intellij https://www.jetbrains.com/help/idea/gradle-jvm-selection.html#jdk_existing_project

A: *

*It turns out that gradle was after all the one to blame.

*Probably similar to this post, I upgraded to gradle-6.7.

*Then, calling gradle-6.7 --version, without any JAVA_HOME change whatsoever, I got:

------------------------------------------------------------
Gradle 6.7-rc-3
------------------------------------------------------------

Build time:   2020-09-30 19:16:51 UTC
Revision:     836e96a80625c9c48b612e662e3b13bd2e2f4c3b

Kotlin:       1.3.72
Groovy:       2.5.12
Ant:          Apache Ant(TM) version 1.10.8 compiled on May 10 2020
JVM:          11.0.8 (Ubuntu 11.0.8+10-post-Ubuntu-0ubuntu118.04.1)
OS:           Linux 5.4.0-48-generic amd64

Which probably "proves" gradle is indeed the one to blame

A: Changing my agent label in the Jenkinsfile, to openjdk11 fixed this error for me.
agent {
    label 'openjdk11'
}


text:
Q: Hiding processes on Unix/Linux I found an interesting article about how to hide specific processes on linux from process monitoring tools like ps, top, lsof, ...
Person states that there are several possible ways to hide processes:

*

*Using a proper framework: there are a bunch of very good frameworks, like SELinux and Grsecurity that do, among other
  things, exactly this. In a production system, I would absolutely
  consider these, although today I want to  get my hands dirty and have
  fun creating something from scratch.

*Modify top/ps/... binaries: I could grab the source code of each of these tools, implement my own "hiding linux processes"
  logic, recompile, and replace the binaries. Very inefficient and time
  consuming.

*Modify libc: I could modify the readdir() function inside libc and input the code to exclude the access to some /proc files.
  But recompiling libc is a burden, not to mention the libc code
  tends to be very hard to understand.

*Modify the system calls in the kernel: This is the most advanced, and it would work by intercepting and modifying the getdents()
  system call directly in the kernel with a custom module. It's
  definitely tempting, but I won't follow this route today because I'm
  already very familiar with how the system call interception works in
  sysdig, so I want to do something new.

  I decided to go for an intermediate solution, one that is interesting
  and simple enough to implement in an hour or so: it's a variant of
  "modifying libc" based on a tricky feature offered by the Linux dynamic linker (the component that takes care of loading the various
  libraries needed by a program at runtime), called preloading.
With preloading, Linux is kind enough to give us the option to load a
  custom shared library before the other normal system libraries are
  loaded. This means that, if the custom library exports a function with
  the same signature of one found in a system library, we are literally
  able to override it with the custom code in our library, and all the
  processes will automatically pick our custom one!
This sounds like a solution to my problem, because I could write a
  very simple custom library that overrides libc's readdir(), and write
  the logic to hide the process! The logic would be fairly
  straightforward too: every time I see that the /proc/PID directory
  (where PID is the PID of the process having the name "evil_script") is
  being read, I just block that access in a clean way, thus hiding the
  entire directory! I went ahead and implemented these thoughts in code.
  You can get the sources at
  https://github.com/gianlucaborello/libprocesshider/blob/master/processhider.c
  (it's actually less than 100 lines of code including comments, so go
  read it!). Once the code is written, let's compile it as a shared
  library, and install it in the system path.

Source code: processhider.c
So the steps are:

*

*make => gcc -Wall -fPIC -shared -o libprocesshider.so processhider.c -ldl

*mv libprocesshider.so /usr/local/lib/ (as root)

*echo /usr/local/lib/libprocesshider.so >> /etc/ld.so.preload

Now back to my question/problem: Here it is described for Linux systems. I tested it on my Ubuntu 18.04 (64 bit) machine and everything worked fine - process was now hidden from ps. Additionally I tested it on my another machine where FreeBSD 11.0 (64 bit) is installed.
First I had to remove following part of the code:
DECLARE_READDIR(dirent64, readdir64);

because I got an error (dirent64 wasn't defined in dirent.h - I just used locate dirent.h and compared the code to some internet sources):
processhider.c: In function 'readdir64':
processhider.c:87:37: error: dereferencing pointer to incomplete type 'struct dirent64'
                 get_process_name(dir->d_name, process_name) &&          \
                                     ^
processhider.c:97:1: note: in expansion of macro 'DECLARE_READDIR'
 DECLARE_READDIR(dirent64, readdir64);
 ^
*** Error code 1

After removing DECLARE_READDIR(dirent64, readdir64); I got another error complaining about -ldl flag:
/usr/local/bin/gcc5 -Wall -fPIC -shared -o libprocesshider.so processhider.c -ldl
/usr/local/bin/ld: cannot find -ldl
collect2: error: ld returned 1 exit status
*** Error code 1

Stop.

I found a solution where one could replace -ldl with -L/usr/local/lib where my libdl.so file is located (meaning of "collect2: error: ld returned 1 exit status" error).
Then I was able to compile the code. I placed the library into /usr/local/lib/ and added it to /etc/ld.so.preload.
However when I called my script evil_script.py (Code was different (no more UDP packets spam), but I still have while true loop and time.sleep(60) so the process should be there) it still appeared in the process list (ps auxww). Maybe /etc/ld.so.preload is not working? Can be there some problem with ld.so shared library? Is there any way how I can test what goes wrong at which point?

A: Method 2 and 3 (modifying ps, top, libraries), is prone to walk around breach. E.g. an attacker can just use there own ps.
A better way would be to block these tools from accessing info on processes of other users. Then running the processes to be hidden as a different user.
For the 1st part, edit /etc/fstab, to include
#protect /proc
proc /proc proc defaults,nosuid,nodev,noexec,relatime,hidepid=2,gid=admin 0 0


text:
Q: macro para eliminar filas duplicadas quiero hacer una macro para eliminar filas duplicadas por ID. El rango no debe seleccionar filas fijas, ya que el fichero se va alimentando con nuevas filas. las columnas siempre permanecen las mismas y en el mismo orden. ¿Alguien me puede ayudar? Gracias!

A: Para eliminar las filas duplicadas en documentos de Excel puedes hacer uso de una Macro, en tu ventana de Visual Basic vas a agregar el siguiente código:
Sub nombremacro()
Dim fila As Long
  With Application
         For fila = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
          If .WorksheetFunction.CountIf(Range(«A:A»), _
              Cells(fila, 1)) > 1 Then Cells(fila, 1).EntireRow.Delete
      Next fila
       End With
End Sub

Después de guardar tu Macro ya las próximas veces que quieras ejecutarla debes hacerlo desde Herramientas/Macro y seleccionar la Macro según el nombre que le asignaste, en el ejemplo le asigne el nombre de nombremacro


text:
Q: Flutter - Wrong list casting after API call I have created an http service for handling requests and made a generic response. It works when passing the Generic as a primitive, but when passing a List (even dynamic), it throws an error during assigning. Skipping typing and casting later on doesn't work either. I am stumped.
class Room {
  final String name;

  const Room({required this.name});
}

  List<Room> ownRoomsList = [];
  List<dynamic> savedRooms = [];

  Future<void> updateRooms() async {
    HttpService httpService = new HttpService();
    await httpService.init();
    final response = await httpService.request<List<Room>>(
        url: "puff/rooms", method: Method.POST);
    if (response != null) {
      setState(() {
        ownRoomsList = response.data; // Error here.
      });
    }
  }

class APIResponse<T> {
  final bool success;
  final T data;
  final String message;

  const APIResponse(
      {required this.success, required this.data, required this.message});

  factory APIResponse.fromJson(Map<String, dynamic> json) {
    return APIResponse(
      success: json['success'],
      data: json['data'],
      message: json['message'],
    );
  }
}

class HttpService<T> {
  Dio? _dio;

  var logger = Logger(
    printer: PrettyPrinter(),
  );

  Future<HttpService> init() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final userId = pref.getInt('userId');
    final headers = {
      "Content-Type": "application/json",
      "userId": userId.toString()
    };
    _dio = Dio(BaseOptions(baseUrl: BASE_URL, headers: headers));
    initInterceptors();
    return this;
  }

  void initInterceptors() {
    _dio!.interceptors.add(
      InterceptorsWrapper(
        onRequest: (requestOptions, handler) {
          logger.i(
              "REQUEST[${requestOptions.method}] => PATH: ${requestOptions.path}"
              "=> REQUEST VALUES: ${requestOptions.queryParameters}"
              "=> POST VALUES: ${requestOptions.data}"
              "=> HEADERS: ${requestOptions.headers}");
          return handler.next(requestOptions);
        },
        onResponse: (response, handler) {
          logger
              .i("RESPONSE[${response.statusCode}] => DATA: ${response.data}");
          return handler.next(response);
        },
        onError: (err, handler) {
          logger.i("Error[${err.response?.statusCode}]");
          return handler.next(err);
        },
      ),
    );
  }

  Future<APIResponse<T>?> request<T>(
      {required String url,
      required Method method,
      Map<String, dynamic>? params}) async {
    Response response;

    try {
      if (method == Method.POST) {
        response = await _dio!.post(url, data: params);
      } else if (method == Method.DELETE) {
        response = await _dio!.delete(url);
      } else if (method == Method.PATCH) {
        response = await _dio!.patch(url);
      } else {
        response = await _dio!.get(url, queryParameters: params);
      }

      if (response.statusCode == 200) {
        return APIResponse.fromJson(jsonDecode(response.data));
      } else if (response.statusCode == 401) {
        //throw Exception("Unauthorized");
      } else if (response.statusCode == 500) {
        //throw Exception("Server Error");
      } else {
        //throw Exception("Something went wrong");
      }
    } on SocketException catch (e) {
      logger.e(e);
      //throw Exception("No Internet Connection");
    } on FormatException catch (e) {
      logger.e(e);
      //throw Exception("Bad response format");
    } on DioError catch (e) {
      logger.e(e);
      //throw Exception(e);
    } catch (e) {
      logger.e(e);
      //throw Exception("Something went wrong");
    }

    return null;
  }
}

Error:
type 'List<dynamic>' is not a subtype of type 'List<Room>'

A: As it happens, Dart does not support dynamic typing of non-primitives, so the casting inside never worked. First, need to add a fromJson to the type, change httpService.request<List<Room>> to httpService.request<List<dynamic>> and then process the answer from ownRoomsList = response.data; to ownRoomsList = response.data.map((e) => Room.fromJson(e)).toList();
class Room {
  final String name;

  const Room({required this.name});

  factory Room.fromJson(Map<String, dynamic> json) {
    return Room(name: json['name']);
  }
}


text:
Q: replace values of keys in json1 from Json2 I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:
 one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the
 second JSON --> for ex: {"blog_heading":"def"}

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:
  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.

So i am trying as below,
$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);

id5 data is : $id5
  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================

Log of $id :
stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )

Please suggest me how can i achieve this... Anything i am doing wrong here

A: Please try that:
$j1 = '{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$j2 = '{"blog_heading":"def"}';

$result = json_encode(
    array_merge(
        json_decode($j1, true),
        json_decode($j2, true)
   )
);

A: <?php
$json1='{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$json2='{"blog_heading":"def"}';

$json1=json_decode($json1);
$json2=json_decode($json2);
foreach ($json1 as $key => $value) {
    if($json2->$key){
        $json1->$key=$json2->$key;
    }
}

$json1=json_encode($json1);
$json2=json_encode($json2);

A: If you have only one element in array,Do like this
$a = json_decode('{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}',true);
$b = json_decode('{"blog_heading":"def"}',true);
$a['blog_heading'] = $b['blog_heading'];
print_r($a);

If you have multiple element like this :
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"blog_heading":"def"},{"blog_heading":"hello"}]',true);
$return = array();
for ($i=0; $i < count($c); $i++) {
    $c[$i]['blog_heading'] = $d[$i]['blog_heading'];
    $return[] = $c[$i];
}
print_r($return);

If you want to replace value by specific id
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":7,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);
$return = array();

for ($i=0; $i < count($c); $i++) {
    if($d[$i]['id'] == $c[$i]['id']) {
        $c[$i]['blog_heading'] = $d[$i]['blog_heading'];
    }
    $return[] = $c[$i];
}
print_r($return);

Checking dynamic key value pair :
$c = json_decode('[{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"},
{"id":8,"active":1,"blogId":"abc","blog_heading":"xyz"}]',true);
$d = json_decode('[{"id":6,"blog_heading":"def"},{"id":9,"blog_heading":"hello"}]',true);

$return = array();
for ($i=0; $i < count($c); $i++) {
    $result = array_intersect_key($c[$i], $d[$i]);
    foreach ($result as $key => $value) {
        $c[$i][$key] = $d[$i][$key];
    }
    $return[] = $c[$i];
}
print_r($return);

Check demo here


text:
Q: C# Round Value of a Textbox I have a small calculator that I am creating in C# (Sharp Develop). The user enters two values and the code returns the third. I am having trouble rounding the third value once it is returned. I have been through a couple of forums and the msdn site and I understand the code that is posted there, but I cant seem to make it work in my situation. Can anyone provide a little help? Reference the code below.
int y;
decimal x, z;
x = int.Parse(tb2_fla.Text);
y = int.Parse(tb2_e.Text);
z = (x * y * 1.732050808m) / 1000;
tb2_kva.Text = z.ToString();

I welcome both assistance and criticism
Greg

A: Use Math.Round. Or, since you're going into a string, you could use either the Standard Numeric Format Strings, or the Custom ones.
Math.Round(z, 2).ToString();
z.ToString("0.00");

A: Could Math.Round(z, nrofdecimals) be the answer to your problem?

A: Try the Math.Round function.

A: Try using Math.Round()
tb2_kva.Text = Math.Round(z, # Places).ToString();

A: Look up Numeric Format Specifiers in the help. Something like:
tb2_kva.Text = String.Format("{0:d2}", z);

to format to 2dp


text:
Q: laravel - The stream or file "/storage/logs/laravel.log" could not be opened in append mode: failed to open stream: Permission denied My application is being deployed to AWS Lightsail(LAMP) and when I try to run artisan migrate it says:
The stream or file "/opt/bitnami/projects/app-name/storage/logs/laravel.log" could not be opened in append mode: failed to o
pen stream: Permission denied

What I have tried so far is to allow access to storage via:
sudo chmod -R 775 storage

Also, I can only access my home page if I use sudo chmod -R 777 storage but not sudo chmod -R 775 storage. I am not sure why.
but it is still giving me the error. What seems to be this issue?

A: This commands were helpful:
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

also follow this link


text:
Q: Send an email using GWT Java I have been reviewing the email solutions in stackoverflow and am trying to use the following solution:
        EmailTask email = new SimpleEmail();
        //Production
        email.setHostName("mail.hostname.net");
        email.setSmtpPort(25); //No authentication required
        //Test
        //            email.setHostName("smtp.googlemail.com");
        //            email.setSmtpPort(587); //Authentication required
        //            email.setAuthenticator(new DefaultAuthenticator("me@gmail.com", "mypwd"));

        email.setTLS(true);
        email.setFrom("ATA@hostname.net");
        email.setSubject("New Award Tracking Application account created.");
        email.setMsg("Please set up a new Award Tracking Application account for: " + account);
        email.addTo(to);
        email.send();
        System.out.println("Mail sent!");

On the first line (EmailTask email = new SimpleEmail();) I get the error

SimpleEmail cannot be resolved to a type

I have imported  import org.apache.tools.ant.taskdefs.email.EmailTask;  as per the Quick fix when I entered the code. Is there another library I should use?
Any assistance would be greatly appreciated.
Regards,
Glyn

A: Add Commons Email in your class path https://commons.apache.org/proper/commons-email/
Check the user guide for a simple example.
Class SimpleEmail

A: GWT is a front-end framework, while what you are asking for, sending mails, is a business process.
This link might help you get started: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html


text:
Q: javascript: console.log not working in this context? (function( $ ){ $.fn.openlayers = function( mapElementId, options ) {
        alert(console.log);
        console.log(options);
        ...
    }
});

Im trying to extend functionality in a javascript library, but much to my suprise, when i got started i realized that nothing was being logged by console.log.. I know that the code is being executed due to the alert() firing properly. However the returned response from the alert function seems to be "function(){}", is that correct? or is in fact console.log and empty function?
So any clues on what's going on here, and why console.log isn't working?

I think i might have found the culprit. Im working with a OpenLayers javascript file, and i can see that their library sets
OpenLayers.Console={log:function(){},...

However, this is uppercase Console, but maybe that doesn't make a difference? I also have to be in the OpenLayers scope, which i can't really see that i am. So i'm still a little baffled. But it would explain why i'm seeing an empty function

This is the output i get from typing "console" in the debug window of chrome after loading the application where this error occurs.
assert: function (){}
count: function (){}
debug: function (){}
dir: function (){}
dirxml: function (){}
error: function (){}
group: function (){}
groupEnd: function (){}
info: function (){}
log: function (){}
profile: function (){}
profileEnd: function (){}
time: function (){}
timeEnd: function (){}
trace: function (){}
warn: function (){}
__proto__: Object

So it would seem that something, possibly the openlayers javascript is overriding the native console.

A: Just click on ALL, you will definitely see the  console.log output.

Hope it helps...!!!

A: Add the following line before OpenLayer script to tell it not to override the console functions.
<script type="text/javascript">
    console.firebug=true;
</script>


text:
Q: Total scores are normally distributed, but subtest scores are not; what to do? I have two sets of data for males and females: $n=33$. I'd like to compare test results for both groups. I want to do a $t$ test, and I know my data should be normally distributed if I want to use a parametric test. I also know that if $n>30$, then the $t$ test normality assumption can be violated. Anyway, what would you suggest? Test total scores are normally distributed for both groups, but 6 of the subtest scores are not.

A: Too long for a comment; hopefully it will expand to become a better answer as issues become clarified.
Much of what you say you know ain't so!

I have two sets of data for males and females: n is 33.

Is that 33 for each group or 33 in total?

I want to do a t test,

Why would "doing a t-test" rather than answering the question you want to ask the data (to which 'do a t-test' might be one answer) be what you want?
(It's like saying "I want to drive the car" when you really mean "I want to go buy something from the hardware store". It is possible you might want to drive a car because you think it's a fun activity -- I know I enjoy doing a t-test now and again ... but I bet that's not the case here. )

and I know my data should be normally distributed if I want to use a parametric test.

Not so. If you want to do a parametric test that also assumes normality, then yes, it's good to have something like a normal distribution, especially with small samples (when you have no good chance of telling when it's violated).
I could do something akin to a t-test (a two-sample comparison of means) using a GLM, for example, that assumed some distribution other than normal (say a Gamma, for example), and it would still be a parametric test.
But for some tests that assume normality, and some non-normal distributions it matters a lot less than with others (some parametric tests of equality of variance, for example, are quite sensitive to normality).

I also know that if n is larger than 30, then the t test normality assumption can be violated.

Also not so. Indeed, I think this is bad advice. In some cases you can happily violate normality with $n=2$ (if it's non-normal in ways that mean the resulting t-test still behaves quite reasonably for your purposes). In other cases, $n=1000$ isn't enough -- but in that case sometimes $n=100,000$ might be fine.
The value "30", for all its popularity in certain areas, is an arbitrary number, it has no general applicability.

But any way I want to ask you what you would suggest. Test total scores are normally distributed for both groups, but 6 of the subtest scores are not.

How do you know some quantity is normally distributed? (From the following sentence I get the impression your scores are probably both discrete and bounded and so, a priori not normal.)
The distribution of subtest scores will only matter if you need to compare subtest scores.
(Highlighted, because that sentence responds directly to the question in the title and it might not be noticed if I don't make it obvious.)

The first things to consider, in approximate order:
1) What questions do you need to answer? (You have to tell us this one)
2) What's a good way to answer those questions? (This is where we might be of some help)
Some general comments:

*

*With heavily discrete, moderately skewed data, a Wilcoxon-Mann-Whitney test may not be a substantially better choice than a t-test (indeed, it might be worse).

*testing normality to see if you can use a t-test answers the wrong question (you're interested in how the properties of your test are affected, rather than whether you have a large enough sample to pick up the difference)

*testing normality and then choosing a test conditional on the outcome of that test leads the tests you do when you make the comparison to not have the desired properties. See some of the links given here. (It may be better, for example, to simply not assume normality with very small sample sizes.)
If you can make the necessary assumptions, at least under the null (such as exchangeability), you might consider some form of permutation test, perhaps.


text:
Q: Chrome cursor properties only work on edge of object? Using: Chrome 18.0.1025.151 on MAC OSX 10.6.8
I'm running into an interesting issue.  When using Chrome the cursor property only changes if you hit the very edge of an DOM object.  For example: in the below usage the cursor will only change to the "move" cursor on the very edge of the image. When its completely over the image it goes back to the pointer?
Any idea whats going on here?
CSS:
.handle{cursor:move}

Usage:
<img alt="Lounge" class="handle" src="SOME URL" />

A: Try

*

*Width

*Height

*Block

So:
.yourObject {
position: relative;
width: 50px;
height: 50px;
display: block;
cursor: move;
}

A: I had the same bug on my Macbook Pro running 10.12.3. It appears to be caused by other programs. When certain programs are open/in certain states, cursor: CSS rules will only work on object edges, regardless of browser. Experienced this bug with both Spotify and Intellij IDEA.
Try closing out your programs one by one until it behaves properly.


text:
Q: Python IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices I try to develop scorecard risk model with this code:
 scorecard_train = X_train[coefficients.index].apply(lambda x: x*coefficients['cf'].T,axis=1)

Error:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-156-06a4182aee37> in <module>
----> 1 scorecard_train = X_train[coefficients.index].apply(lambda x: x*coefficients['cf'].T,axis=1)

IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

How to fix this error?

A: Solved by taking out [coefficients.index]
scorecard_train = X_train_df.apply(lambda x: x*coefficients['cf'].T,axis=1)


text:
Q: Getstream - How to use the ranking method and personalization? By using Ranking method how to filter the most liked activity(or posts) in the getstream, and how to use the personalization?
Give some example related about ranking method and personalization
I have tried the examples given in the documentations but i can't understand what is that filtering?

A: personalization is a different level from ranking. Here's a description of personalization.
For ranking, take a look at this post to get ideas: https://getstream.io/blog/getting-started-ranked-feeds-getstream-io/


text:
Q: How to use a specific app config file The below code does not work. It does not get the app settings from the TestApp.Config file. Do you know why? And how can I fix it?
  public void GetConfig()
  {
     AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\dev\VS\ProofOfConcept\ProofOfConcept\TestApp.config");
     var a = ConfigurationManager.AppSettings;
  }

A: This post might help:
In the solution posted here there is a method ResetConfigurationMechanism() that you should call after you call CurrentDomain.SetData(...);.
private static void ResetConfigMechanism()
{
   typeof(ConfigurationManager)
   .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static)
   .SetValue(null, 0);

   typeof(ConfigurationManager)
   .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static)
   .SetValue(null, null);

   typeof(ConfigurationManager)
   .Assembly.GetTypes()
   .Where(x => x.FullName ==
      "System.Configuration.ClientConfigPaths")
   .First()
   .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static)
   .SetValue(null, null);
}


text:
Q: Why function $f$ is concave (convex upward) $\iff\forall x,\exists\text{ vector } \boldsymbol v(x) s.t. \forall z, f(z)-f(x)\leq (z-x)\cdot v(x)$ [Definition] $f$  is concave (convex upward) when
$$\forall x,y\in G,\forall 0<\lambda<1, \,f(\lambda x+(1-\lambda)y)\geq \lambda f(x)+(1-\lambda)f(y) $$

Prove that
$f:G\to\mathbb{R} \, (G\subset\mathbb{R^n} \text{ is a domain})$ is concave (convex upward) $$\iff \forall x,\exists \text{ a vector }  \boldsymbol v(x)\in \mathbb{ R}^n \, \mathrm{s.t.} \, \forall z ,\ f(z)-f(x)\leq (z-x)\cdot \boldsymbol{v}(x)$$

*

*$(1)$ for $f\in C^1$, it's easy to prove the theorem above and $ \boldsymbol v(x)=\nabla f(x)$,and for $f\in C^{2}$ Hessian is positive definite;

*$(2)$ $1$-dimension is easy, because
$$\forall x\leq y\leq z, \bigg[\frac{f(y)-f(x)}{y-x}\geq \frac{f(z)-f(x)}{z-x}\Longrightarrow \hspace{5cm}$$
$$ \hspace{3cm} \exists f'_+(x),f'_-(x), \; f(z)-f(x)\leq\min\{f'_+(x),f'_-(x)\}(z-x) \bigg]$$

*$(3)$ But for any $f$, I can only prove that in any direction $ \hat{\boldsymbol r} , f(x+\hat{ \boldsymbol r} t)-f(x)\leq C( \hat{\boldsymbol r})||\hat{\boldsymbol r}t||$ (same as $1$-dimension case), but how should I find $\boldsymbol{v}(x)$?


text:
Q: Numpy Leastsq fitting returning unchanged inital guess in all cases I am attempting to fit a function using Leastsq to fit to a few relevant points in an fft. The issue at hand is that, no matter how good or bad the fit is, there is absolutely no change in the parameters. In other words the least squares takes 6 iterations and does nothing on any of them, then returns the initial parameter values. I cannot determine why nothing is happening.
guess = [per_guess,thresh_guess,cen_guess] #parameter guesses, all real numbers
res, stuff = leastsq(fitting, guess)

The fitting function has a number of manipulations to find the correct indices, which I will not reproduce here to save space, but it returns a list of complex numbers:
M, freq= fft(real_gv, zf)
def fitting(guess):
    gi, trial_gv = gen_pat(size, guess[0], guess[1], guess[2])
    trial_gv = trial_gv*private.han #apply hanning window
    F, freq= fft(trial_gv, zf)
    #stuff that picks the right indices
    return M[left_fit target:right_fit_target]-F[left_fit target:right_fit_target]

I tried at one point using an array cast in the return, but I would constantly receive errors about casting between complex and real floats, even though I wasn't asking for any. Even with this method, I occasionally receive ComplexWarnings.
EDIT:
As requested, I am putting up gen_pat:
def gen_pat(num, period, threshold, pos = 0, step = 1.0, subdivide=10.0, blur = 1.0):
x= np.arange(-num/2,num/2,step) #grid indexes
j=np.zeros((len(x),subdivide))
for i in range(len(x)):
    j[i]=np.linspace(x[i]-0.5*blur,x[i]+0.5*blur,subdivide) #around each discrete point take a subvision. This will be averaged to get the antialiased point. blur allows for underlap (<1) or overlap of pxels
holder = -np.sin(2*np.pi*np.abs(j-pos)/period) #map a sin function for the region
holder = holder < 2.0*threshold-1.0 #map to 1 or 0 based on the fraction of the period that is 0
y = np.sum(holder, axis=1)/float(subdivide) #take the average of the values at the sub-points to get the anti-aliased value at the point i
y= np.array(y)
x= np.array(x)
return x,y

EDIT 2:
Managed to get a fit working using res = fmin_powell(fitting, guess, direc=[[1,0,0],[0,0.1,0],[0,0,1]]) and a modified return. Would still like to know why lestsq didn't work.
return np.sum((M[fit_start_index:fit_end_index].real-F[fit_start_index:fit_end_index].real)**2+(M[fit_start_index:fit_end_index].imag-F[fit_start_index:fit_end_index].imag)**2)

A: The provided function gen_pat(x1,x2,x3,x4) returns a horizontal line at value 1 for a few values of input (x1,x2,x3,x4) I tried. Its Fourier components (except the 0-th component of course) are then always zero independently of the parameters. Then the leastsq algorithm fails, as the change in the 4 parameters does not affect the Fourier components you are trying to optimize.
You are doing something wrong in gen_pat(), either a coding or conceptual error, like choosing a wrong fitting curve.


text:
Q: Listen to the 'change' even of an element in the shadow DOM I am trying to select an element in the shadow DOM.
As I understand, there are 2 options: /deep/ or ::shadow
I have setup a jsfiddle to illustrate my tests:
http://jsfiddle.net/chevdor/ph2qo5s8/4/
I am testing with and  element and I try selecting on of its div as example. I know I could use -webkit to access those but this is not what I need.
I don´t succeed on getting the elements under the shadow-root, neither using /deep/ not using ::shadow
I am using Chrome.
Does anyone know where the mistake could be?

A: It appears you're trying to pierce the shadow DOM of a native <input> tag. You cannot pierce the shadow DOM of native elements. Try using polymer's paper-input element instead. That will expose a shadow DOM you can pierce with the /deep/ or ::shadow selector.
<input id="native">
<paper-input id="paper"></paper-input>

Try it out yourself on Polymer's demo page for paper-input.


text:
Q: How do I make a if statement that checks message id ? (Discord PY) I have a discord bot that gives roles when a user reacts with a special emoji on a specefic message, but the problem is that it's giving roles whenever a user reacts with those emojis on whatever message.
I have tried to make an if statement that checks the message-id but it did not work do anyone how to fix?
The if statement:
 if payload.message_id != 669082231955783707:
                print('[Error] Wrong message id {0.display_name}'.format(member))

The bot logs:
The whole code:
import discord
from discord import utils

import config

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_raw_reaction_add(self, payload):
        channel = self.get_channel(payload.channel_id) # получаем объект канала
        message = await channel.fetch_message(payload.message_id) # получаем объект сообщения
        member = utils.get(message.guild.members, id=payload.user_id) # получаем объект пользователя который поставил реакцию

        try:
            emoji = str(payload.emoji) # эмоджик который выбрал юзер
            role = utils.get(message.guild.roles, id=config.ROLES[emoji]) # объект выбранной роли (если есть)

            if payload.message_id != 669082231955783707:
                print('[Error] Wrong message id {0.display_name}'.format(member))

            if (len([i for i in member.roles if i.id in config.ROLES.values()]) < config.MAX_ROLES_PER_USER):
                await member.add_roles(role)
                print('[SUCCESS] User {0.display_name} has been granted with role {1.name}'.format(member, role))

            else:
                await message.remove_reaction(payload.emoji, member)
                print('[ERROR] Too many roles for user {0.display_name}'.format(member))

        except KeyError as e:
            print('[ERROR] KeyError, no role found for ' + emoji)
        except Exception as e:
            print(repr(e))

    async def on_raw_reaction_remove(self, payload):
        channel = self.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)
        member = utils.get(message.guild.members, id=payload.user_id)

        try:
            emoji = str(payload.emoji) # эмоджик который выбрал юзер
            role = utils.get(message.guild.roles, id=config.ROLES[emoji])

            await member.remove_roles(role)
            print('[SUCCESS] Role {1.name} has been remove for user {0.display_name}'.format(member, role))

        except KeyError as e:
            print('[ERROR] KeyError, no role found for ' + emoji)
        except Exception as e:
            print(repr(e))

# RUN
client = MyClient()
client.run(config.TOKEN)

A: You should just add return in your if statement:
if payload.message_id != 669082231955783707:
    print('[Error] Wrong message id {0.display_name}'.format(member))
    return

By doing so, your on_raw_reaction_add function will stop when someone reacts on the wrong message.


text:
Q: MVC, views knowing about model This may be a dumb question, but in MVC the view doesn't know about the model right.  I've looked at some examples for table view cells, and the table view cell has a property of the model object.  It then uses that model's property to fill in the label, or the image for the cell.
Or in another case, if I have a UIView to draw something dynamically based on the model, it seems like it would be the easiest to have a property on the UIView so the UIView can access that model's data in order to draw it dynamically.  So I could do something like this:
myView.object = newObject;
[myView setNeedsDisplay];

Is this wrong for MVC?  If so, what are the better ways to do these two things?  Thanks.

A: There are different variants of the MVC model - the Apple documentation on it for Cocoa is here: http://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/Model-View-Controller/Model-View-Controller.html#//apple_ref/doc/uid/TP40010810-CH14-SW9.
The main thing I take from this is that Views should not be directly linked to the Model. See this diagram:

You mention UITableViewCells as often having a property of the Model object - I would suggest this is wrong.  The pattern should be as follows:

*

*The Model handles all of the actual data storage and management

*The View knows the type of data that is being displayed, but not the data itself.

*The Controller (UITableViewController) is the 'glue' that takes data from the Model and sets up the View

How does this work in practice?
Excuse some mistakes in the following psuedo-code as I just typed it directly in, I haven't tested any of it, but hopefully it shows the point.
So you have a UITableViewCell sub-class which looks like this:
@interface PhoneEntryTableViewCell {

@property (weak) IBOutlet UILabel *personName;
@property (weak) IBOutlet UILabel *phoneNumber;

}

The Model looks like this:
@interface PhoneModel {

@property (strong) NSMutableArray *listOfPeople;

}

And the UITableViewController implements the standard UITableViewDelegate/UITableViewDataSource methods, for example:
- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  Person *person = [myModel personForIndex:indexPath.row];

  PhoneEntryTableViewCell *cell = [self dequeueReusableCellWithIdentifier:@"PhoneCell"];
  cell.personName.text = [person name];
  cell.phoneNumber.text = [person phoneNumber];

  return cell;
}

So in summary, the View does not have any idea of the actual data - it just knows it has to display a person's name and phone number.  It doesn't know what the back-end storage is - it could be Core Data, a file, a downloaded and parsed JSON, etc.  It doesn't know anything about the Model - for example, maybe it stores other data about the Person, maybe the phone number is actually stored in a different model to the name.  The Controller handles all of this work.
Why do it this way?
So you roll out the above application and then discover your Model is horribly slow - you can swap it out for a completely different model without touching the View.  Maybe you can have another developer or designer create the View - all they need to know is that it has to display two bits of text. Basically it allows your code to be clean, clearly partitioned, easily extensible, and easier to refactor.
Now, as soon as you do something like this in your UITableViewCell View, all of this goes away:
@property (strong) Person *person;

A: First of all: There is no "the MVC model". It is outlined in different ways with subtile, but important differences.
If a component in the view needs to get information it can get this in two ways: Asking for it (polling), or being notified about it (pushing). Notification should be the cleaner approach in most cases, as the view really doesn't know anything about the model, it just works as observer.
However, GUI components tend to need "model objects" that hold the data and can be asked for it, like in your example. Altough they're often named after the model, architecturally they don't need to belong to it. And in my opinion they shouldn't, as the model's interfaces then are built after the needs of predefined GUI components and the whole sense of MVC is gone. If you want a clear separation between model and view you should try something like this:
-----------------       -----------------       --------------      ---------
| GUI Component | --->  | "Model Class" | <-->  | Controller | ---> | Model |
-----------------       -----------------       --------------      ---------

So the "Model Class" object that is expected by the GUI component is nothing but an adapter for the controller. In this relation between GUI and Controller you can now implement whatever strategy you like - poll or push (the reason for the two-sided arrow).

A:
Or in another case, if I have a UIView to draw something dynamically
  based on the model, it seems like it would be the easiest to have a
  property on the UIView so the UIView can access that model's data in
  order to draw it dynamically.

So what would you have the view say to the model in order to get the right information? It has to know something about the model in order to ask the right question, right? Alternately, you could define a protocol like UITableViewDataSource and send generic messages like -cellForRowAtIndexPath:, and then implement that protocol in your model. That avoids the need for the view to know anything specific about the model, but it means instead that the model now has to know about the view -- it has to know something about what's supposed to be displayed in the view so that it can pass back the right data. Whichever way you go, you introduce a dependency between the model and the view, and that means that when you make a change in one you'll have to make a change in the other.
Avoiding those kinds of dependencies is exactly the point of the MVC architecture. The controller knows about both model and view, which allows the model and view to exist independent of each other.
It might sometimes make sense to have some objects that both model and view know about. If you're writing an address book, it might make sense to have a ContactView that knows how to display a Contact, and a model that stores Contact objects. That seems much more sensible than having a view that's completely stupid about what it's displaying, and it lets you pass around Contact objects instead of great long lists of name, address, phone, fax, email, etc. You could say that a Contact is a model object, and all the above applies: you'll be introducing a dependency between ContactView and Contact. But usually when we talk about "the model", we mean the whole graph of objects that the program uses to store its data, and the benefit of MVC is to separate the way you manage all those objects from the way you present the data that they contain.


text:
Q: How to import and use PyWhatKit on Google Colaboratory? I wanted to automate sending messages on WhatsApp from Google Colab using the pywhatkit library. So far I have tried doing:
pip install pywhatkit

Output:
Requirement already satisfied: pywhatkit in /usr/local/lib/python3.7/dist-packages (5.3)
Requirement already satisfied: wikipedia in /usr/local/lib/python3.7/dist-packages (from pywhatkit) (1.4.0)
Requirement already satisfied: pyautogui in /usr/local/lib/python3.7/dist-packages (from pywhatkit) (0.9.53)
Requirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from pywhatkit) (2.23.0)
Requirement already satisfied: Pillow in /usr/local/lib/python3.7/dist-packages (from pywhatkit) (7.1.2)
Requirement already satisfied: mouseinfo in /usr/local/lib/python3.7/dist-packages (from pyautogui->pywhatkit) (0.1.3)
Requirement already satisfied: pyscreeze>=0.1.21 in /usr/local/lib/python3.7/dist-packages (from pyautogui->pywhatkit) (0.1.28)
Requirement already satisfied: pygetwindow>=0.0.5 in /usr/local/lib/python3.7/dist-packages (from pyautogui->pywhatkit) (0.0.9)
Requirement already satisfied: PyTweening>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from pyautogui->pywhatkit) (1.0.4)
Requirement already satisfied: python3-Xlib in /usr/local/lib/python3.7/dist-packages (from pyautogui->pywhatkit) (0.15)
Requirement already satisfied: pymsgbox in /usr/local/lib/python3.7/dist-packages (from pyautogui->pywhatkit) (1.0.9)
Requirement already satisfied: pyrect in /usr/local/lib/python3.7/dist-packages (from pygetwindow>=0.0.5->pyautogui->pywhatkit) (0.2.0)
Requirement already satisfied: pyperclip in /usr/local/lib/python3.7/dist-packages (from mouseinfo->pyautogui->pywhatkit) (1.8.2)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests->pywhatkit) (2021.10.8)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests->pywhatkit) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests->pywhatkit) (2.10)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests->pywhatkit) (1.24.3)
Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.7/dist-packages (from wikipedia->pywhatkit) (4.6.3)

I have also tried to see if pip list has it installed and it says it has:
pip list

Output:
....
....
pywhatkit     5.3
....
....

When I try to import it shows error.
import pywhatkit

Output:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-16-54f6f476dc6e> in <module>()
----> 1 import pywhatkit

4 frames
/usr/lib/python3.7/os.py in __getitem__(self, key)
    679         except KeyError:
    680             # raise KeyError with the original key value
--> 681             raise KeyError(key) from None
    682         return self.decodevalue(value)
    683

KeyError: 'DISPLAY'

What is the workaround or solution to this problem?


text:
Q: I would like to know how to program the JavaScript part that checks whether the onclick function is active function myFunction() {
document.getElementById('foo').style.cssText = 'border-color: rgb(0, 0, 255);color: black;font-size: 20px;padding: 0px;margin: 10px 20px';
document.getElementById("demo").innerHTML = "8500$"
}


text:
Q: The screen in Android Virtual Device is too big As you can see in the screenshot, what appears is only a small one in the upper left corner, but the frame is very large. The operation also follows the size of the frame, so if I want to press the gallery I have to go to the bottom of the frame and press with guesswork. Can anyone help me? I'm a newbie to Android Studio and this was quite annoying for my first try.
https://i.stack.imgur.com/g8tMn.jpg

A: You can resize your emulator screen
By going (in the top menu of Android Studio) to Run > Edit Configurations
In the left panel of the just opened dialog, choose your application.
In the right panel, choose the General tab, and then go down and check Emulator, and in Prefer Android Virtual Device, choose the virtual device you are currently using.
Now, go the tab Emulator (next to the General tab), and in Additional command line options, write
-scale 0.X
where X can be for example 25 or 50, which would represent respectively 25% and 50% of original size.


text:
Q: Efficient way making "Like" function without duplication? I am making a "Like" function (facebook or instagram kind of), but not sure what is the right way to do it.
I could think of 2 ways.... (User cannot like same article twice)
A. "User" data has an array of "Article" IDs...

// simplified user schema MongoDB
const UserSchema ={
    id:ObjectID,
    username:String,
    likes:[{type:ObjectID,ref:"Article"}]
}

// simplified article schema
const AriticleSchema = {
     id:ObjectID,
     title:String,
     content:String,
     likes:Number,
}

B. "Article" data has an array of "User" IDs...

// simplified user schema MongoDB
const UserSchema ={
    id:ObjectID,
    username:String,

}

// simplified article schema
const AriticleSchema = {
     id:ObjectID,
     title:String,
     content:String,
     likes:[{type:ObjectID,ref:"User"}],
}

I tried both ways and they all worked fine when I only have few users and few articles.
but What if I have thousands of "User"s and thousands of "Article"s? I am worrying that everytime I request "User" data or "Article" data(let's say several at a time), I also have to bring arrays of thousands? I think there must be better way to do this...
Do you know how people or companies do this? I want to know the concept of how "Like" function works.
Thank you.
** Adding some details **
I want "User" can login for reading articles, and press "like button" to like it. Article "like" will go up by 1 every time unique user likes it (no duplicate). Somebody who already liked the " article" they can "unlike" it or "user" will see they already liked the "article", which means we gotta know that "user" like this "article" or not. Other people dosen't need to know.

A: I'll extrapolate on a solution by going through the requirements you elaborated step by step.

User can login

This will require some system for authorization. You could perhaps use another Mongo table dedicated to this sort of thing - at the minimum it should link some authorization token to a user id.
const AuthSchema = {
  user_id: ObjectID,
  auth_token: string,
}

The way you get this auth token is through various means - really depends on how you auth your users, e.g. phone auth or username/password. All that's a bit beyond the scope of this answer.

Article "like" will go up by 1 every time unique user likes it (no duplicate). Somebody who already liked the " article" can "unlike" it or "user" will see they already liked the "article"

A Redis Set would model this quite well. Every time a user likes an article, add their user_id into a Redis Set for that article. The key for such set could look like this:
article:${article_id}:likes

Get the number of people who liked the article by taking the size of its set (full of unique user_ids). Whenever someone unlikes an article, remove their user_id from the set.
Further reading:

*

*Redis Sets and other Redis datatypes

*Redis sadd command.


text:
Q: unexpected output for map inside of do Why doesn't this produce the output I expect?
(defn test-fn []
  (do
    (println "start")
    (map #(println (+ % 1)) '(1 2 3))
    (println "done")))

It outputs
start
done

Whereas I would expect
start
2 3 4
done

A: map is lazy, and do does not force it. If you want to force the evaluation of a lazy sequence, use doall or dorun.
(defn test-fn []
  (do
    (println "start")
    (dorun (map #(println (+ % 1)) '(1 2 3)))
    (println "done")))


text:
Q: selenium: css query
<s>
   --- (1)
   --- (2)
</s>

<s>
   --- (3)
   --- (4)
</s>

*

*I would like to could  tags but only the ones which are children of  tag?
How do I specify the css in this case?
Is this ok: self.selenium.get_css_count("css=s b")
Would this count all  s b relationships, with s as parent and b as child. 4 in the above example? If not, could you help with this issue?

*I would like to click the fourth (4)  tag under  tag. How would I do that?
if I do: self.selenium.click("css=s b:nth(1))
it would select (2), so how do i specify (s b):nth(3)?
Because s is parent of b. and I want to click on the fourth kind of this relationship.
I hope this makes sense.

*what is the difference between nth() and nth-of-type()
Thanks
Sunny

A: You could use xpaths rather than css selectors to do this.
for your 1.
get_xpath_count("//s/b")

and 2.
click("//s[2]/b[2]")

A: What about:
b > s:first-child > b
To click 4th child:
:nth-child(4)
3rd question: nth-of-type vs nth-child


text:
Q: SQL Server query no longer slow after query char or parameter type change I have the following query :
SELECT
  A.id,
  NEWID() as id,
  RTRIM(LTRIM(A.label)) as label
FROM (
SELECT
  a.id_aff as id,
  p.nom as label
FROM
  A a inner join
  P p on p.id_aff = a.id_aff INNER JOIN
  L l on l.id_aff = a.id_aff INNER JOIN
  PL pl on pl.id_lien = l.id_lien AND pl.id_prog = p.id_prog INNER JOIN
  S s on s.id_prog = p.id_prog
where
  s.id_pub = :idPub and l.id_type = :idType and
  s.active = 1 and s.valid = 1
UNION
SELECT
  a.id_aff as id,
  p.nom as label
FROM
  A a inner join
  P p on p.id_aff = a.id_aff INNER JOIN
  L l on l.id_aff = a.id_aff INNER JOIN
  S s on s.id_prog = p.id_prog INNER JOIN
  SL sl on sl.id_lien = l.id_lien AND sl.id_session = p.id_prog
where
  s.id_pub = :idPub and l.id_type = :idType and
  s.active = 1 and s.valid = 1
) A
ORDER BY
 RTRIM(LTRIM(A.label)) ASC

Normally the query execution time is approximately 2 - 3 seconds.
Suddenly this query execution time rise to 1 minute - 1 minute and 30 seconds.
This query is executed by hibernate by the following code :
Query query = entityManager.createNativeQuery(QUERY, Select.class);
Integer id = 1;
query.setParameter("id", idAffilie);
query.setParameter("idType", SystemConstant.ID_TYPE);
List<Select> resultList = query.getResultList();

I execute the following tests :
1) Changing the parameter type
If for example i change the type of id from Integer to String without modifying the query, the query return the same result and the execution the is back to normal (2 - 3 seconds) :
Query query = entityManager.createNativeQuery(QUERY, Select.class);
String id = "1";
query.setParameter("id", idAffilie);
query.setParameter("idType", SystemConstant.ID_TYPE);
List<Select> resultList = query.getResultList();

2) Changing the query formatting
If i change the query formatting the same result occur the query execution the is back to normal (2 - 3 seconds). In this example, I change the SELECT formatting :
SELECT A.id, NEWID() as id, RTRIM(LTRIM(A.label)) as label
FROM (
SELECT
  a.id_aff as id,
  p.nom as label
FROM
  A a inner join
  P p on p.id_aff = a.id_aff INNER JOIN
  L l on l.id_aff = a.id_aff INNER JOIN
  PL pl on pl.id_lien = l.id_lien AND pl.id_prog = p.id_prog INNER JOIN
  S s on s.id_prog = p.id_prog
where
  s.id_pub = :idPub and l.id_type = :idType and
  s.active = 1 and s.valid = 1
UNION
SELECT
  a.id_aff as id,
  p.nom as label
FROM
  A a inner join
  P p on p.id_aff = a.id_aff INNER JOIN
  L l on l.id_aff = a.id_aff INNER JOIN
  S s on s.id_prog = p.id_prog INNER JOIN
  SL sl on sl.id_lien = l.id_lien AND sl.id_session = p.id_prog
where
  s.id_pub = :idPub and l.id_type = :idType and
  s.active = 1 and s.valid = 1
) A
ORDER BY
 RTRIM(LTRIM(A.label)) ASC

Question : why changing a parameter or the query formatting makes this query execution time back to the normal ?
This issue is encountered with a few queries but not all of them.
Cardinalities of tables :

*

*A : 9000 records

*P : 25000 records

*L : 185000 records

*PL : 736000 records

*S : 600000 records

*SL : 20000 records

SQL Server : Microsoft SQL Server 2019 (RTM-CU3) (KB4538853) - 15.0.4023.6 (X64)
Spring boot : 2.0.9
Spring data JPA : 2.0.14
Hibernate : 5.2.18
Thanks and have a good day.
EDIT
SQL server driver maven version : 9.2.1.jre8


text:
Q: Ethereum Nonce Management. error nonce too low I use web3 and provider mainnet. I do 2 transactions by contract. first is approve method and another  transaction is multitransfer. I store second signature in database. if first transaction is success I send second transaction/. second transaction almost always error nonce too low`. how i can solve this problem

A: There may be two issues(solutions) here from my understanding;
1) You may have to manually increment nonce for the gas estimation of the multitransfer operations.
2) Some server are pretty slow these days, so either you fetch transactionReceipt(poll) of first transaction before doing the second to be sure that it has been mined. This way you would likely have the right nonce for second transaction. However, if you are lazy to do this, just are reasonable delay between the two transactions.

A: For proper nonce management you have 2 options :

*

*Request the nr of transactions confirmed for your address with web3.eth.getTransactionCount(ethAddress), increment, send and wait for receipt before processing the next one. This is very slow if you need to have high-throughput and you are relying on a specific node to be available and to be synced.

*You maintain your own local counter persisted at the level of the database. Use the DB's access locks to handle possible concurrent requests and return correct values every time. You do not want to keep this counters in memory as they will be lost if your application crashes or restarts. This is very efficient as you do not need the node and you can send as many transactions as you can dish out. If something goes wrong... (nonce too low) reset to the value of web3.eth.getTransactionCount(ethAddress).
Important Note: You might wonder why not to use web3.eth.getTransactionCount(ethAddress, 'pending'). This is because the 'pending' option makes the call unreliable as its hard for the nodes to have an accurate number of transaction in the queue & the memory pool.
For a better understanding how the nodes look at your message's nonce. Check this answer here : https://ethereum.stackexchange.com/questions/2808/what-happens-when-a-transaction-nonce-is-too-high/2809#2809
And this one too : Send Raw Transaction Ethereum infura nodejs npm


text:
Q: Google colab GPU Background issue enter image description here <- Error Image
I'm using Colab pro +
It's been 3 days that message pop up when I start to use GPUon Background machine on Google Colab
I know that is beacuse of limitation of usage, So I was waiting for a while but still that meassge  is exist and I can't use GPU on Backround.
What shoud i do to solve this? just waiting more?


text:
Q: CoreData fetched property and RestKit 0.20.3: value for undefined key I'm facing a big issue with fetched properties.
I have this entities in the model:
EntityDetail
Attributes:
NSString: idd_info
[...]
Fetched Property:
Name: info Destination: EntityInfo Predicate: idd==$FETCH_SOURCE.idd_info

EntityInfo
Attributes:
NSString: idd
NSString: title
[...]

In this way I can obtain related EntityInfo when I need:
[[detail.info objectAtIndex:0] title]

I prefer this approach instead of configuring a regular relationship due to performance reasons during the parsing process.
If I use the Apple generated CoreData boilerplate to setup the stack, everything works fine and I can use the fetched property with success. But if I use the RestKit provided implementation by the RKManagedObjectStore class, the fetched property does not work. This is the error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<_NSObjectID_48_15 0x1a2f9ac0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key idd_info.'
It seems that $FETCH_SOURCE resolves to a NSObjectID instead of the NSObject itself. And, obviously, the idd_info property is not defined on that class.
Googling around I found the possibility to setup the resultType on a fetchRequest to NSManagedObjectResultType. This is the default behavior as stated in Apple documentation. So why does RestKit 0.20.3 use NSManagedObjectIDResultType instead? With RestKit 0.10 everything works fine...
Is this a know bug? How can I force the fetched property to NSManagedObjectResultType ?
This is the way I setup the persistent stores and create managed object context using RKManagedObjectStore.
I am in the application delegate and _managedObjectModel _managedObjectStore _managedObjectContext are singleton variables used in the whole app).
NSURL *modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"MyApp" ofType:@"momd"]];
_managedObjectModel= [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
_managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:_managedObjectModel];
[_managedObjectStore createPersistentStoreCoordinator];

NSString *storePath = [[self docDir] stringByAppendingPathComponent::@"MyApp.sqlite"];
NSDictionary *options = @{ NSSQLitePragmasOption : @{@"journal_mode" : @"DELETE"} };
NSPersistentStore __unused *persistentStore = [_managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:options error:&error];
NSAssert(persistentStore, @"Failed to add persistent store: %@", error);

[_managedObjectStore createManagedObjectContexts];
[RKManagedObjectStore setDefaultStore:_managedObjectStore];
[_managedObjectStore.mainQueueManagedObjectContext setUndoManager:nil];
_managedObjectContext = _managedObjectStore.mainQueueManagedObjectContext;

Thank you.
UPDATE 1:
If I use:
_managedObjectContext = _managedObjectStore.persistentStoreManagedObjectContext;

instead of:
_managedObjectContext = _managedObjectStore.mainQueueManagedObjectContext;

in the application delegate at startup the issue doesn't occurs and fetched property works fine, but it still occurs during mapping.
This is how I set up the mapping.
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:baseURL];

[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:@"application/xml"];
[[RKObjectManager sharedManager] setAcceptHeaderWithMIMEType:RKMIMETypeTextXML];
[RKObjectManager setSharedManager:objectManager];

RKManagedObjectStore* objectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:appDeleg.managedObjectModel];

[objectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:@{ NSInferMappingModelAutomaticallyOption: @YES,NSMigratePersistentStoresAutomaticallyOption: @YES, NSSQLitePragmasOption: @{@"journal_mode" : @"DELETE"} } error:nil];

[objectStore createManagedObjectContexts];

objectManager.managedObjectStore=objectStore;

[objectManager.HTTPClient setAuthorizationHeaderWithUsername:usernameString password:passwordString]

[... here RKEntityMappings and ResponseDescriptors added to the objectManager ...]

[[RKObjectManager sharedManager]  getObjectsAtPath:remoteBaseAddedPath parameters:nil

    success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {

            [delegate parserDidSuccessParsingData:self];

    } failure:^(RKObjectRequestOperation *operation, NSError *error) {

            [delegate parserDidFailParsingData:self withError:error];

}];

UPDATE 2:
This is the stack trace during mapping. Please note that I have a transient property on the object which uses the fetched property in the getter, RestKit call this getter and crash occurs:
2014-03-20 11:10:53.545 MyApp[15378:f03] D restkit.object_mapping:RKMappingOperation.m:952 Starting mapping operation...
2014-03-20 11:10:53.549 MyApp[15378:60b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSTemporaryObjectID_default 0xcb9a870> valueForUndefinedKey:]: this class is not key value coding-compliant for the key idd_info.'

*** First throw call stack:
(
    0   CoreFoundation                      0x02b021e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x028818e5 objc_exception_throw + 44
    2   CoreFoundation                      0x02b91fe1 -[NSException raise] + 17
    3   Foundation                          0x00f6dc7a -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 282
    4   Foundation                          0x00edadfd _NSGetUsingKeyValueGetter + 81
    5   Foundation                          0x00eda437 -[NSObject(NSKeyValueCoding) valueForKey:] + 260
    6   Foundation                          0x00ef9f0a -[NSObject(NSKeyValueCoding) valueForKeyPath:] + 409
    7   Foundation                          0x00eab465 -[NSFunctionExpression expressionValueWithObject:context:] + 1260
    8   CoreData                            0x00728bbc -[NSSQLSimpleWhereIntermediate initWithPredicate:inScope:] + 620
    9   CoreData                            0x007283eb -[NSSQLGenerator generateWhereIntermediatesInContext:] + 187
    10  CoreData                            0x00727dc1 -[NSSQLGenerator generateIntermediatesForFetchInContext:countOnly:] + 673
    11  CoreData                            0x007242f3 -[NSSQLGenerator newSQLStatementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:] + 483
    12  CoreData                            0x00723fb8 -[NSSQLAdapter _newSelectStatementWithFetchRequest:ignoreInheritance:] + 472
    13  CoreData                            0x00723dd0 -[NSSQLAdapter newSelectStatementWithFetchRequest:] + 48
    14  CoreData                            0x00723b91 -[NSSQLCore newRowsForFetchPlan:] + 129
    15  CoreData                            0x0072331d -[NSSQLCore objectsForFetchRequest:inContext:] + 701
    16  CoreData                            0x00722dcf -[NSSQLCore executeRequest:withContext:error:] + 383
    17  CoreData                            0x007227f2 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 4466
    18  CoreData                            0x0071ff56 -[NSManagedObjectContext executeFetchRequest:error:] + 566
    19  CoreData                            0x00774d86 -[NSManagedObjectContext(_NestedContextSupport) _parentObjectsForFetchRequest:inContext:error:] + 502
    20  CoreData                            0x007f2a14 __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 676
    21  CoreData                            0x00774b81 internalBlockToNSManagedObjectContextPerform + 17
    22  libdispatch.dylib                   0x032394d0 _dispatch_client_callout + 14
    23  libdispatch.dylib                   0x03226740 _dispatch_barrier_sync_f_invoke + 58
    24  libdispatch.dylib                   0x032263ea dispatch_barrier_sync_f + 89
    25  CoreData                            0x00774b02 _perform + 114
    26  CoreData                            0x007749ae -[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:] + 238
    27  CoreData                            0x0071ff56 -[NSManagedObjectContext executeFetchRequest:error:] + 566
    28  CoreData                            0x00774d86 -[NSManagedObjectContext(_NestedContextSupport) _parentObjectsForFetchRequest:inContext:error:] + 502
    29  CoreData                            0x007f2a14 __82-[NSManagedObjectContext(_NestedContextSupport) executeRequest:withContext:error:]_block_invoke + 676
    30  CoreData                            0x00774b81 internalBlockToNSManagedObjectContextPerform + 17
    31  libdispatch.dylib                   0x032394d0 _dispatch_client_callout + 14
    32  libdispatch.dylib                   0x03228439 _dispatch_barrier_sync_f_slow_invoke + 80
    33  libdispatch.dylib                   0x032394d0 _dispatch_client_callout + 14
    34  libdispatch.dylib                   0x03227726 _dispatch_main_queue_callback_4CF + 340
    35  CoreFoundation                      0x02b6743e __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 14
    36  CoreFoundation                      0x02aa85cb __CFRunLoopRun + 1963
    37  CoreFoundation                      0x02aa79d3 CFRunLoopRunSpecific + 467
    38  CoreFoundation                      0x02aa77eb CFRunLoopRunInMode + 123
    39  GraphicsServices                    0x0392c5ee GSEventRunModal + 192
    40  GraphicsServices                    0x0392c42b GSEventRun + 104
    41  UIKit                               0x012bff9b UIApplicationMain + 1225
    42  MyApp                               0x001a186c main + 76
    43  libdyld.dylib                       0x0346e701 start + 1
    44  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException


text:
Q: php array count includes trailing comma I have an array which I get from an exploded url (using $_GET).
The elements in the url are separated by commas but when I COUNT the elements the result includes the final comma. Eg: '?list=jonny,sally,bob,' returns '4' when '?list=jonny,sally,bob' returns '3'. I can't avoid the final comma as they are genrated with them automatically but I need to return 3 on both examples. Any ideas please?? Thanks
$list = explode(",", $_GET['list']);
$listCount = count($list);
//$listCount =(int)$listCount -1;
//$list[$listCount]=str_replace($list[$listCount],',','');
echo $listCount;

NB: the commented out lines are a failed attempt to remove the comma. But $list[$listCount] ,ie the final array element doesn't seem to exist even though it is counted

A: If you want to trim any extra commas at the start or end of the string, use trim(). If you want it at the end of the string, you can use rtrim().
$list = explode(",", $_GET['list']);

to
$list = explode(",", trim($_GET['list'], ','));

A: Trim any commas first:
$strList = rtrim($_GET['list'], ",")
$arrList = explode(",", $strList);

A: Array_filter will remove any empty values from your array, so in case you have two commas in a row, it will remove empty values caused by that also.
$list = array_filter(explode(",", $_GET['lists']));


text:
Q: Display SQLite table data row by row in Android using TableLayout dynamically I'm new to android coding. I simply want to display data row by row from my database table.
Here is the part where I have created database/table and added data.
    SQLiteDatabase glucoDB = openOrCreateDatabase("glucoDB",MODE_PRIVATE,null);
    glucoDB.execSQL("CREATE TABLE IF NOT EXISTS Results(Timestamp VARCHAR, Level_using_hsv_range VARCHAR,Level_using_hsv_gradient VARCHAR,Level_using_lab_range VARCHAR,Level_using_lab_gradient VARCHAR);");
    String query=new String("INSERT INTO Results VALUES ('" + currentDateTimeString + "', '" + str + "mg/dL', '" + glucose[1] + "mg/dL', '" + gvalue + "-" + largeg + "mg/dL', '" + LabRes2 + "mg/dL');");
    glucoDB.execSQL(query);

Below is the activity code (ViewResults.java) for displaying database values.I can't figure out what I'm doing wrong. On exporting and running the app, the rest of the app works fine but the part where data is displayed shows a black screen and app exits instantly. Although if I display data using simple TextView and not TableLayout, it is displayed normally. So database part is working fine, there's something wrong with my TableLayout code.
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result_page);
    int i=0,j=0;
    SQLiteDatabase Glucodb = openOrCreateDatabase("glucoDB",MODE_PRIVATE,null);
    Cursor resultSet = Glucodb.rawQuery("Select * from Results",null);
    resultSet.moveToFirst();

    TableLayout l1 = (TableLayout) findViewById(R.id.table2);
    l1.setStretchAllColumns(true);
    l1.bringToFront();

            do
            {   TableRow tr =  new TableRow(getBaseContext());

                    TextView t1 = new TextView(getBaseContext());
                    TextView t2 = new TextView(getBaseContext());
                    TextView t3 = new TextView(getBaseContext());
                    TextView t4 = new TextView(getBaseContext());
                    TextView t5 = new TextView(getBaseContext());
                    t1.setBackgroundResource(R.drawable.border);
                    t1.setText(resultSet.getString(0));
                    t2.setText(resultSet.getString(1));
                    t3.setText(resultSet.getString(2));
                    t4.setText(resultSet.getString(3));
                    t5.setText(resultSet.getString(5));

                    tr.addView(t1);
                    tr.addView(t2);
                    tr.addView(t3);
                    tr.addView(t4);
                    tr.addView(t5);

                l1.addView(tr);
            }while(resultSet.moveToNext());

        }

Below is the code of XML file associate with displaying results in table format.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal" >

  <TableLayout
    android:id="@+id/table2"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_marginBottom="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:layout_weight="0.80"
    android:stretchColumns="*" >

      <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
          >

        <TextView
            android:gravity="left"
            android:text="Timestamp"
            android:background="@drawable/border"
            android:textStyle="bold" />

        <TextView
            android:gravity="center"
            android:text="Gvalue1"
            android:background="@drawable/border"
            android:textStyle="bold" />

        <TextView
            android:gravity="center"
            android:text="Gvalue2"
            android:background="@drawable/border"
            android:textStyle="bold" />

        <TextView
            android:gravity="center"
            android:text="Gvalue3"
            android:background="@drawable/border"
            android:textStyle="bold" />
        <TextView
            android:gravity="center"
            android:text="Gvalue4"
            android:background="@drawable/border"
            android:textStyle="bold" />
    </TableRow>
</TableLayout>

</LinearLayout>


text:
Q: How can you render widgets from a different page in Kentico? I'm working with a Kentico application that uses the 'ASPX + Portal Engine' template type. In one of the pages, I need to display all the widgets and web parts (basically the whole page) from all it's child nodes.
If I use the 'Portal Engine' template type and have the following code in a user control, it works just fine:
<asp:Repeater runat="server" ID="ChildPagesRepeater" ItemType="CMS.DocumentEngine.TreeNode">
    <ItemTemplate>

<%# Item.DocumentPageTitle %>

                <cms:CMSPagePlaceholder runat="server" ShortID="p" Path="<%# Item.NodeAliasPath %>" />

    </ItemTemplate>
</asp:Repeater>

In the CodeBehind, I set the DataSource for the ChildPagesRepeater to the TreeNode children of the CurrentDocument and this 'just works'. But it just won't work with 'Portal Engine + ASPX' templates. What am I missing here?
My last resort is to use a WebClient to get the child pages' markup and render it directly but I'd rather do it the 'proper' way. I've tested this and this does work but it doesn't feel like the 'right' way to do this.

A: I've done this trick but only in portal, i can only guess if the same thing done in portal+aspx.net doesn't work, that the coding difference in one rendering all the zones and the other only loading webparts into the existing zones may be the issue.
Out of curiosity, why are you doing aspx.net+portal?  There is very little you can't do in pure Portal (plus a custom control) than you can do in aspx.net+portal, plus it's super annoying to have a hard coded master template.  I would convert.


text:
Q: Selecting multiple cells in Silverlight 4 Datagrid I have some 6 columns in Silverlight 4 Datagrid. On each cell in the data grid, we have some custom controls got displayed. Now i should allow the user to select one control from each of the columns. Once they select one control from each columns, then will go and click on OK button to preform some work. One note is, He might choose different cells from different columns. They might not be from the same row.
How can we implement this kind of functionality in the grid. Any suggestions on, how should we proceed with this problem. Is there any way to select multiple cells in Silverlight 4 Datagrid?

A:    <DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" SelectionMode="Extended" SelectionUnit="CellOrRowHeader" />


text:
Q: Android Studio doesn't send a match code for my device I see there are some similar questions(you may check the links below) but none of them answers my question. I have installed Android Studio many times and used 2 different phones before. 3 days ago I had to factory reset my PC and than I reinstalled Android Studio. I connected my Galaxy S4 but adb doesn't see it. BUT MY QUESTION IS before this occasion whenever I plug in a device it was sending me an USB debugging authorization code. This time it doesn't happen. Why I don't receive an authorization code ?
Here's some similar questions which helped none. Yes I almost have the same problem but one says AS starts project with virtual device other says I see my device is running but it doesn't work.

Android Studio doesn't see device
Android studio doesn't list my phone under "Choose Device"
Android Studio doesn't start with connected device

Also I did a google research found something about Google USB Driver which is already installed on my SDK. So it didn't help me either. Here's the link:

http://developer.android.com/sdk/win-usb.html

So I am hopeless. I tried everything. ADB doesn't see my device. But my real question is before you downgrade or say it is duplicate why I don't receive an USB debugging authorization code? Thanks for checking! If you could help me I would very appreciate it!

A: The Google USB-Driver is for Nexus devices only.
If you want to use a Samsung device you need to download and install the needed driver.
A list of all supported retailers can be found here.
After you've downloaded the driver simply install it as described here.
Then you can activate the "USB debugging" mode on your device. It can be found under "developer options".
If you don't see this category simply tap the "build number field" 7 times.

A: You need restart android device, android ADB. After that, reconnect android device to PC, it will be automaticaly installed proper USB driver.


text:
Q: Can't Call ParentVC Func Swift This Cell can not call parentVC's function.
 class MultipleAnswerTableViewCell: UITableViewCell, SurveyAnswerViewDelegate, UITextFieldDelegate {

var parentVC: AddQuestionViewController!

 let surveyAnswer = SurveyAnswer(answer: textField.text!, order: Int(textField.tag))
            surveyAnswers.append(surveyAnswer)
            self.parentVC?.savedAnswer(answer: surveyAnswer). //Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file Rtuk/MultipleAnswerTableViewCell.swift

 if let myParentVC = self.parentVC as? AddQuestionViewController {
                myParentVC.savedAnswer(answer: surveyAnswer)
            }

And the ParentVC is
class AddQuestionViewController: BaseViewController, SurveyTopTableViewCellDelegate, MultipleAnswerTableViewCellDelegate, SurveyTextAnswerTableViewCellDelegate, UITextFieldDelegate {

 func configureMultiAnswerCell(indexPath: IndexPath) -> MultipleAnswerTableViewCell {
        let postSettingsVC = PostSettingsViewController.instantiateFrom(appStoryboard: .Post)
        postSettingsVC.post = post
        let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
        cell.parentVC = self
        return cell
    }

 func savedAnswer(answer: SurveyAnswer) {
        self.surveyAnswers.append(answer)
        print("answerLo", answer.answer)
    }

func configureTable() {
        tableView.register(MultipleAnswerTableViewCell.self)
        }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch cellTypes[indexPath.row] {
        case .fixedTop: return configureFixedTop(indexPath: indexPath)
        case .multiAnswer: return configureMultiAnswerCell(indexPath: indexPath)
        }
    }

func pickerChanged(type: SurveyType) {
        switch type {
        case .multiAnswer: cellTypes = [.fixedTop, .multiAnswer]
        case .singleAnswer: cellTypes = [.fixedTop, .singleAnswer]
        case .textAnswer: cellTypes = [.fixedTop, .textAnswer]
        }
    }

Somehow child never reaches to parentVC. How I configure tableview is added
I am not sure but maybe this func inside ParentVC may break it.
 @IBAction func saveButtonTapped(_ sender: UIButton) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MultipleAnswerTableViewCell") as! MultipleAnswerTableViewCell
        cell.mainSaveTapped(stackView: savedStack)
    }

A: Change your method like that to make it work. But, as I mentioned in comments above, it is very strange implementation and u should think about its improvement)
   @IBAction func saveButtonTapped(_ sender: UIButton) {
        let cell = tableView.visibleCells.first(where: { $0 is MultipleAnswerTableViewCell }) as? MultipleAnswerTableViewCell
        cell?.mainSaveTapped(stackView: savedStack)
    }


text:
Q: Porting from cygwin to win32 native program I am porting the Enhanced CTorrent to Windows. But I'd like use Visual Studio to compile source code and get rid of cygwin.dll.
I found directives to conditionally use winsock header. But at moment I only can compile the source code by cygwin. I am wondering is the WINDOWS in code below same as _WIN32 in Visual Studio? And can cygwin directly use Win32 API as well?
#ifdef WINDOWS
#include <Winsock2.h>
#else

A: if you still want to keep this working under cygwin while you convert the source, you can use something like:
#if defined(WINDOWS) || defined(_WIN32)
#include <Winsock2.h>
#else

and for using Win32 API on cygwin, see the FAQ.


text:
Q: Javascript fetch request doesn't load php data on Heroku? I'm working on a project which is hosted on Heroku and I'm making a call to a PHP file on backend using the Javascript fetch API. Here is the code,
fetch('./api/file.php').then(function(response){
    console.log(response);
});

And for some reason I'm not loading anything from the backend the file loads fine, the developer tools on the browser shows that file is called by making the request, however there is no data being loaded.

However when I opened the file.php from the browser by typing the URL the data is shown on the same file.php file on the browser.
So how come that there is no response from the fetch request but have the data when accessing the file by typing the URL on browser? Does this have to do something with heroku? How can I fix this?
Thanks


text:
Q: how can get action path of the form in laravel 5.2 I have update My data with this form
<form class="form-vertical" role="form" method="post" action="">

has('comments') ? ' has-error' : '' }}">
                <input type="text" name="comments" class="form-control" id="comments" value="{!! $comment->comments ?: '' !!}">
                @if ($errors->has('comments'))
                    {{ $errors->first('comments') }}
                @endif

                <button type="submit" class="btn btn-info">Update Commment</button>

            <input type="hidden" name="_token" value="{{ csrf_token() }}">
            {!! method_field('PUT') !!}
        </form>

this form routes is
Route::put('projects/{projects}/collaborators/{id}',['uses'=>'ProjectCollaboratorsController@update',]);

I need how can I give my form action
<form class="form-vertical" role="form" method="post" action="">

A: You can define your route as:
Route::put('projects/{projects}/collaborators/{id}',['uses'=>'ProjectCollaboratorsController@update', 'as' => 'projects.collaborators.update']);

Then in your form you can do as:
<form class="form-vertical" role="form" method="post" action="{{ route('projects.collaborators.update', ['projects' => 1, 'collaborators' => 2]) }}">

Docs

A: Another option is to use Laravel Collective.
Then you can create forms as simple as echo Form::open(['action' => 'Controller@method'])