text:
Q: unity c#-- rotation problems when snapping to terrain I'm working on some objects can be moved around by the user via the mouse. They snap to the terrain whenever dragging so they can't actually be pulled off the terrain. This was in place before I was put on the project.
My task is to make the objects not only snap positionally but rotationally(hug slopes, etc). Currently I've made a prefab that shoots 3 rays to the ground (-up of object). I average the normals of the hits and then set the object's up vector to that value. Which at first I thought was working fine because I was testing with a cube and couldn't visually see issues.
So then I tried on a truck model. Seemed fine, but then I rotated the truck then went to drag again and I found it was snapping to a y rotation that was different than before I started dragging. I THINK this is because the forward vector is auto-recalculating when I directly set the up.
Below is my update method that does the work I've specified. It would be much appreciated if anyone can tell me how I can achieve the desired effect.
void Update()
{
   //TargetObject.transform.position+=-TargetObject.transform.up*Time.deltaTime;
   //_snapChildren.ToArray()[2].transform.RotateAround(new Vector3(0.0f, 1.0f, 0.0f), Time.deltaTime);

   //Debug.LogWarning("Mouse Button 0 down: "+Input.GetMouseButton(0));

   if (_OI.GetActiveObject()==TargetObject.gameObject && _OI.GetActiveObjectDragging())
   {
      //Debug.LogWarning("We are the active object being dragged!!");

      //_curHitInfo=_snapChildrenHitInfos.ToArray()[0];
      if (Physics.Raycast(TargetObject.transform.position, -TargetObject.transform.up, out _hitInfo, 100.0f,
                          _targetLayerMask))
      {
         _normals.Clear();
         _normals=new List<Vector3>();

         //Debug.LogWarning("Ding!! "+_hitInfo.transform.name);
         for (int iChild=0; iChild<_snapChildren.Count; iChild++)
         {
            _curHitInfo=_snapChildrenHitInfos.ToArray()[iChild];
            //Debug.LogWarning("LayerMask.NameToLayer(\"Draggable\"): "+(1 << LayerMask.NameToLayer("Draggable")));
            Physics.Raycast(_snapChildren.ToArray()[iChild].transform.position,
                            -_snapChildren.ToArray()[iChild].transform.up, out _curHitInfo, 100.0f,
                            _targetLayerMask);

            _normals.Add (new Vector3(_curHitInfo.normal.x, _curHitInfo.normal.y, _curHitInfo.normal.z));
            //Debug.LogWarning("Ding!! "+iChild+' '+_curHitInfo.transform.name);
            //Debug.LogWarning("_curHitInfo.normal: "+_curHitInfo.normal);
            /*Debug.LogWarning("_snapChildrenHitInfos.ToArray()[iChild].normal: "+
                             _snapChildrenHitInfos.ToArray()[iChild].normal);*/
            //Debug.LogWarning("_normals.ToArray()[iChild]: "+_normals.ToArray()[iChild]);
         }

         Vector3 avgNormal=new Vector3(0.0f, 0.0f, 0.0f);
         for (int iNormal=0; iNormal<_normals.Count; iNormal++)
         {
            avgNormal+=_normals[iNormal];
            //Debug.LogWarning("_normals["+iNormal+"]: "+_normals[iNormal]);
         }
         avgNormal/=_normals.Count;
         //Debug.LogWarning("avgNormal: "+avgNormal);

         //TargetObject.transform.localRotation=Quaternion.Euler(avgNormal);
         TargetObject.transform.up=avgNormal; //MAKE A POST ON STACK OVERFLOW...if limiting rotation to x/z
                                     //doesn't work
      }
   }
}


text:
Q: Conditional check of DateTime in x-kendo-template Approved is a DateTime in my model. approvedDate is a Datetime variable in my Razor view.  The script block is inside the same Razor view.
I want to test Approved to see if it is before approvedDate, and replace it with a empty string "" if it is, inside the x-kendo-template detail-template.
@{ var approvedDate = DateTime.Parse("01-01-2016"); }

The above syntax causes the detail-template script to fail.
What is the syntax to make this if statement work?

A: There were two problems, a syntax one and using a Razor DateTime variable in the conditional.
I have both an if else and a ternary syntax working and have converted the Razor variable to a javascript Date.
@{ var approvedDate = "01-01-2015"; }

The following was displayed:
Test1:  Fail
Test2:  08-22-2015
Test3: Fail
Test4: 08-22-2015
I changed it a bit from the OP.  It now displays Applied if the condition passes and 'Fail' if it failed.  Now that the two issues have been resolved the code could be easily modified to the original behavior.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xml tags printing differently in Restcontroller I am using a controller for post mapping in spring
@PostMapping(value ="/HttpNoRespAdapter",consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_XML_VALUE}, produces=MediaType.APPLICATION_XML_VALUE)
    protected String process(@RequestBody String request, HttpServletResponse response)  {

        }

I am taking whatever coming in the requestbody as string, the following xml should come
<REQ><FEATURE>DELIVERY-RECEIPT</FEATURE><TIME-STAMP><![CDATA[20200925190730]]></TIME-STAMP><TRANSACTION-ID><![CDATA[71554]]></TRANSACTION-ID><SMPP-ID><![CDATA[airtel]]></SMPP-ID><COMMAND-ID><![CDATA[5]]></COMMAND-ID><OA><![CDATA[8407600010]]></OA><DA><![CDATA[555]]></DA><DCS><![CDATA[0]]></DCS><SMS><![CDATA[stat:DELIVRD err:000 Text:silent]]></SMS><MESSAGE-ID><![CDATA[19]]></MESSAGE-ID></REQ>

But it coming as
%3CREQ%3E%3CFEATURE%3EDELIVERY-RECEIPT%3C%2FFEATURE%3E%3CTIME-STAMP%3E%3C%21%5BCDATA%5B20201007175019%5D%5D%3E%3C%2FTIME-STAMP%3E%3CTRANSACTION-ID%3E%3C%21%5BCDATA%5B60564%5D%5D%3E%3C%2FTRANSACTION-ID%3E%3CSMPP-ID%3E%3C%21%5BCDATA%5Bairtel%5D%5D%3E%3C%2FSMPP-ID%3E%3CCOMMAND-ID%3E%3C%21%5BCDATA%5B5%5D%5D%3E%3C%2FCOMMAND-ID%3E%3COA%3E%3C%21%5BCDATA%5B8007600010%5D%5D%3E%3C%2FOA%3E%3CDA%3E%3C%21%5BCDATA%5B555%5D%5D%3E%3C%2FDA%3E%3CDCS%3E%3C%21%5BCDATA%5B0%5D%5D%3E%3C%2FDCS%3E%3CSMS%3E%3C%21%5BCDATA%5Bid%3A69+sub%3A001+dlvrd%3A001+submit+date%3A2010071750+done+date%3A2010071750+stat%3ADELIVRD+err%3A000+Text%3Asilent%5D%5D%3E%3C%2FSMS%3E%3CMESSAGE-ID%3E%3C%21%5BCDATA%5B69%5D%5D%3E%3C%2FMESSAGE-ID%3E%3C%2FREQ%3E=

the xmltags are been replaced wrongly. how can i rectify this??

A: Try to use java.net.URLDecoder:
request = URLDecoder.decode(request, "UTF-8");


text:
Q: how to response before the server return on iOS my situation is  like this:
when you press a button, it will first hide the button, and then send a http request to the server, the request is sent to a php script and execute an "exe" to use the printer to print something.
But when I test the app, I find the button hides when the "exe" on the server exits, the result is that when I press the button, the application is like "not response", the button
dose not hide and keep the state of "press down", it is not user-friendly. So any ideas
to help me solve this ?

Finally, I used slef performSelectorInBackground, since I did not care the result php return, it works well and easier than Asynchronous call.

A: It may be that you are making a synchronous call to the server. Check here for how to make asynchronous calls.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

A: interface updates are only done after the method finishes. try running the php part in an extra method with performSelector:
- (void)yourCurrentMethod {
    button.hidden = YES;
    [self performSelector:@selector(doSomething)];
}

- (void)doSomething {
    /* call php script, etc */
}

A: Sorry, what I meant was performSelector:withObject:afterDelay:
- (void)yourCurrentMethod {
    button.hidden = YES;
    [self performSelector:@selector(doSomething) withObject:nil afterDelay:0.1];
}

- (void)doSomething {
    /* call php script, etc */
}

That will process the hidden in the UI and then call the doSomething-method without making it a background thread, so you can use a synchronous request. Using asynchronous requests is a little more work (but cleaner), which you don't really need, if you only want to call the php and don't care about the result.


text:
Q: how do I know UIDocumentInteractionController can not open a file? UIDocumentInteractionController *documentVc = [UIDocumentInteractionController interactionControllerWithURL:fileURL];

documentVc.delegate = self;

if (![documentVc respondsToSelector:@selector(presentPreviewAnimated:)]) {
     NSLog(@"can not open this file");
} else {
    [documentVc presentPreviewAnimated:YES];
}

when UIDocumentInteractionController can not open a file, I want to know how to tip user, that file can not be open. any idea?
and my code is not working.

A: [documentVc presentPreviewAnimated:YES]
this method has a return value to indicate whether a file was able to display.


text:
Q: GNOME Flashback on Ubuntu Server Can you install the GNOME Flashback desktop environment on Ubuntu Server 18.04 and beyond?

A: Yes, you can install GNOME FlashBack session on 18.04 LTS:
sudo apt-get install gnome-panel

and then select GNOME FlashBack (Metacity) on login screen.
But as it is a server system I recommend to switch it back to console login as default target:
sudo systemctl set-default multi-user.target

and run GNOME FlashBack manually on demand:
sudo systemctl isolate graphical.target


text:
Q: SUMPRODUCT with Dates for Criteria I am trying to obtain an average of an array of fields with the following simple formula
=SUMPRODUCT(Main!BA:BA, Main!CY:CY, --(Main!D:D >=D3, Main!D:D <=E3))

I'm getting a #DIV/0! error. I have no clue why it's dividing anything. Please help!
Basically, how can I get the sum product of columns D vs E between the dates 11/05 to 11/27.

A: From looking at your worksheet, you want this:
=SUMPRODUCT(D:D*E:E*(C:C>=$C$27)*(C:C<=$C$49))

A: You need to use * or + depending on whether you want AND or OR.
=SUMPRODUCT(Main!BA:BA, Main!CY:CY, (Main!D:D >=D3)*(Main!D:D <=E3))

One more note:
You want to limit the references to only that with data as this formula will do a lot of unneeded calculations.


text:
Q: Duplicate tree-structure in org-mode archive In Orgmode under Emacs, is there already a way programmed to automatically duplicate in the archive the tree structure above an item being archived?
My new org-mode structure in a file looks like the following:
* CONFIGURE
** Operating Systems
*** Debian Unstable
*** Demodyne

** Machines
(...)
** Software
(...)

After archiving the entry "Demodyne", I would like the archive to contain the following:
* CONFIGURE
** Operating Systems
*** Demodyne

I thought I had seen it in the documentation of org-mode when I started using it many many years ago, but did not find anything like this in the documentation of the latest version at http://orgmode.org/manual/ (the entry on archiving http://orgmode.org/manual/Archiving.html#Archiving is rather succinct). I feel I could program it, but I would rather not if it has been done before...

A: There's a partial solution for this at https://gist.github.com/edgimar/072d99d8650abe81a9fe7c8687c0c993.
This could be a really nice solution, however, it only works for me when executing on a single DONE task. If I try extending it to all DONE tasks in a subtree using org-map-entries as shown below, it creates a new top-level * ARCHIVED heading each time it's run. Is there a way to avoid this unwanted behavior?
Example of undesired behavior with org-map-entries
Define function to operate on all DONE tasks in current subtree:
(defun org-archive-done-tasks ()
  (interactive)
  (org-map-entries 'org-archive-subtree-hierarchical "/DONE" 'tree))

Note: org-archive-subtree-hierarchical is found in above link.
Now if I take the following buffer
* Project 1
** TODO Task 1
** TODO Task 2
** TODO Task 3

and mark Task 1 DONE, run org-archive-done-tasks on Project 1, and then do the same for Task 2, the buffer results in
* ARCHIVED
** Project 1
*** DONE Task 1

* ARCHIVED
** Project 1
*** DONE Task 2

* Project 1
** TODO Task 3

Here is the desired result, which is what would happen if org-archive-subtree-hierarchical were run directly on ** DONE Task 1 and then ** DONE Task 2 (as children of * Project 1)
* ARCHIVED
** Project 1
*** DONE Task 1
*** DONE Task 2

* Project 1
** TODO Task 3

Is the desired behavior possible using org-map-entries? Is there a better method of executing org-archive-subtree-hierarchical on all DONE tasks in a subtree multiple times without duplicating the archive target heading?


text:
Q: mysql query from php isnt working but it works in a different php file I'm trying to make a query from my MySQL database here is the code
<?php
     $link = new MySQLi('localhost','root','Rrtynt','copy');
    if(isset($_POST['id'])){
        $name = $_POST['id'];
        $profile = 'profile';
        $thestring = $name.$profile;
       //echo $thestring;

       $result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");
       echo $result;
        }
?>

the code for the query
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");

works in a different php script the same exact code but it keeps giving me http 500 error, I'm using this to post from a javascript file
$.post("/getfirstfolder.php", { id: value1 }, function (data) {
                            cop = data;
                            console.log("Data: " + data);
                        });

if I take out
 $result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$name'");

and just echo $thestring it works fine, I cant figure out the problem so thank you for your time and your help is greatly appreciated

A: The fact that you mentioned $thestring, makes me think that perhaps you should be using $thestring as the parameter to the query like this:
$result = $link->query("SELECT Email,Name,idauth FROM user WHERE Email = '$thestring'");


text:
Q: Custom button from jquery dialog not calling controller action I have main view and open a dialog by using the jquery dialog like below.
function ShowDialog() {

    dialog = $('#reassign').dialog({
        autoOpen: false,
        height: 500,
        width: 700,
        modal: true,

        open: function () {
            $('#reassign').load('/ItemsList/Reassign');
        }
    });
    dialog.dialog("open");

}
The content of the dialog is in a PartialView. I have a button on that dialog and I want to call another action to load a list of users. This how I call the action method. But its not getting fired.
$('#searchUser').click(function () {
        var search = $('#search').val();
        alert(search);
        $.ajax({
            ur1: '@(Url.Action("Users", "WorkItemsList"))',
            type: 'POST',
            success: function(result) {
                alert(result);
            }
        });
    });

Am I missing something?


text:
Q: What is the advantage of storing a lambda in a `std::function` as opposed to an `auto variable`? What is the advantage of storing a lambda in a std::function as opposed to an auto variable. For example in the code below I store the lambda in variable f1 rather than in std::function f.
#include <iostream>
#include <functional>
using namespace std;

void global_f() {
    cout << "global_f()" << endl;
}

struct Functor {
    void operator()() { cout << "Functor" << endl; }
};

int main() {
    std::function<void()> f;

    cout << "sizeof(f) == " << sizeof(f) << endl;

    f = global_f;
    f();

    auto f1 = [](){ cout << "Lambda" << endl;};
    f1();

    Functor functor;
    f = functor;
    f();
}

A: In your simple example, there is no advantage to storing the lambda inside a std::function.  Often, storing a lambda using auto is more efficient, but it also highly restrictive.  The auto version can serve only as a local variable.  If you want to store the lambda for later use, then you must use a std::function.
For example, you might want to store the lambda inside a class member.  Consider the following class:
class Foo
{
  std::function<void()> callback_;
public:
  void Bar(int value)
  {
    callback_ = [value] { DoStuff(value); }
  }
  /* other constructors and methods omitted */
}

In this case, you can't use auto because the lambda's type is anonymous and only available within the Bar method.
std::function is also useful when you want to use lambdas as arguments to regular functions.  The function has no way to know the lambda's type, but it can declare a std::function parameter instead.  For example:
void Foo(std::function<void()> callback);

...

Foo([](){ cout << "Lambda" << endl;});

It's worth pointing out that this does not apply to function templates.  When using a lambda in such a context, it's usually a better idea to let the compiler deduce the lambda's type (similar to using auto).  For example:
template <class F> void Foo(F&& callback) { /* details */ }

...

Foo([](){ cout << "Lambda" << endl;}


text:
Q: Plotly plot is pushed out of bounds in flexdashboard I am having trouble getting my plotly plot to fit in its flexdashboard container. The bottom gets cut off.
Consider the following reprex:
---
title: "Plotly Flexdashboard Conflict"
output:
  flexdashboard::flex_dashboard:
      source_code: embed

---

Column
---

### In this tab, the plot is pushed out of bonds by the selectize items.

```{r}
library(tidyverse)
library(plotly)
library(gapminder)
library(flexdashboard)

gapminder_highlighted <-
  highlight_key(gapminder[1:408,], ~country, "Select a country")

gapminder_ggplot <-
  gapminder_highlighted %>%
  ggplot(aes(x = year, y = lifeExp, group = country), alpha = 0.2) +
  geom_line()

gapminder_plotly <- ggplotly(gapminder_ggplot)

highlight(gapminder_plotly, dynamic = T, selectize = T, persistent = T)

```

### Without selectize, all is well. The x axis is visible.

```{r}
gapminder_plotly
```

Column
---

### When plots overflow, flexdashboard is meant to add a scrollbar. E.g.

```{r}
plot(cars)
plot(nhtemp)
plot(cars)
plot(nhtemp)
```

### Although this does not actually work for all elements. E.g. Text generated from code chunks fails to trigger slider addition:

```{r}
cat( rep("Flex is not responsive to text overflow here.           ", 100) )
print("This line is hidden")
```

Output is on Rpubs here so you can have a look: https://rpubs.com/kenwosu/661556
The first gapminder plot is pushed out of bounds by the selectize items. And flexdashboard doesn't trigger the addition of a vertical scrollbar like it should.

Any help would be extremely appreciated!

A: Does this look a little bit better? I changed the y axis to start at 0 and it appears to be a little bit more clearly displayed. I just added + expand_limits(y = 0) to the end of the ggplot graph. I tried messing with ggplotly() but it appeared it was the ggplot graphic that had the figure issue.
---
title: "Plotly Flexdashboard Conflict"
output:
  flexdashboard::flex_dashboard:
      source_code: embed

---

Column
---

### In this tab, the plot is pushed out of bonds by the selectize items.

```{r}
library(tidyverse)
library(plotly)
library(gapminder)
library(flexdashboard)

gapminder_highlighted <-
  highlight_key(gapminder[1:408,], ~country, "Select a country")

gapminder_ggplot <-
  gapminder_highlighted %>%
  ggplot(aes(x = year, y = lifeExp, group = country), alpha = 0.2) +
  geom_line() + expand_limits(y = 0)

gapminder_plotly <- ggplotly(gapminder_ggplot)

highlight(gapminder_plotly, dynamic = T, selectize = T, persistent = T)

```

### Without selectize, all is well. The x axis is visible.

```{r}
gapminder_plotly
```

Column
---

### When plots overflow, flexdashboard is meant to add a scrollbar. E.g.

```{r}
plot(cars)
plot(nhtemp)
plot(cars)
plot(nhtemp)
```

### Although this does not actually work for all elements. E.g. Text generated from code chunks fails to trigger slider addition:

```{r}
cat( rep("Flex is not responsive to text overflow here.           ", 100) )
print("This line is hidden")
```


text:
Q: Error al evaluar contraseña encriptada desde PHP a Mysql Estoy tratando de hacer un login, pero el problema viene cuando tengo que comparar la contrase?a cifrada devuelta de la BBDD, cuando la compruebo con password_verify() es como si no coincidiera con la que esta en la BBDD.
Bueno aqui mi codigo
<?php

try {

    $base= new PDO("mysql:host=localhost; dbname=contador" , "root", "");

    $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql="SELECT * FROM usuarios WHERE ID=:id AND usuario = :usuario AND contra= :contra";

    //contador

    $contador = 0;

    //preparar consulta
    $resultado=$base->prepare($sql);

    //recivir parametros de el formulario
    $login= htmlentities(addslashes($_POST['usuario']));
    $password = htmlentities(addslashes($_POST['contra']));
    $ID=0;

    $resultado->bindValue(":usuario", $login);
    $resultado->bindValue(":contra", $password);
    $resultado->bindValue(":id", $ID);

    $resultado->execute(array(":id"=>$ID, ":contra"=>$password, ":usuario"=>$login));

     $registro=$resultado->fetch(PDO::FETCH_ASSOC);

    if (password_verify($password, $registro['contra'])) {

        $contador++;
    }

    $numero_registro=$resultado->rowCount();

    if ($numero_registro !=0 && $contador!=0){

        session_start();

        $_SESSION['usuario']=$_POST['usuario'];

        header("location: http://192.168.1.31/contador/");

    }else{

        header("location: index.php");
    }

}catch(Exception $e) {

    die("Error: " .  $e->getMessage());

}

en vez de redireccionarme a http://192.168.1.31/contador/
lo hace a index.php
y la contrasena revise bien y si coincide a la que ingreso en el formulario. Tampoco me lanza algun tipo de error.
Este es el codigo con el que inseerte el registro
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'contador';

$conexion = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno($conexion)) {

    echo 'Ha ocurrido un error al conectar a la base de datos';
    exit();

}

mysqli_set_charset($conexion, "utf8");

$contra_has = "contrasena";

$cifrada = password_hash($contra_has, PASSWORD_DEFAULT);

$sql = $conexion->query("INSERT INTO usuarios(usuario,contra) VALUES ('usuario', '$cifrada')");
if ($sql) {

    echo 'Se insertado correctamente';

}else{

    echo 'Ha ocurrido un error';
}

?>

A: Si tu contraseña en la tabla está hasheada con password_hash y buscas en la tabla por una contraseña igual al texto plano que recibes por POST nunca van a coincidir. Debe ser:
$sql="SELECT * FROM usuarios WHERE   usuario = :usuario";

$resultado=$base->prepare($sql);

$resultado->execute(array(":usuario"=>$login));

$registro=$resultado->fetch(PDO::FETCH_ASSOC);

if (password_verify($password, $registro['contra'])) {
   $contador++;
}

Edit: por recomendación de @Xerif, mejor quitar el ID porque la pantalla de login no va a pedir ese campo ni el backend tiene como adivinarlo antes de ejecutar la consulta.

A: Hay varias cosas que podrían estar trayendo problemas en tu código. Las voy a enumerar aquí:

*

*No estableces la codificación a UTF-8 cuando creas la conexión a PDO

*El uso (que en este caso no sirve absolutamente para nada) de htmlentities y de addslashes. Has de saber que PDO es mayor de edad y que se protege sólo contra cualquier tipo de Inyección (a condición de que lo uses bien, mediante consultas preparadas). Además, como he demostrado en una respuesta al tema de la Inyección SQL, las dos funciones antes mencionadas se revelan inútiles para la protección de nuestro código.

*En PDO, no necesitas usar bindValue en este caso. Puedes bindear directamente en el execute.

En el código que propongo corrijo todo eso. Y además, me permito optimizar tu consulta (si quieres sólo la contraseña, no veo por qué tengas que hacer un SELECT *....
Me permití además optimizar la forma de obtener la contraseña, usando fetchColumn en lugar de fetch. Es simple: traemos sólo lo que necesitamos, nada más. No seas como quienes se van de viaje por tres días y llevan ropa por tres meses. Menos mal que hoy día te limitan por todas partes el equipaje. :)
Propongo que pruebes este código y comentes el resultado:
<?php

try {

    $base= new PDO("mysql:host=localhost; dbname=contador;charset=utf8" , "root", "");
    $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql="SELECT contra FROM usuarios WHERE ID=:id AND usuario = :usuario AND contra= :contra";

    //contador
    $contador = 0;

    //preparar consulta
    $resultado=$base->prepare($sql);

    //recibir parametros de el formulario
    $login= $_POST['usuario']);
    $password = $_POST['contra'];
    $ID=0;
    /*Esto es todo lo que PDO necesita en consultas preparadas*/
    $arrParams=array(":id"=>$ID, ":contra"=>$password, ":usuario"=>$login);
    $resultado->execute($arrParams);

    $registro=$resultado->fetchColumn();

    if (password_verify($password, $registro)) {

        $contador++;
    }

    $numero_registro=$resultado->rowCount();

    if ($numero_registro !=0 && $contador!=0){

        session_start();
        $_SESSION['usuario']=$_POST['usuario'];
        header("location: http://192.168.1.31/contador/");

    }else{

        header("location: index.php");
    }

}catch(Exception $e) {
    die("Error: " .  $e->getMessage());

}

PD: Me extrañó también que usaras PDO para una cosa y MySQLi para otra. Usa una sola, o PDO o MySQLi. Yo te recomendaría PDO... es mejor, más seguro, más completo, más todo.


text:
Q: argument passing in pthread_creation I am learning how to work with pthread functions.
Here i want to create a thread using pthread_create and calculate the average of some numbers with it.
( a 0 at the end of the number sequence shows it has finished)
This is what I've written so far:
#include<stdio.h>
#include<stack>
#include<pthread.h>

using namespace std;

void *Thread1(void*argument)
{
printf("in Thread1\n");

int sum=0;
int count=0;
stack<int> numbers;
(stack<int>) numbers = *((stack<int>*) argument);
int size = numbers.size();

while(numbers.size()!=0)
{

sum=sum+numbers.top();
count=count+1;
numbers.pop();
}

int result= sum / count;
printf("Average is :");
printf("%d",result);

pthread_exit(0);

}

int main(void)
{
printf("Enter your numbers\n");

int num;
stack<int> numStack;
scanf("%d",&num);
numStack.push(num);

while( num!=0)
{
scanf("%d",&num);

numStack.push(num);
}

numStack.pop();
pthread_t myThread;
int ret;

ret=pthread_create(&myThread,NULL,Thread1,&numStack);

if (ret<0)
   printf("Thread Creation Failed\n");

pthread_join(myThread,NULL);
return 0;
}

when i get the size of my stack in main and check it by printing it, it's correct but when i do the same in the Thread1 function the size is 0.  Therefore i get the
Floating point exception (core dumped)

error.
Why the size of my stack turns into 0?  How can i solve this problem?
Thanks in advance

A: This
(stack<int>) numbers = *((stack<int>*) argument);

cast is the root of the zero size set. The first C-Type cast creates a temporary unnamed object as a copy of numbers which vanishes after assignment. numbers is never changed. Make it:
numbers = *((stack<int>*) argument);


text:
Q: Semisimple Frobenius Algebras I'm reading this paper and am stuck on the proof of theorem 3.4 on page 7.  In particular, how does the author justify the statement below

If some component A′ of A is not a field, then it contains nontrivial
  nilpotents

A: Context: $A$ is assumed to be a commutative Frobenius algebra over some field $k$, and $A^{\prime}$ is a factor in the decomposition of $A$ as a product of local $k$-algebras.
The author's claim then follows since (as a finite-dimensional $k$-algebra) $A^{\prime}$ as Artinian local, hence its maximal ideal is nilpotent. Therefore $A^{\prime}$ is a field if and only if its maximal ideal is the zero idealif and only if it has no nontrivial nilpotents.


text:
Q: Scala implicit parameter scope I've spent all morning reading up on how Scala scopes implicits, including the very excellent answer here: Where does Scala look for implicits?
But alas, I am still confused. Let me give an example of what I'm trying to do:
object Widget {
  implicit val xyz: Widget = new Widget("xyz")
}
class Widget(val name: String) {
  override def toString = name
}
class Example {
  def foo(s: String)(implicit w: Widget): Unit = {
    println(s"Got $s with $w")
  }
  def bar {
    foo("abc")  // Compiler error at this line
  }
}

object implicit_test {
  val x = new Example()
  x.bar
}

So, I expect to see something like Got abc with xyz. Instead I get told could not find implicit value for parameter w: Widget. Now, strangely if I move the Widget class and object as well as the Example class inside the implicit_test object, then this works.
Please explain to me again, if you will, how exactly Scala identifies which implicit val to use!

A: Your code should work and it does work for me.
Did you by chance type that in the REPL? If so, there is something special concerning companion objects. In scala, a companion object must be in the same file as its class (otherwise, the code is valid, but it is not a "companion object", just an object with the same name, and not part of the implicit scope). In the REPL, there are no files, but the class and its companion object must  be defined at the same time. To do that, you must enter them in paste mode.
Type :paste, then paste (or just type) at least both the object Widget and the class Widget (you may paste the rest to the code at the same time, but it is not necessary), and then CTRL-D. That should work.


text:
Q: Spring Boot Kafka Consumer throwing No bean named 'kafkaListenerContainerFactory' available pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mobicule</groupId>
    <artifactId>spring-boot-kafka-consumer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-kafka-consumer</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

KafkaConfiguration.java
package com.mobicule.springbootkafkaconsumer.config;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;

@EnableKafka
@Configuration
public class KafkaConfiguration {

    @Bean
    public ConsumerFactory<String, String> consumerFactory()
    {
        Map<String, Object> config = new HashMap<String, Object>();

        config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        config.put(ConsumerConfig.GROUP_ID_CONFIG, "group_id");
        config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

        return new DefaultKafkaConsumerFactory<String, String>(config);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaConsumerFactory()
    {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<String, String>();

        factory.setConsumerFactory(consumerFactory());
        return factory;
    }

}

KafkaConsumer.java
package com.mobicule.springbootkafkaconsumer.listener;

import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
public class KafkaConsumer {

    @KafkaListener(topics="ConsumerDemo",groupId="group_id")
    public void consume(String message)
    {
        System.out.println("In kafka consumer "+message);
    }

}

I have configured Basic Kafka Producer project using Spring Initializer (without server)
1) I produced a message "Hello World" on topic "ConsumerConfig" using terminal
   Then when i executed my consumer project i got error as
The following candidates were found but could not be injected:
    - Bean method 'kafkaConsumerFactory' in 'KafkaAutoConfiguration' not loaded because @ConditionalOnMissingBean (types: org.springframework.kafka.core.ConsumerFactory; SearchStrategy: all) found beans of type 'org.springframework.kafka.core.ConsumerFactory' consumerFactory
    - User-defined bean method 'consumerFactory' in 'KafkaConfiguration'

Action:

Consider revisiting the entries above or defining a bean of type 'org.springframework.kafka.core.ConsumerFactory' in your configuration.

So i searched and i got a link which said put
@SpringBootApplication(exclude = KafkaAutoConfiguration.class)
Even after putting the above in my code i got an error as
Description:
A component required a bean named 'kafkaListenerContainerFactory' that could not be found.

Action:

Consider defining a bean named 'kafkaListenerContainerFactory' in your configuration.

What am i missing here ? Do i need to do anymore configurations?

A: If you use Spring Boot, you don't need that custom ConsumerFactory, neither ConcurrentKafkaListenerContainerFactory. You should fully rely on the auto-configuration and appropriate configuration properties from the spring.kafka namespace: https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-kafka
If you still insist to exclude KafkaAutoConfiguration and do everything manually, you really need to name your ConcurrentKafkaListenerContainerFactory with the requested kafkaListenerContainerFactory bean name: https://docs.spring.io/spring-kafka/docs/2.2.0.RELEASE/reference/html/_reference.html#kafka-listener-annotation


text:
Q: Conjugate Function Is Lower Semicontinuous Let $E$ be a Normed Vector Space. Let $\phi : E \rightarrow ( - \infty , + \infty] $ be a function such that $\phi$ is not equivalent to $\infty$. i.e. The set $ \{ x \in E : \phi (x) \neq \infty \}$ is not empty.
The Conjugate Function $\phi^* : E^* \rightarrow ( - \infty , + \infty]$ is defined as follows:
$$ \phi^* (f) = ^{\text{sup}} _{x \in E} \{ \{f(x) - \phi (x) \} \}$$
here, $E^*$ is the Dual Space of $E$.
My textbook claims that such $\phi^*$ is lower semicontinuous. Could someone please offer a hint for me to prove this? Thank you.

A: Note that, given any $x$, the map $f \mapsto f(x) - \phi(x)$ is affine and continuous. In particular, the epigraph is closed and convex (in fact, weak$^*$ closed).
The epigraph of $\phi^*$ is the intersection of all these epigraphs, which makes it (weak$^*$) closed and convex. Thus $\phi^*$ is closed and (weak$^*$) lower-semicontinuous.


text:
Q: Jump to the right C++ STL documentation page in QtCreator after F1? QtCreator comes with cool Qt-related documentation and functionality: when you select a Qt class and press F1, it opens a sidebar with that class specific documentation page.
Now, QtCreator lets me install C++ documentation (found here: http://qt-project.org/wiki/Qt_Creator_Documentation_Gallery - I've tried the en.cppreference.com version). However, selecting an STL class and pressing F1 only opens the default, generic page listine, sort of "Home" of the documentation.
Is it possible to have a mimic functionality for C++ STL docs to the one of Qt docs?
Also, I've checked it in QtCreator 2.4 running on Ubuntu 12.04. Is it maybe fixed in newer versions?

A: In case you're still looking for an answer to this (or for anyone else finding this posting), there is a working solution now. In the official documentation gallery there is a download link labelled STL documentation. That version will provide correctly working context sensitive look-up. There are a few things where that seems to fail though (like std::unique_ptr), but for most things I tested it works just fine. Some things find a technically correct but not helpful entry though. As an example, std::fill(...) will link to the correct entry in "std Namespace Reference" (which is just a line of the definition, and not linked to anything useful either) but not the description on the "Mutating" page (which is the first suggestion when searching for 'fill' via the index).
Please ignore the two links that are still at the top of that page though, those either completely lock-up the help system (docs.google.com) or just don't provide context sensitive help (en.cppreference.com).

A: Unfortunately, cppreference docs don't support navigation with F1.


text:
Q: find exact value from user input to csv file content I have a simple HTML file with input text id="ERP", I want the user to be able to find the exact match to the CSV file content. Here is the code I have been trying to fix. This searches the CSV file but returns result not exactly as the value entered from input box, Example, input box value = "CH-134", the out-put will show data for "CH-134-DT" how can I make the search result exactly the same as the input? Thank you in advance.
    var DB = new Array();
    function MakeDB() { DB = CSV.split('\n'); }

    function CSVsearch(dbInfo) {
    var posn = -1;
    for (i=0; i<DB.length; i++) {
    tmp = DB[i];
    if (tmp.indexOf(dbInfo) != -1) { posn = i; break; }
    }
    if (posn == -1) { alert('No matching result from the file'); }
    else { document.getElementById('tblDisplay').innerHTML = displayAsTable(DB[posn]); }
    }
    function displayAsTable(info) {
    var table = '
';
    var ary = info.split(',');
    table += '
'+ary.join('
')+'
';
    table += '
';
    return table;
    }
    function resetthis() {
    document.getElementById("myForm").reset();

}

A: I think I would use the Javascript str.match(regexp) function and a regular expression, instead of using the str.indexOf(searchValue) function.
So in your case, I'd do something like:
var regex = '/\b' + dbInfo + '\b/g';
var matches = tmp.match(regex);
if (matches.length > 0)
{ ... }

Just replace the '\b' above with whatever you'd expect your incoming data to be separated by. For example, if you expect to find CH-134 is in your dataset with spaces before and after, you can leave the '\b' there. If it is in your dataset with commas, you can replace '\b' with ','. Or if you only know what terminates the word you're trying to match, you can leave off the first '\b' from the regex. For example, you could do something like:
//finds occurences of dbInfo with anything before it, but only a comma after it
var regex = '/' + dbInfo + ',/g';

//finds occurences of dbInfo with a word break before it, and no hyphen after it
var regex = '/\b' + dbInfo + '[^-]/g';

You'll probably be able to come up with a better, more precise, regular expression for your needs. My favorite site for playing with and testing out regular expressions is http://regexr.com/
Good luck!

A: tadaaa, as according to Seth, I added the dbInfo + ',' and simply put the 'while' so the loop wont stop when the search hits a similar value. WoohOooo
    var DB = new Array();
    function MakeDB() { DB = CSV.split('\n'); }

    function CSVsearch(dbInfo) {
    var posn = -1;
    var input = document.getElementById('ERP').value;
    for (i=0; i<DB.length; i++) {
    tmp = DB[i]; //ROW DATA
    while (tmp.indexOf(dbInfo+',') != -1) { posn = i; break; }
    }
    var data = DB[posn];
    if (posn >=0) { (alert('RECORD FOUND!\nERP: ' + dbInfo));
    document.getElementById('tblDisplay').innerHTML = displayAsTable(data); }
    else { (alert ('NO RECORD FOUND')); }
    }
    function displayAsTable(info) {
    var table = '
';
    var ary = info.split(',');
    table += '
'+ary.join('
')+'
';
    table += '
';
    return table;
    }
    function resetthis() {
    document.getElementById("myForm").reset();
    }


text:
Q: Scene transition image drawn in tiles during transition I'm facing weird drawing issue with scene transitions (running with Nexus 5x 6.0.1 platform)
I found out that <item name="android:windowBackground">@null</item> has some relation to the issue.
Anyone know why this happens and what can be possible places to check in order to fix this?
Here is my test project setup to reproduce the problem:
minSdkVersion 16 and targetSdkVersion 23 using:

com.android.support:appcompat-v7:23.3.0

AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".NextActivity"/>
</application>

styles.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@null</item>
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final View iv = findViewById(R.id.iv_test);
        ViewCompat.setTransitionName(iv, "test");

        findViewById(R.id.b_go).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this,
                        android.support.v4.util.Pair.create(iv, "test")).toBundle();

                startActivity(new Intent(MainActivity.this, NextActivity.class), bundle);
            }
        });
    }
}

NextActivity.java
public class NextActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);

        final View iv = findViewById(R.id.iv_test);
        ViewCompat.setTransitionName(iv, "test");
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.test.scenetransitions.MainActivity">

    <ImageView
        android:id="@+id/iv_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email"
        android:tint="@color/colorAccent"/>

    <Button
        android:id="@+id/b_go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:background="@color/colorAccent"
        android:padding="20dp"
        android:text="GO"/>
</RelativeLayout>

activity_next.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.test.scenetransitions.MainActivity">

    <ImageView
        android:id="@+id/iv_test"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true"
        android:src="@android:drawable/ic_dialog_email"
        android:tint="@color/colorAccent"/>
</RelativeLayout>

And here is screenshot took in proper time during the transition:

A: The issue is with <item name="android:windowBackground">@null</item> you should never ever use null for window background. Replace it with <item name="android:windowBackground">@android:color/transparent</item>
When you set it to null Android doesn't know what to draw and it could draw any garbage from GPU. So you should explicitly specify transparent background.

A: I copy pasted your code, but i didn't get any drawing issues. I mean when the second page opens up, the image is a bit blurry(pixelated) that's cause of the small size of the actual image(if that's the case just use a bigger image in the second activity). May be its your device. I tested this in Moto E2. For me the transition is smooth, no drawing issues what so ever.


text:
Q: RaphaelJS: Make a line that is solid at the center and has a transparent "border" In RaphaelJS I'm using the path function to draw a black line. This line is draggable, but because of its' width it is hard to drag on a tablet. What I's like to do is fill around the line with a transparent "border". This way the line wouldn't look any wider, but there would be more area to grab on to on a tablet device. Is there any easy way to accomplish this?
Here's an example of how I'm drawing a line:
paper.path("M 150 250 h 200").attr({
fill: "#ff0",
gradient: "90-#526c7a-#64a0c1",
stroke: "#3b4449",
"stroke-width": 5
});

A: The answer may depend a bit on if its going over some other objects etc. If the other solution doesn't work, you could try grouping 2 objects into a set, and have one as the trigger point. So like the following...
var set = r.set();
var rect = r.rect(200,200,50,70).attr({ fill: 'red' });

set.push(
   r.path("M 150 250 h 200").attr({
    fill: "#ff0",
    gradient: "90-#526c7a-#64a0c1",
    stroke: "#3b4449",
    "stroke-width": 5
    })
    );
set.push(
  r.path("M 150 250 h 200").attr({
    fill: "#ff0",
    gradient: "90-#526c7a-#64a0c1",
    stroke: "#3b4449",
    "stroke-width": 20,
    "stroke-opacity": 0.05,
    "stroke-linecap": "round"
    })
);

set.mouseover(function(){
alert('mouse over');
});

There is a fiddle at http://jsfiddle.net/Ap29U/2/ showing it over another object (the opacity could be adjusted further, 0.01 would probably make it pretty much invisble). I've also just added a fiddle at http://jsfiddle.net/Ap29U/3/ showing how you could make them both move together.


text:
Q: Find $l$ of an oblique cone, based on $r, \alpha$ and $\beta$ I am trying to find $l$ of an oblique cone, but the only variables that I have at the moment are $r, \alpha$ and $\beta$. I am not sure if it is even possible.

Edit: Thanks to @Bernards answer I managed to come up with this:
\begin{align*}
h & =l\sin\alpha=m\sin\beta \\
m& = l\frac{\sin\alpha}{\sin\beta}
\end{align*}
\begin{align*}
r^2 &= l^2 + \left(l\frac{\sin\alpha}{\sin\beta}\right)^2-2l\left(l\frac{\sin\alpha}{\sin\beta}\right)\cos(\beta-\alpha) \\
r^2 &= l^2 + l^2\frac{\sin^2\alpha}{\sin^2\beta}-2l^2\frac{\sin\alpha}{\sin\beta}\cos(\beta-\alpha) \\
l &= \sqrt{\frac{r^2}{1+\frac{\sin^2\alpha}{\sin^2\beta}-2\frac{\sin\alpha}{\sin\beta}\cos({\beta-\alpha})}}
\end{align*}

A: You can, starting from the equations
$$h=l\sin\alpha=m\sin\beta,$$
and using Al Kashi's relation:
$$r^2=l^2+m^2-2lm\cos(\beta-\alpha).$$
There remains to eliminate $m$ to obtain an equation in $l$.


text:
Q: Nested Angular Ng-Repeat Performance I have an odd ng-repeat problem related to performance (or at least I believe it's ng-repeat related). I have a list of items that will never be more than 10 or so, but this problem occurs regardless of how many items there are (even when there's only one).
When the page first loads, it's lightning fast. I can even add/update items in the list and it still happens nearly instantaneously. But as soon as I try to remove an item, it takes > 4 seconds. Let me show a couple piece of code.
removeItem(itemId) {
  this.ordersService.removeItem(
    this.order.order_id,
    itemId
  ).then(
    (item) => {
      let index = _.findIndex(this.items, {
        item_id: itemId
      });
      this.items.splice(index, 1);

      console.log('item removed');

      this.$timeout(function() {
        console.log('$timeout fired');
      });
    }, (response) => {
      this.message = response.data.message;
    }
  );
}

Template:

        {{ item.item_number }}
        {{ item.model_number }}
        {{ item.model_title }}

This obviously doesn't run in it's current state, but I think you get the picture. When the row is clicked, it calls the removeItem method on the OrderCtrl. The controller fires off an Ajax request from the service, which completes in about 80ms. Both "item removed" and "$timeout fired" are displayed in my console nearly instantaneously. However it takes about 4 seconds to actually visually remove the rendered element from the list.
Is there anything here that stands out to somebody that I should be doing? I'm about out of ideas. Is it something with the this.items.splice that affects the watches in some weird way or something?


text:
Q: Bluetooth mouse lag -- Precision 5510 -- MX Anywhere 2 -- 16.04 I have an MX anywhere 2. After some effort, I managed to pair it (over bluetooth) to my Dell Precision 5510
(see https://askubuntu.com/a/769095/647310)
Now, when I'm using this mouse, it always starts lagging: the cursor becoming slightly jumpy. I never have this problem with a USB mouse.
The problem is not related to wifi and bluetooth coexistence (as suggested in many related threads): it also occurs when wifi is disabled.
My kernel version is 4.10.0-40-generic
This mouse works fine in Windows. It would be nice to also be able to use it in Ubuntu.
Does anyone have ideas on how to get this working properly?
UPDATE It might be related to bluetooth-wifi coexist. I seem to experience more bluetooth lag when wifi traffic is heavy. However, disabling coexist, or playçng around with that parameter in /etc/modprobe.d/iwlwifi.conf does not seem to help.

A: Tried setting it up on Ubuntu 18.04 and happily (surprisingly, if I'm honest), it worked without any adjustments. True plug and play :-)

A: This sounds like a power save issue, your computer is probably trying to save power by turning off the bluetooth adapter.
I would solve this using powertop, an apt package for monitoring power usage and optimising features. We can use this to remove a power optimisation.
We can begin by installing powertop:
sudo apt-get install powertop

once this is finished, we can run powertop b simply typing
sudo powertop

Press tab until you reach tunable and find your bluetooth adapter.
Press enter so this displays bad.
Finally press esc to exit powertop.


text:
Q: how do I mock objects and their methods in javascript I am having trouble unit testing the javascript function listEntities. The difficulty lies in the mocking/stubbing. The documentation for javascript mocking/stubbing libraries is a mess. I am hoping someone with experience can show me the way. Here is the code:
export const listEntities = (kind, googleDatastoreFactory) => {
  const datastore = googleDatastoreWrapperFactory();
  const query = datastore.createQuery(kind);
  return datastore.runQuery(query)
    .then(results => (results[0]));
};

export const googleDatastoreFactory = () => {
    const Datastore = require('@google-cloud/datastore');
    return Datastore();
};

Here is my attempt:
describe('datastore api', () => {
  describe('listEntities', () => {
    const mockedGoogleDatastore = JsMockito.mock(GoogleDatastore);
    JsMockito.when(mockedGoogleDatastore).runQuery('query').thenReturn(new Promise(resolve => resolve(['result'])));
    JsMockito.when(mockedGoogleDatastore).createQuery('Test').thenReturn('query');
    const googleDatastoreFactory = () => (mockedGoogleDatastore);
    test('should return list of items', () => {
      listEntities('Test', googleDatastoreFactory).then(result => console.log(result));
    });
  });
});

Here is my error:
  ● datastore api › listEntities › encountered a declaration exception

    TypeError: _jsmockito2.default.mock is not a function

      at Suite.<anonymous> (app/api/datastore.api.test.js:7:60)
      at Suite.<anonymous> (app/api/datastore.api.test.js:6:3)
      at Object.<anonymous> (app/api/datastore.api.test.js:5:1)
          at Generator.next (<anonymous>)
          at Promise (<anonymous>)
          at Generator.next (<anonymous>)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)

A: I ended up not using a mocking library/framework. I just created a dumby class.


text:
Q: Why can't I set the value of variable using other variables using =? In my unity project I have a grid which I coded the columns and rows like this:
public int rows = 10;
public int columns = 10;

But then when i try to set the value of another variable like this:
Total = columns * rows;

It gives me the following errors:
A field initializer cannot reference the non-static field, method, or property 'Enemy.rows'
A field initializer cannot reference the non-static field, method, or property 'Enemy.columns'

However it does work if I use => instead of = and I wanted to know why.
The only thing I can think of is because the values of columns and rows can change.
I know => is a getter but I don't understand much about it as I am new to unity/c#.

A: As you may read in the c# Specification, "A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name".
class A
{
    int x = 1;
    int y = x + 1;        // Error, reference to instance member of this
}

The typical way to encounter this error is on the attemp to set an array size at the instance field variable initializers of a class, which throws the Compiler Error CS0236 for the very same reason.
public class MyClass : MonoBehaviour{

    int size = 6;
    float[] f = new float[size]; //not allowed

    // Start is called before the first frame update
    void Start()
    {
      //some code
    }
}


text:
Q: Kotlin "Destructuring declaration initializer of type String must have a 'component1()' function" This is how I am calling the function :-
val (ImageUrl: String) = uploadImage("ImageTitle", imageTitleUri!!)

This is the function code:-
private fun uploadImage(ImageName: String, ImageUri: Uri): String {
        val fileRef = storagePicRef!!.child("$ImageName.jpg")
        val uploadTask: StorageTask<*>
        uploadTask = fileRef.putFile(ImageUri)

        var imageURL = ""

        uploadTask.continueWithTask(com.google.android.gms.tasks.Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }
            return@Continuation fileRef.downloadUrl
        }).addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val downloadUrl = task.result
                imageURL = downloadUrl.toString()
            }
            Toast.makeText(baseContext, "Uploaded successfully.", Toast.LENGTH_SHORT).show()
        }
        return imageURL
    }

This is how I am trying to get the Image Url. But I am getting this error:-
"Destructuring declaration initializer of type String must have a 'component1()' function"

I saw other similar questions but here the return value is only one of type string. So, I can directly use it.

A: delete those parenthesis (ImageUrl: String) and it will work fine,
So your function call should look like this:
val ImageUrl: String = uploadImage("ImageTitle", imageTitleUri!!)

Also it's recommended to start a variable with a lowercase letter so name it imageUrl instead of ImageUrl.


text:
Q: Why we can't do List mylist = ArrayList(); Why we can't do
List<Parent> mylist = ArrayList<child>();

A: Because they're not the same type. Suppose you had another child class of Parent (Child2 for the sake of argument), it would then be possible to put an instance of Child2 into a List<Parent>, but type-incorrect to put it into an instance of List<Child>. Covariant inheritance is a real headache, and is only supported at all in Java for array types (where it can cause odd problems).

A: Suppose we could. Then this program would have to be fine:
ArrayList<Banana> bananas = new ArrayList<Banana>();
List<Fruit> fruit = bananas;
fruit.add(new Apple());

Banana banana = bananas.get(0);

That's clearly not type safe - you've ended up with an apple in the collection of bananas.
What you can do is:
List<? extends Fruit> fruit = new ArrayList<Banana>();

this is safe, because the compiler won't then let you try to add to the list of fruit. It knows that it's a list of some kind of fruit, so you could write:
Fruit firstFruit = fruit.get(0);

but it doesn't know what exact kind of fruit it's a list of, and make sure you can't do the wrong thing.
See the Java generics FAQ another explanation.

A: It should be this way, because we can do:
Parent A = new Child();
Edit :   Wait, actually it works :

     List<Parent> list = new ArrayList<Parent>();
     List<ChildA> tmp = new ArrayList<ChildA>();
     list.addAll(tmp);
     List<ChildB> tmp2 = new ArrayList<ChildB>();
     list.addAll(tmp2);

It's just that the direct cast is not supported.


text:
Q: Using Student Distribution to obtain the Gaussian Distribution From the Student distribution:
$$\rho(x) = \frac{1}{\sqrt{N\pi}} \frac{\Gamma\big(\frac{N+1}{2} \big)}{\Gamma\big(\frac{N}{2} \big)} \bigg(1+ \frac{x^{2}}{N} \bigg)^{-(N+1)/2} $$
it's possible to obtain the Gaussian distribution by doing $N \rightarrow \infty $.
I did the limit by separating it in two functions:
$$ \lim_{N \rightarrow \infty} g(N)f(N) = \lim_{N \rightarrow \infty} g(N)\lim_{N \rightarrow \infty} f(N) $$
where:
$$ g(N) = \frac{1}{\sqrt{N\pi}} \frac{\Gamma\big(\frac{N+1}{2} \big)}{\Gamma\big(\frac{N}{2} \big)} $$
and
$$ f(N) = \bigg(1+ \frac{x^{2}}{N} \bigg)^{-(N+1)/2} $$
I know they exist, so this action holds. The $f(N)$ limit is equal to:
$$ \lim_{N \rightarrow \infty} \bigg(1+ \frac{x^{2}}{N} \bigg)^{-(N+1)/2} = e^{-x^{2}/2} $$
but, the $g(N)$ limit is where I get stuck on:
$$ \lim_{N \rightarrow \infty} \frac{1}{\sqrt{N\pi}} \frac{\Gamma\big(\frac{N+1}{2} \big)}{\Gamma\big(\frac{N}{2} \big)} $$
This limit is one of the type $\frac{\infty}{\infty}$. I know that the gamma function has derivatives involving the polygamma function, like:
$$ \Gamma'(z) = \Gamma(z)\psi^{(0)}(z) $$
where,
$$ \psi^{(m)}(z) = \frac{d^{m+1}}{dz^{m+1}} \ln \Gamma(z) $$
or, more generally,
$$ \frac{d^{m}}{dz^{m}} \Gamma(z) = \int_{0}^{\infty} t^{z-1}e^{-t}(\ln t)^{m} dt,$$
where, $R(z) > 0$.
So, there are anyway of going forward?
Or maybe, anyone knows a better path?

A: @StubbornAtom gave you the proper links.
When you face ratio's of gamma functions or factorials, the trick is to take the logarithms and use Stirling approximation of $\log(\Gamma(p))$. Apply it (as many times as required) replacing $p$ by the proper argument, continue with Taylor series and exponentiate it using Taylor series again. I shall let you doing it since it is a good exercise you will practice very often.
If I may add a comment, what you did separating the functions to get the limit is very correct but you just end with the limit (!!).
You could have obtained a bit more of information working with the whole problem.
$$\rho(x) = \frac{1}{\sqrt{N\pi}} \frac{\Gamma\big(\frac{N+1}{2} \big)}{\Gamma\big(\frac{N}{2} \big)} \bigg(1+ \frac{x^{2}}{N} \bigg)^{-(N+1)/2}$$
$$\log(\rho(x))=-\frac 12 \log(N)-\frac 12 \log(\pi)+\log\left(\Gamma\big(\frac{N+1}{2} \big)\right)-\log\left(\Gamma\big(\frac{N}{2} \big)\right)-\frac{N+1}2 \log\left(1+ \frac{x^{2}}{N}\right)$$ Do what I did suggest and you will end with
$$\rho(x)=\frac{e^{-\frac{x^2}{2}}}{\sqrt{2 \pi }}\left(1+\frac{x^4-2 x^2-1}{4 N}+O\left(\frac{1}{N^2}\right)\right)$$ which gives an idea about the deviation from the gaussian.


text:
Q: Check parameter name, not value, in JavaScript I am trying to place if statements inside of a function with conditions based on the NAME of the parameter used in the function, not the value.
What conditions can be used to achieve this? Is it possible? If not, is there and alternative?
For example:
var lorem="The name is Lorem, but the value isn't.";
var ipsum="The name is Ipsum, but the value isn't.";
//the values shouldn't matter

logIt(Lorem);

function LogIt(theName){
    if(**the name of the variable theName = "lorem"**){
    console.log("The variable 'lorem' was used.");
  }else if(**the name of the variable theName = "ipsome"**){
    console.log("The variable 'ipsum' was used.");
  }else{
    console.log("huh?");
  }
}

A: I believe it's not really possible to get the name of the variable in the general case, since argument values are copied to function parameters.
That said, if you only have a fixed set of variable names and you are using ES6, you could technically "hack" around the problem with object destructuring:
var lorem="The name is Lorem, but the value isn't.";
var ipsum="The name is Ipsum, but the value isn't.";

Logit({lorem})

function Logit({lorem, ipsum}) {
   if(lorem) console.log("Function called with lorem");
   else if(ipsum) console.log("Function called with ipsum");
   else console.log("Function called with something else");
}


text:
Q: windows server backup using powershell

I want to test backups after completion by confirming that I can recover a sentinel file.
We all know that a frequent backup, and later storage, copy in a different environment provides extra security.  For that purpose, our backup storage server, named Vault, keeps multiple extra copies of our daily backups.
Testing sample code:
$Backup  = '\\localhost\d$\Vault\One'
$ex      =""
try{
    # I have no clue how to get the servers from Get-WBBackupSet, so, resort to parsing the error
    # Get-WBBackupSet error response when multiple backups are stored:
    #Backups of multiple computers are in the backup storage location. The computers for which backups are present are:
    #bdc iis myblue quickbooks sqlserver <redacted> .
    #Please specify the computer that you want to manage backups for.

    $servers=@{}
    Get-WBBackupSet -BackupTarget $BackupTarget
  } catch {
    $m=($_ -split "`r`n")[0]
    $ix=$m.IndexOf(":")
    $l=$m.Substring($ix+1)
    $ix=$l.IndexOf(" . ")
    $Servers=$($l.Substring(0,$ix).split(" "))|? {$_ -ne ''} }

    $servers | %{
      $BackupSet = Get-WBBackupSet -BackupTarget $BackupTarget -MachineName $_
      Write-host "  $("$_".PadRight(12))$($($BackupSet.BackupTime).ToString("yyyy-MM-dd hh:mm tt ddd"))"
      $BackupSet.Volume | ? { $_.MountPath -ne '' } | % {
        $V=$_
        Write-Host $($v.VolumeLabel.PadRight(12)) $($v.MountPath.PadRight(6)) " `
          "$(($_.FreeSpace/1GB).tostring("n2").PadLeft(8))Gb  $(($_.TotalSpace/1GB).ToString("n2").PadLeft(8))Gb "

        Get-WBBackupVolumeBrowsePath   -VolumeInBackup $_ -BackupSet $BackupSet
      }
  }

I can't get Get-WBBackupVolumeBrowsePath to work to recover a well-known sentinel file stored on each volume:
"\\localhost\d$\Vault\One"
  admin        2020-03-13 07:00 PM Fri
                  C:         21.38GB     59.46GB

Get-WBBackupVolumeBrowsePath : an attempt to retrieve the properties for the backup set
                               failed because the backup set is not in the catalog.

at "C:\Repos\PowerShell\BackupStatus.ps1":... char:13
+             Get-WBBackupVolumeBrowsePath   -VolumeInBackup $_ -Backup ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-WBBackupVolumeBrowsePath], Exception
    + FullyQualifiedErrorId : System.Exception,Microsoft.Windows.ServerBackup.Commands.GetWBBackupVolumeBrowsePath

Where or how to reference a catalog? Using WBbackup, I can open and retrieve a single file from Vault, but I have about 25 servers' backups to check!!!

A: Get-BackupSet by itself will return all backup sets in your system catalog. You should be able to use any of those, but Get-WBBackupVolumeBrowsePath seems to require a backup set to be in your system catalog (and not another path) to be able to mount it interactively which it's doing in the background.
You can restore a file directly without a WBBackupVolumeBrowsePath though, and check the restore for errors:
Start-WBFileRecovery -BackupSet $BackupSet -FilePathToRecover "C:\Dir1" -Recursive -FileRecoveryOption CreateCopyIfExists -Force


text:
Q: Ajax liaded links wont open in shadowbox(lightbox) Well, I have figured something out... but I still need a litle help. btw. sorry for making a new post.
This is the oryginal shadowbox code:
<script type="text/javascript">
Shadowbox.init({
                // skip the automatic setup again, we do this later manually
                skipSetup: true
            });

            window.onload = function () {

                // set up all anchor elements with a "test" class to work with Shadowbox
                Shadowbox.setup("a.shadowbox", {
        player:     "html",
        title:      "Welcome"
                });

            };
</script>

And the script that should help me to make it work with ajax loaded links was this:
$('.shadowbox').live('click', function() {
                Shadowbox.open(this);
                return false;
});

But it wasnt helping, so I made this:
$('.shadowbox').live('click', function() {
        Shadowbox.setup("a.shadowbox", {
        player:     "html",
        title:      "Welcome"
                });
                Shadowbox.open(this);
                return false;
});

And now it's working but I think this line:
Shadowbox.open(this);

is no more needed there anyways when I delete it, the script works but it need 2 clicks on the link to start, anyone can help me how to optymalize it?
Greetings.

A: $('.shadowbox').live('click', function() {
        Shadowbox.setup("a.shadowbox", {
        player:     "swf"
             });
        Shadowbox.open(this);
        return false;
});
Thank you Michail the above code working for me when the page loading in ajax.I have display YouTube video in popup window by using Shadowbox Media Viewer plugin and above code in joomla.


text:
Q: What does strcmp return if two similar strings are of different lengths? I understand that if you have 'cat' (string1) and 'dog' (string2) in strcmp (this is a C question) then the return value of strcmp would be less than 0 (since 'cat' is lexically less than 'dog').
However, I am not sure what would happen with strcmp if this happened:
string1: 'dog'
string2: 'dog2'.

What would strcmp return? Less than zero, zero, or greater than? For context, I am trying to write a comparator function that compares strings and would like to account for strings starting with the same characters. One string may have an extension (such as '2' in 'dog2' in the example above).
EDIT: This is not a duplicate question. The question that this is allegedly similar to asks what the return type represents - I am saying what happens when the strings are identical up to a point but then one of them stops whilst the other continues.

A: It is defined in the C standard as the difference between the first two non matching characters, but the implementation is wild. The only common point is that the return value is zero for equal strings, then respectively <0 or >0 for str1<str2 and str1>str2.
From ISO/IEC 9899:201x, §7.23.4 Comparison functions:

The sign of a nonzero value returned by the comparison functions
  memcmp, strcmp, and strncmp is determined by the sign of the
  difference between the values of the first pair of characters (both
  interpreted as unsigned char) that differ in the objects being
  compared.

But some implementations take care to return typical values as 0, 1 and -1. See i.e. the Apple implementation (http://opensource.apple.com//source/Libc/Libc-262/ppc/gen/strcmp.c):
int
strcmp(const char *s1, const char *s2)
{
    for ( ; *s1 == *s2; s1++, s2++)
    if (*s1 == '\0')
        return 0;
    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}

EDIT:
In the Android boot library for Donut-release (https://android.googlesource.com/platform/bootable/bootloader/legacy/+/donut-release/libc/strcmp.c) the function returns 0 if strings are equal and 1 for the other 2 cases, and are used only logical operations:
int strcmp(const char *a, const char *b)
{
    while(*a && *b) {
        if(*a++ != *b++) return 1;
    }
    if(*a || *b) return 1;
    return 0;
}

A: C11 quotes
C11 N1570 standard draft
I think "dog" < "dog2" is guaranteed by the following quotes:

7.23.4 Comparison functions
  1
  The sign of a nonzero value returned by the comparison functions memcmp, strcmp,
  and strncmp is determined by the sign of the difference between the values of the first
  pair of characters (both interpreted as unsigned char) that differ in the objects being
  compared.

So the chars are interpreted as numbers, and '\0' is guaranteed to be 0:
Then:

7.23.4.2 The strcmp function
  2
  The strcmp function compares the string pointed to by s1 to the string pointed to by
  s2.

says that, obviously, strings are compared, and:

7.1.1 Definitions of terms
  1 A string is a contiguous sequence of characters terminated by and including the first null
  character.

says that the null is part of the string.
Finally:

5.2.1 Character sets
  2 [...] A byte with
  all bits set to 0, called the null character, shall exist in the basic execution character set; it
  is used to terminate a character string.

so '\0' is equal to zero.
Since the interpretation is as unsigned char, and all chars are different, zero is the smallest possible number.

A: It returns the difference at the octet that differs. In your example '\0' < '2' so something negative is returned.

A: From man strcmp:

The strcmp() and strncmp() functions return an integer less than,
  equal to, or greater than zero if s1 (or the first n bytes thereof) is
  found, respectively, to be less than, to match, or be greater than s2.

This would normally be implemented like @hroptatyr describes.

A: If you want to compare just the initial len characters of two strings, use strncmp instead of strcmp:
#include <string.h>
size_t len = 3;
int res = strncmp("dog", "dog2", len);

res will be 0 in this case.


text:
Q: SchemaRDD (Hive Table Scan) not cached by Spark-Shell I'm trying to run some basic data exploration using Spark on a Hive table (hosted on CFS via DataStax 4.6). My dataset is about 3.1GO and I run the spark-shell with dse spark --executor-memory 16g (Yes I do have 16g available on my executors). So basically I would write into the spark-shell, the following:
val dataset = hc.sql("SELECT * FROM my_hive_table") ;
val data_sample = dataset.sample(false,.01,0) ;
data_sample.cache

and then I would try a count to actually cache something
data_sample.count

but when I check on the spark-shell web UI I see no RDD persisted and if I try a count again my whole dataset is read again from CFS.
So I tried accessing my dataset though CFS directly as a textfile as such
textFile.type = cfs:/user/hive/warehouse/my_hive_table/aaaammjj=20150526

and adapt the previous code to count the number of line after caching the RDD and this time the RDD is indeed cached using 7 GB across two workers ! From the web UI :

cfs:/user/hive/warehouse/my_hive_table/aaaammjj=20150526  Memory Deserialized 1x Replicated

Is there any reason why my schemaRDD is not cached using Hive ? That would be much pratical since schemaRDD provide ... well the schema.
Thx for any help.

A: So based on my discussion with eliasah, I could eventually cache the table somehow with :
val dataset = hc.sql("SELECT * FROM autori_daily_import")
dataset.registerTempTable("data")
hc.cacheTable("data")
hc.sql("select count(*) from data")
res22: Array[org.apache.spark.sql.Row] = Array([6409331])
hc.sql("select sens,count(*) from data group by sens").collect().foreach(println)
[A,3672249]
[E,2737082]

And there is indeed a RDD in cache with name "RDD Storage Info for HiveTableScan ..."
What is a litle fuzzy to me is why I need to register a temporary table when I have a schemaRDD for which I have a .cache() method. If I run queries against the schemaRDD (with .select('sens).countByValue() ) then Spark scan the Hive table again and don't use the temporary in-memory table.

A: According to the official documentation of Spark 1.2, Spark SQL can cache tables using an in-memory columnar format by calling sqlContext.cacheTable("tableName").
Then Spark SQL will scan only required columns and will automatically tune compression to minimize memory usage and GC pressure. You can call sqlContext.uncacheTable("tableName") to remove the table from memory.
Note that if you call schemaRDD.cache() rather than sqlContext.cacheTable(...), tables will not be cached using the in-memory columnar format, and therefore sqlContext.cacheTable(...) is strongly recommended for this use case.
Configuration of in-memory caching can be done using the setConf method on SQLContext or by running SET key=value commands using SQL.
So actually you'll need to cache your data_sample RDD using sqlContext.cacheTable("the name of the table you gave for your table")


text:
Q: Infinitive instead of gerund, specifically after 'require' I use Grammarly Chrome extension to validate my texts in English. And with some sentences I keep seeing the error message "Infinitive instead of gerund". I'm not sure if this is an appropriate error message, and whether I should I adopt the suggested correction or not.
Example:

The initial installation requires to have a certain expertise.

Correction suggested by Grammarly:

Initial installation requires having a certain expertise.

For some reason, I don't like how the suggestion sounds. And I think I met with a similar use of an infinitive used after a verb before.

A: Both gerunds and infinitives can be used as the subject or the complement of a sentence. However, as subjects or complements, gerunds usually sound more like normal, spoken English, whereas infinitives sound more abstract. In the following sentences, gerunds sound more natural and would be more common in everyday English. Infinitives emphasize the possibility or potential for something and sound more philosophical. If this sounds confusing, just remember that 90% of the time, you will use a gerund as the subject or complement of a sentence.
Examples:
•Learning is important. normal subject
•To learn is important. abstract subject - less common
•The most important thing is learning. normal complement
•The most important thing is to learn. abstract complement - less common


text:
Q: Why waiting for rendering thread to finish in SurfaceView is usually guarded against interrupts? I've seen a couple of times the following pattern people use when working with SurfaceView:
while(true) {
    try {
        renderThread.join();
        break;
    } catch (InterruptedException e) {
        // retry
    }
}

For example, here or here. Why do that? Especially given that nothing is actually interrupting the thread.


text:
Q: 404 on FacesServlet causes infinite loop with java.lang.NullPointerException at org.apache.myfaces.shared_impl.context.flash.FlashImpl.isKeepMessages In WebSphere 8.5, accessing /myapp, /myapp/, /myapp/nosuchpage and /myapp/faces/nosuchpage will procude a 404, which is fine. But /myapp/faces and /myapp/faces/ causes instead of 404 an infinite loop with a NPE on MyFaces Flash scope as seen in the log.
[3/6/15 16:58:03:391 CST] 000000f7 SystemOut     O [PhaseListener:beforePhase] phase=RESTORE_VIEW(1)
[3/6/15 16:58:03:391 CST] 000000f7 SystemOut     O [PhaseListener:beforePhase] phase=RENDER_RESPONSE(6)
[3/6/15 16:58:03:391 CST] 000000f7 SystemOut     O [PhaseListener:beforePhase] fc.viewRoot.viewId=/faces/ fc.application.viewHandler.actionURL=/jsfTest2/faces//faces/
... (repeats)
[3/6/15 16:58:03:392 CST] 000000f7 SystemOut     O [PhaseListener:beforePhase] phase=RESTORE_VIEW(1)
[3/6/15 16:58:03:392 CST] 000000f7 SystemOut     O [PhaseListener:beforePhase] phase=RENDER_RESPONSE(6)
[3/6/15 16:58:03:392 CST] 000000f7 SystemOut     O [PhaseListener:beforePhase] fc.viewRoot.viewId=/faces/ fc.application.viewHandler.actionURL=/jsfTest2/faces//faces/
[3/6/15 16:58:03:405 CST] 000000f7 ErrorPageWrit E   An exception occurred
                                 java.lang.NullPointerException
    at org.apache.myfaces.lifecycle.PhaseListenerManager.informPhaseListenersAfter(PhaseListenerManager.java:107)
    at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:186)
    at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:119)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:189)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1111)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:194)
    at org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:367)
    at org.apache.myfaces.view.jsp.JspViewDeclarationLanguage.buildView(JspViewDeclarationLanguage.java:94)
    at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:66)
    at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:240)
    ... (repeats)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1111)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3901)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:981)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1865)

[3/6/15 16:58:03:429 CST] 000000f7 ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: An exception was thrown by one of the service methods of the servlet [Faces Servlet] in application [jsfTest2EAR]. Exception created : [java.lang.NullPointerException
    at org.apache.myfaces.shared_impl.context.flash.FlashImpl.isKeepMessages(FlashImpl.java:394)
    at org.apache.myfaces.shared_impl.context.flash.FlashImpl._saveMessages(FlashImpl.java:669)
    at org.apache.myfaces.shared_impl.context.flash.FlashImpl.doPostPhaseActions(FlashImpl.java:275)
    at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:252)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1111)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1385)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:194)
    at org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:367)
    at org.apache.myfaces.view.jsp.JspViewDeclarationLanguage.buildView(JspViewDeclarationLanguage.java:94)
    at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:66)
    at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:240)
    ... (repeats)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:191)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1230)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:779)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:478)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1111)
    at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3901)
    at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:981)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1865)
]
[3/6/15 16:58:03:442 CST] 000000f7 LocalTranCoor E   WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
... (repeats)
[3/6/15 16:58:04:523 CST] 000000f7 SRTServletRes W com.ibm.ws.webcontainer.srt.SRTServletResponse setStatus WARNING: Cannot set status. Response already committed.
[3/6/15 16:58:04:523 CST] 000000f7 SRTServletRes W com.ibm.ws.webcontainer.srt.SRTServletResponse addHeader SRVE8094W: WARNING: Cannot set header. Response already committed.

Adding <error-page> for 404 does not help. No such looping is observed in WebSphere 6.1. Perhaps a bug in MyFaces bundled in WebSphere 8.5?
This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

    <display-name>jsfTest2</display-name>

    <context-param>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>server</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value></param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>com.ibm.ws.jsf.JSP_UPDATE_CHECK</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>com.ibm.ws.jsf.LOAD_FACES_CONFIG_AT_STARTUP</param-name>
        <param-value>true</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>-1</load-on-startup>
        <enabled>true</enabled>
        <async-supported>false</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>


text:
Q: xetex fontspec error ubuntu I'm using a custom style (not made by me) for a report and when I compile it using PdfLatex it works fine. However, when I want to use the house style fonts I have to compile it with XeLatex and I get an error:
! fontspec error: "font-not-found"
!
! The font "BookmanOldStyle" cannot be found.

(I get this error for multiple font styles but I won't include them here for brevity)
I've looked at similar questions but none of the answers have been able to help me or steer me in the right direction.
A MWE:
\documentclass[print]{tudelft-report}

\begin{document}

\chapter{Font test}
House style

\end{document}

! Note that you need this custom style! (see line 61)

A: This is because different fonts are used when compiling using PDFLaTeX or XeLaTeX. Quoting from the style definition file:

\ifxetex
    %% If the document is compiled with XeLaTeX, we load the TU Delft house
    %% style fonts: Bookman Old Style (serif) for titles and Tahoma (sans-serif)
    %% for text. Even if the nativefonts option was specified, we need these
    %% fonts for the cover.
    \newfontfamily\tudrmfamily[
        Path = fonts/,
        Extension = .ttf,
        BoldFont = *-Bold,
        ItalicFont = *-Italic,
        BoldItalicFont = *-BoldItalic
    ]{BookmanOldStyle}
    \newfontfamily\tudsffamily[
        Path = fonts/,
        Extension = .ttf,
        BoldFont = *-Bold,
        ItalicFont = *,
        ItalicFeatures = FakeSlant,
        BoldItalicFont = *-Bold,
        BoldItalicFeatures = FakeSlant
    ]{Tahoma} \else
    %% If the document is not compiled with XeLaTeX, we need to use the native
    %% fonts.
    \@nativefontstrue
    \newcommand*\tudrmfamily{\rmfamily}
    \newcommand*\tudsffamily{\sffamily} \fi

The error you get suggests the specified font is not installed on your system. A casual Google search hints that you might be able to download it, e.g. from http://fontzone.net/font-details/bookman-old-style . Additionally, fonts are provided in the subfolder of the one you linked: https://github.com/praseodym/tudelft-report-latex


text:
Q: How to show Arabic style in Google charts <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ar_PieChart.aspx.cs" Inherits="Ar_PieChart" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <meta http-equiv='content-type' content='text/html; charset=UTF-16' />
    <meta name="viewport" content="width=device-height,minimum-scale=0.5,maximum-scale=3.0,user-scalable=yes" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load('visualization', '1', { packages: ['corechart'] });
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                url: 'Ar_PieChart.aspx/GetData',
                data: '{}',
                success:
                    function (response) {
                        drawVisualization(response.d);
                    }
            });
        })
        function drawVisualization(dataValues) {
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Column Name');
            data.addColumn('number', 'Column Value');
            for (var i = 0; i < dataValues.length; i++) {
                data.addRow([dataValues[i].ColumnName, dataValues[i].Value]);
            }
            new google.visualization.PieChart(document.getElementById('visualization')).draw(data, { is3D: true });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="visualization" style="width: 600px; height: 350px">

    </div>
    </form>
</body>
</html>

Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using MySql.Data.MySqlClient;

public partial class Ar_PieChart : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static List<Data> GetData()
    {
        MySqlConnection conn = new MySqlConnection("server=****;user id=****;Password=****;database=****");
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        conn.Open();
        string cmdstr = "SELECT Class,COUNT(Class) FROM sh_report GROUP BY Class";
        MySqlCommand cmd = new MySqlCommand(cmdstr, conn);
        MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
        adp.Fill(ds);
        dt = ds.Tables[0];
        List<Data> dataList = new List<Data>();
        string cat = "";
        int val = 0;
        foreach (DataRow dr in dt.Rows)
        {
            cat = dr[0].ToString();
            val = Convert.ToInt32(dr[1]);
            dataList.Add(new Data(cat, val));
        }
        return dataList;
    }
}
public class Data
{
    public string ColumnName = "";
    public int Value = 0;
    public Data(string columnName, int value)
    {
        ColumnName = columnName;
        Value = value;
    }
}

I am getting chart perfectly but i am in need of Arabic style like reverse.
 i mean while seeing the chart view in mirror.
 If any one know the answer please help me.
Thanks in advance.


text:
Q: how to automount a virtualbox shared folder on a guest OS with specific options? virtualbox by default mounts shared folders as user root, group vboxsf, and 770 permissions on everything.
I would like to mount with specific options, namely
sudo mount -t vboxsf myshare /media/sf_myshare/ -o rw,uid=501,gid=20

I can manually unmount the automounted share and run the above command, but I'd like these options applied automatically.   I can't find any file in /etc/ that controls the vbox share mount settings

A: This looks to be controlled by the vbsvcAutoMountWorker as defined by VBoxServiceAutoMount.cpp, and the mount log indicates that the vbsvcAutoMountSharedFolder function is involved, which is called by something that manually sets the group to vboxsf. Changing this appears to require changing the code and recompiling, or to request a feature that the options be settable via a "guestproperty" or "extradata" or some other means...


text:
Q: Java get the default proxy Is there a way to get the "behind-the-scenes" proxy in Java? The one specified with http.proxyHost and http.proxyPort.
If I do:
URL url = new URL("http://google.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

It automatically connects through the values set above. I can also specify a Proxy (HttpURLConnection con = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);). But how can I specify the default proxy?
For example, I have a method and want to open a connection with the "default proxy" (which does the same thing as Proxy.NO_PROXY if http.proxyHost and http.proxyPort aren't set)? I could use
(HttpURLConnection) ((proxy == null) ? url.openConnection() : url.openConnection(proxy))

but is there away to do
(HttpURLConnection) url.openConnection(proxy == null ? [the default proxy] : proxy)

I tried getting the default proxy with
public static Proxy getCurrentHTTPProxy(Proxy defaultProxy) {
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (proxyHost == null || proxyPort == null) {
        return defaultProxy;
    }
    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)));
}

But I still need to make a special case and check for https proxy settings. (if the URL is http, call getCurrentHTTPProxy, if the URL is https, call getCurrentHTTPSProxy). I also looked into ProxySelector (like here How to get default proxy settings in java program (not applet)?) but that seems too clumsy for something like this.
Lastly, I tried looking into openjdk's implementation, which seems to open a connection with the default proxy if the passed parameter is null, but when I tried it on the Sun JVM and that gives a NullPointerException.