text:
Q: Compare 2 nested arrays to return duplicate arrays I have the following code that doesn't work with nested arrays (it works with simple arrays, though):
var array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
var array2 = [["501", 1800, "floorsRegion1", 0]];

var duplicatesArray = array1.filter(function(val) {
  return array2.indexOf(val) !== -1;
});
console.log(duplicatesArray); // should return [["501", 1800, "floorsRegion1", 0]]; but it doesn't currently

If instead of nested arrays, I had simple numbers or strings, it would work and 'duplicatesArray' would contain the dupes.  But JS doesn't compare the whole arrays as values, so my code doesn't work.
Only the val[0] is essential to compare in those nested arrays, but result array must contain the whole nested arrays for duplicates.
I found several similar solutions, but they remove the dupes instead of returning an array with those dupes.

A: If you only care about the item at index 0, then you can filter using some and check id some item in array2 it's first value equals the first value of the current item being filters:

var array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
var array2 = [["501", 1800, "floorsRegion1", 0]];

let filtered = array1.filter(arr => array2.some(arr2 => arr2[0] == arr[0]))
console.log(filtered)

// with two items in array2:

array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
array2 = [["501", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];

filtered = array1.filter(arr => array2.some(arr2 => arr2[0] == arr[0]))
console.log(filtered)

This isn't very efficient because it looks thought array2 for every item in array1. If the arrays were large it would be worth making a lookup with an object or Set that allows quicker lookups. Something like:

var array1 = [["501", 1800, "floorsRegion1", 0], ["502", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];
var array2 = [["501", 1800, "floorsRegion1", 0], ["503", 1800, "floorsRegion1", 0]];

let known = new Set(array2.map(item => item[0]))

let filtered = array1.filter(arr => known.has(arr[0]))
console.log(filtered)


text:
Q: curl post request jquery equivalent I want to use echoprint - http://echoprint.me/start - to send an mp3 file locally from my computer in a post request in order to retrieve this song's details from their server. I am trying to write this post request in jquery in my text editor to retrieve a json object with the song details so I can view this in my browser's console, and then use the data from there. Their website explains how to make this post request by using curl for which the following code works in the command line. This returns a json object, however this is in the terminal so isn't much use to me as far as I know.
curl -F "api_key=################" -F "filetype=mp3" -F "track=@audio.mp3" "http://developer.echonest.com/api/v4/track/upload"

I want to make this request using jquery in my text editor so I can make the same request and retrieve the json data in the browser's console.
I have tried this code but unfortunately it doesn't work
   $.post("http://developer.echonest.com/api/v4/track/upload?api_key=############&url=http://tylergrund.com/mp3/MP3s%20from%20home/Coldplay/01%20Speed%20Of%20Sound.mp3" )
  .done(function( data ) {
    console.log( data );
  });

Can anyone provide the appropriate code. There are instructions here http://developer.echonest.com/docs/v4/track.html but they only explain how to do this using curl. Any help would be greatly appreciated. I am a beginner to this so please go easy.

A: You need to POST the parameters instead of adding them to the URL causing a GET request:
$.post("http://developer.echonest.com/api/v4/track/upload", {
          "api_key":"############",
          "url":"http://tylergrund.com/mp3/MP3s%20from%20home/Coldplay/01%20Speed%20Of%20Sound.mp3"
      },
      function( data ) {
                console.log( data );
      },
      "JSON" );

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to have your delimiter double and single, too In my custom Notepad++ user-defined language (UDL) for AutoHotkey, I am trying to fix an issue where the colours for variables don't display correctly.
In the UDL configurator, I have, under Operators & Delimiters, specified Delimiter 1 Style for
Open: %
Escape:
Close: %

But I need to fix it so that if there is a % followed by a space that the colouring for Delimiter 1 is not continued to the next line.
How can I do that?

A: Here is the solution:
In the UDL documentation it says you can use a special code within the styler options to indicate either / or.
Thus, for your variable delimiter for the % sign, you want to do this:
open:  %
escape:
close: ((% EOL))

This will provide you with proper colouring in both situations.
Here is what it looks like in the UDL file:
<Keywords name="Delimiters">00% 01 02((% EOL)) 03" 04 05" 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23</Keywords>

Here is my new AutoHotkey syntax file with working % variable markers.

A: I had the same problem some months ago. Well, I was able to fix it by downloading a different syntax highlighting file.
Mine is probably not up-to-date any more, but it works pretty good and the most important things are highlighted so check it out: ...\Notepad++\plugins\APIs\Autohotkey.xml.
<?xml version="1.0" encoding="windows-1252"?>
<NotepadPlus>
    <AutoComplete language="AutoHotkey">
        <Environment ignoreCase="yes" startFunc="(" stopFunc=")" paramSeparator="," terminal="" additionalWordChar="#{@"/>
        <KeyWord name="Abort"/>
        <KeyWord name="AboveNormal"/>
.
.
.

Maybe you need it as well, but I'm not sure: ...\Notepad++\ahk_userDefineLang.xml
However, if you find a more updated file, tell me. :)


text:
Q: template function taking cv::Point_ as parameter won't compile I'm trying to write a generic function to serialize to string a std::vector<cv::Point_<T>> and I want this to work for both cv::Point2i and cv::Point2f (both are typedefs of cv::Point_<T> with a specific T).
The function looks like this:
template<typename T>
int SVIniFile::write(const std::string& section,
                     const std::string& key,
                     std::vector<cv::Point_<T>>& points)
{
    std::ostringstream os;
    if (points.empty())
    {
        return SUCCESS;
    }
    for (size_t j = 0; j < points.size(); j++)
    {
        os << points[j].x << " " << points[j].y;
        if (j < points.size() - 1)
        {
            os << " ";
        }
    }

    write(section, key, os.str()); // do the writing of os.str() in the right `section` at `key`

    return SUCCESS; // function that writes a string into an ini file
}

Trying to compile this throws an "Unrecognizable template declaration/definition" error. Investigating on the error (full compiler output is below), I found this question, which however doesn't seem related to my case, and this question, the answer of which I don't understand.
I'm very new to template programming and I suspect the error is caused by the fact that I'm using as template parameter the type that is itself a template parameter of one of the parameters. Could anyone point me in the right direction and possibly expand a bit on why the compiler can't build this?

This is what the compiler produces as error output in every file where my header is included:

1>svinifile.h(640): error C4430: missing type specifier - int assumed.
  Note: C++ does not support default-int 1>svinifile.h(640): error
  C2988: unrecognizable template declaration/definition
  1>svinifile.h(640): error C2143: syntax error: missing ',' before '&'

line 640 is the one right after the template<typename T> in the function definition I show above.

Just to be explicit, cv::Point_<T> i OpenCV's 2D point type defined in types.hpp as:
namespace cv
{
// ...
template<typename _Tp> class Point_
{
public:
    typedef _Tp value_type;

    //! default constructor
    Point_();
    Point_(_Tp _x, _Tp _y);
    Point_(const Point_& pt);
    Point_(Point_&& pt) CV_NOEXCEPT;
    Point_(const Size_<_Tp>& sz);
    Point_(const Vec<_Tp, 2>& v);

    Point_& operator = (const Point_& pt);
    Point_& operator = (Point_&& pt) CV_NOEXCEPT;
    //! conversion to another data type
    template<typename _Tp2> operator Point_<_Tp2>() const;

    //! conversion to the old-style C structures
    operator Vec<_Tp, 2>() const;

    //! dot product
    _Tp dot(const Point_& pt) const;
    //! dot product computed in double-precision arithmetics
    double ddot(const Point_& pt) const;
    //! cross-product
    double cross(const Point_& pt) const;
    //! checks whether the point is inside the specified rectangle
    bool inside(const Rect_<_Tp>& r) const;
    _Tp x; //!< x coordinate of the point
    _Tp y; //!< y coordinate of the point
};

typedef Point_<int> Point2i;
typedef Point_<int64> Point2l;
typedef Point_<float> Point2f;
typedef Point_<double> Point2d;
typedef Point2i Point;

}

A: Since there's nothing wrong with the code shown, the problem must be with some code you have not shown. It's probably something very simple, like a missing or out-of-order #include.
You should try to create a Minimal, Complete, and Verifiable example. You'll likely find the problem while doing it.
For example, this compiles just fine on VS 2017:
#include <vector>

namespace cv {
    template<typename _Tp> class Point_ {};
    typedef Point_<int> Point2i;
}

class SVIniFile {
public:
    template<typename T>
    int write(
        const std::string& section,
        const std::string& key,
        std::vector<cv::Point_<T>>& points);
};

template<typename T>
int SVIniFile::write(
    const std::string& section,
    const std::string& key,
    std::vector<cv::Point_<T>>& points) {
    return 0;
}

int main() {
    SVIniFile svIniFile;
    std::vector<cv::Point2i> points;
    svIniFile.write("abc", "def", points);
    return 0;
}


text:
Q: Using column from main dataset as multi-value parameter in subreport Hi I am using SSRS 2008.
My set up is MainReport with dataset1 and 1 parameter - OrderID. One of the columns in dataset1 is ShippingID.
My other report  called - SubReport has 1 multivalue paramter - ShippingID.
I am trying to use ShippingID from Main report as multi-value parameter for Subreport.
I tried different threads here but mostly they are diffrent than my scenario.
How do I go about setting this up, is that even possible?
I have been trying to set it up for whole day but unsuccessfully.
In my scenario one Order can be on multiple shipments.
One of the things I tried is creating new multi-value parameter in MainReport - call it shippingIDs_sub and mapping its default value to dataset1.ShippingID. But when I try to run report I get error "The 'shippingIDs_sub' parameter is missing value" - because my MainReport would sometimes return NULL in ShippingID column.
My scenario is very much similar to this
SSRS passing parameter to subreport
although I sometimes get NULLs in the column used as source for multi-value parameter.
Is there any way to filter out NULLs and run subreport only for existing IDs?

A: In the Action where you call the sub-report, where you map to shippingIDs_sub, use an expression to pass some valid value whenever the value in your dataset is NULL.
=IIF(IsNothing(Fields!ShippingID.value),"Some Valid Value",Fields!ShippingID.value)

As to this:

Is there any way to filter out NULLs and run subreport only for
  existing IDs?

No, you can't turn off the ability to go to a subreport, but you can "hide" it by changing the appearance of whatever your user clicks on so that it doesn't look like it's clickable.   For example, in our reports, when something is clickable, we make it underlined in blue.   So if I don't want to user to click it, I just make it the same font color/style as all the other text.   But it doesn't stop a determined user from clicking on it anyway if they want.


text:
Q: Finding covariation between datasets For me this is a very fascinating problem, which I however lack the ability to deal with as well as the nomenclature to describe properly. (Please feel free to edit the title).
The conditions are the following:
I have three volumes of air in which I measure the concentration of a chemical compound.
So I have three sets of data: A, B and C, which describe the variation of the compound over time. The measurements are made synchronous with equal and constant time steps.
A is the outdoor air and is not influenced by neither B nor C.
B has its own unique variation due to some internal processes, but can to some extent be influenced by A.
C can be influenced by both A and B.
The big question is:
How can I determine which of A and B influence C and to what extent.
A complicating factor is that there is a phase shift, which may vary. It can even be the case that A and B effect C alternately or simultaneously.
I have picked up that some form of Fourier function may come in handy.
What functions and approach would be productive?


text:
Q: A question about orthogonal projections of Smooth Embeddings of the circle. Question: Let $f$ be a smooth embedding of $S^1\rightarrow \mathbb{R}^3$. Given an element $v\in S^2$ we have the orthogonal projection $\pi_v:\mathbb{R}^3\rightarrow P_v$ to the plane
$P_v$ = the orthogonal complement of v. Show that for almost every $v\in S^2$, we have that $f_v=\pi_v\circ f$ is an immersion.
I'm fairly sure the strategy here will be to show that if $v$ is a regular value of $f$, then $\pi_v$ is an immersion and has injective derivative. Since the derivative of $f$ was injective, so too will the derivative of the the composition map be injective. Then by Sard's theorem, almost every v works.
The problem is when I write out the conditions on the tangent spaces, I don't see any reason why this would be true. if $v$ is regular, then that means that $df_x$ is surjective if $f(x)=v$. Since it is an embedding, that means the derivative is bijective. The projection is a submersion and also has surjective derivative, but there is no reason to suspect that the composition of a bijection and a surjection would be injective. I fear I've fallen into a paralysis of thought, and am a bit stuck in this rut of unproductive thinking.
Will uprate - thanks!

A: The projection onto $P_v$ kills the component of the derivative that is parallel to $v$. Therefore,  the entire derivative $df$ will be killed if and only if
$$df=\lambda v \ \text{ for some } \ \lambda\in \mathbb R\tag1$$ We just have to choose $v$ so that (1) never happens.
To that end, rewrite (1) as
$\dfrac{df}{|df|}=v$ and observe that the map $F(x)=  \dfrac{df(x)}{|df(x)|}$ is a smooth map from the one-dimensional manifold $S^1$ to the two-dimensional manifold $S^2$. Its image has finite length, and therefore has zero area. Thus, we can choose $v\in S^2\setminus F(S^1)$, and this $v$ does what we want.


text:
Q: Excluir somente um registro no banco de dados Ao executar o código abaixo, mais de um registro é excluído do banco de dados. Não consigo encontrar o problema.
Codigo para excluir
excluir_cliente.php
<?php

require 'repositorio_clientes.php';

$clientes = $repositorio->getListarClientes();

echo"

";

while($clienteTemporario = array_shift($clientes)){

if($clienteTemporario->getCodigo() == $_REQUEST['codigo']){

echo '' . "Cliente: " . $clienteTemporario->getNome() . ", cpf: " . $clienteTemporario->getCpf() . $repositorio->excluirClientes($_REQUEST['codigo']) . "excluído com sucesso" . '';

}

}

exit;

?>

Página: repositorio_clientes.php
<? php

require ' conexao.php ';

include 'cliente.php';

interface IRepositorioClientes {

public function cadastrarClientes($cliente);

public function excluirClientes($cliente);

public function atualizarClientes($cliente);

public function buscarCliente($codigo);

public function getListarClientes();

public function getListarClienteDia();

public function getListarClienteAtraso();

}

class RepositorioClientesMySQL implements IRepositorioClientes {

private $conexao;

public function __construct() {

$this->conexao = new Conexao("localhost", "root", "", "biblioteca");

if($this->conexao->conectar() == false) {

echo "Erro" . mysqli_error();

}

}

public function cadastrarClientes($cliente) {

$nome = $cliente->getNome();

$endereco = $cliente->getEndereco();

$cpf = $cliente->getCpf();

$saldo = $cliente->getSaldo();

$situacao = $cliente->getSituacao();

$data= $cliente->getData();

$sql = "INSERT INTO cliente (nome, endereco, cpf, saldo, situacao, data) VALUES
('$nome', '$endereco', '$cpf', '$saldo', '$situacao', '$data')";

$this->conexao->executarQuery($sql);

}

public function excluirClientes($codigo) {

$sql = "DELETE FROM cliente WHERE codigo = '$codigo'";

$this->conexao->executarQuery($sql);

}

public function atualizarClientes($cliente) {

$nome = $cliente->getNome();

$codigo = $cliente->getCodigo();

$cpf = $cliente->getCpf();

$endereco = $cliente->getEndereco();

$saldo = $cliente->getSaldo();

$situacao = $cliente->getSituacao();

$data = $cliente->getData();

$linha = $this->conexao->obtemPrimeiroRegistroQuery;

$sql = "UPDATE cliente SET nome ='$nome', endereco='$endereco', cpf='$cpf', saldo='$saldo', situacao='$situacao', data='$data' WHERE codigo ='$codigo'";

$this->conexao->executarQuery($sql);

}

public function buscarCliente($codigo) {

$linha = $this->conexao->obtemPrimeiroRegistroQuery ("SELECT * FROM cliente WHERE codigo='$codigo'");

$cliente = new Cliente(

$linha['nome'],

$linha['codigo'],

$linha['endereco'],

$linha['cpf'],

$linha['saldo'],

$linha['situacao'],

$linha['data']);

return $cliente;

}

public function getListarClientes() {

$listagem = $this->conexao->executarQuery("SELECT * FROM cliente");

$arrayClientes = array();

while($linha = mysqli_fetch_array($listagem)){

    $cliente = new Cliente(

    $linha['nome'],

    $linha['codigo'],

    $linha['endereco'],

    $linha['cpf'],

    $linha['saldo'],

    $linha['situacao'],

    $linha['data']);

array_push($arrayClientes, $cliente);

}

return $arrayClientes;
}

public function getListarClienteDia() {

$listagem = $this->conexao->executarQuery("SELECT * FROM cliente WHERE situacao='Em Dia'");

$arrayClientes = array();

while($linha = mysqli_fetch_array($listagem)){

    $cliente = new Cliente(

    $linha['nome'],

    $linha['codigo'],

    $linha['endereco'],

    $linha['cpf'],

    $linha['saldo'],

    $linha['situacao'],

    $linha['data']);

array_push($arrayClientes, $cliente);

}

return $arrayClientes;

}

public function getListarClienteAtraso() {

$listagem = $this->conexao->executarQuery("SELECT * FROM cliente WHERE situacao='Em Atraso'");

$arrayClientes = array();

while($linha = mysqli_fetch_array($listagem)){

    $cliente = new Cliente(

    $linha['nome'],

    $linha['codigo'],

    $linha['endereco'],

    $linha['cpf'],

    $linha['saldo'],

    $linha['situacao'],

    $linha['data']);

array_push($arrayClientes, $cliente);

}

return $arrayClientes;

}

}

$repositorio = new RepositorioClientesMySQL();

?>

A: Se deseja apenas excluir um cliente informe o id/código não precisa de um while para isso.
Não é necessario usar php para verificar qual cliente da lista(array) da lista será removido, apenas passe o id para a função de deixe que o banco se encarregue dessa tarefa.
Pode simplificar:
while($clienteTemporario = array_shift($clientes)){
if($clienteTemporario->getCodigo() == $_REQUEST['codigo']){
   echo '' . "Cliente: " . $clienteTemporario->getNome() . ", cpf: " .
   $clienteTemporario->getCpf() . $repositorio->excluirClientes($_REQUEST['codigo']) .
   "excluído com sucesso" . '';
}

Para:
if ($repositorio->excluirClientes($_REQUEST['codigo'])) {
   echo 'cliente excluido com sucesso';
} else {
   echo 'erro';
}


text:
Q: New to docker, Not seeing local changes made on site I've been working on a site using laravel 5.8 which runs on a docker container and usually I've been able to save my local changes and the site on my local host reflects them but not my changes aren't seen on the site.
I'm running docker-compose up -d and it starts with the laravel driver, creating php and creating nginx but My local changes just won't show.
Should I be running a different command?
docker-compose file:

version: '3'

networks:
laravel:

services:
nginx:
    image: nginx:latest
    container_name: nginx
    ports:
        - "8080:80"
    volumes:
        - ./:/var/www
        - ./resources/docker/nginx:/etc/nginx/conf.d
    depends_on:
        - php
    networks:
        - laravel
php:
    image: quay.io/testRepo/docker-php-iaccess-odbc:7.3-devel
    container_name: php
    volumes:
        - ./:/var/www
    environment:
        - PHP_OPACHE_ENABLE=0
    ports:
        - "9000:9000"
    networks:
        - laravel

A: docker-compose volume mounting requires either a  full path or using the Version 3 bind configuration.
https://docs.docker.com/compose/compose-file/#volumes
In Linux/Unix OSes the pwd CLI command can be used as a short cut.


text:
Q: Excel adding rows to a table and automatically adding rows to another I have two excel tables on two separate sheets. Both tables have a ID column and a many more columns that have nothing similar between the two tables (IE the tables store different things entirely). I want to sync them up so that whenever I add rows to one of the tables, it automatically adds a row to the other table.
So far, all I can get is having the ID in one of the tables directly reference the ID in the other table, but upon adding a row, it 1) doesn't automatically add another row (I didn't expect it to work though), and more importantly, 2) the cell references break. By that, I mean that they no longer hold a 1:1 relationship, and upon adding a new row, there will be a row that isn't referenced at all, and a row that is reference twice.
I've tried paste-special with different links, but nothing else functions any better. Any thoughts? I'm not particularly keen on a VB solution, I'll only use it as my last resort. I'd much prefer some help making something native in Excel that 'just works'.


text:
Q: IE9: Force IE9 browser mode and document mode In IE9, my webpage is displaying as Browser Mode: IE9 Compat View and Document Mode: IE standards, which is breaking all my canvases.
I have made sure to have <!DOCTYPE html> as the very first line.
How can I force "normal" IE9 mode on IE9?

A: There is the "edge" mode.

      <title>My Web Page</title>
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />

Content goes here.

From the linked MSDN page:

Edge mode tells Windows Internet Explorer to display content in the
  highest mode available, which actually breaks the "lock-in" paradigm.
  With Internet Explorer 8, this is equivalent to IE8 mode. If a
  (hypothetical) future release of Internet Explorer supported a higher
  compatibility mode, pages set to Edge mode would appear in the highest
  mode supported by that version; however, those same pages would still
  appear in IE8 mode when viewed with Internet Explorer 8.

However, "edge" mode is not encouraged in production use:
It is recommended that Web developers restrict their use of Edge mode to test pages and other non-production uses because of the possible unexpected results of rendering page content in future versions of Windows Internet Explorer.

A: The following line, taken from HTML5 boilerplate, did the job:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">


text:
Q: Proving uniform continuity on [0, infinity) using episilon, delta, and M (formal proof) "Suppose that $f:[0,\infty) \to \mathbb R$ is continuous and that there is an $L$ in $\mathbb R$ such that $f(x)\to L$ as $x \to \infty$. Prove that $f$ is uniformly continuous on $[0, \infty)$."
 This is the proof my professor gave me to answer this question, but I don't understand what's going on after "if $|x-y| < \delta$" and the use of $M+1$, $M+2$. I believe $\delta$ has some relationship to the x values (as epsilon has some relationship to the y values); but is it true that for this reason we are moving up from M (which is used for infinity) so we add 1 when we are dealing with $x$ and add 2 when we are dealing with $y$?
I really appreciate any help and explanations. Thank you in advance!

A: It might help here to construct an incorrect proof, and then see why the above proof works :
For $\epsilon > 0$, there is $M \in \mathbb{R}$ such that
$$
x > M \Rightarrow |f(x) - L| < \epsilon/2
$$
And so for $x,y > M$, one has
$$
|f(x) - f(y)| < \epsilon
$$
Also, $f$ is uniformly continuous on $[0,M]$, so there is $\delta > 0$ such that
$$
x,y \in [0,M] \text{ and } |x-y| < \delta \Rightarrow |f(x) - f(y)| < \epsilon
$$
From this, you would think that
$$
|x-y| < \delta \Rightarrow |f(x) - f(y)| < \epsilon
$$
should hold. Except, you need to account for the case where $x < M$ and $y>M$.
This leads to all the messing around with $M+1$ and $\delta \leq 1$, etc.


text:
Q: Find all Folders with Certain Size Parameters? I am looking for a good way to find all folders that have contents that are say 500k or less. I think this involves recursively going to the lowest folder in a hierarchy and then "reading up" to get a size total. All ideas appreciated (something int he .NET framework or PowerShell if I really have to), thanks.

A: This could help you out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GetDirectorySize
{
    class Program
    {
        static void Main(string[] args)
        {
            long maxFolderSizeInBytes = 20000000;

            foreach (var directory in Directory.GetDirectories(@"C:\Projects\Visual Studio 2010\"))
            {
                string[] a = Directory.GetFiles(directory, "*.*");
                long i = 0;
                foreach (string name in a)
                {
                    FileInfo info = new FileInfo(name);
                    i += info.Length;
                }
                if (i <= maxFolderSizeInBytes)
                {
                    Console.WriteLine(directory);
                }
            }
            Console.ReadLine();
        }
    }
}


text:
Q: Does my Debug.WriteLines show up someplace? Here and there in my silverlight application I'm doing Debug.WriteLine. I've deployed the solution to another server, but something is wrong (works locally), is the debugs stored somewhere?

A: Debug.WriteLine internally uses OutputDebugString function which sends output to the currently attached debugger. If you opened browser with URL to remote server, it would load remote Silverlight application and you could attach Visual Studio debugger to the browser afterwards (if dll binaries match).


text:
Q: how to divide two intengers and get a result with decimal numbers? I'm doing a project in Contiki to a Zolertia module where I need to calculate the risk of a wildfire to occur.
To calculate this risk the formula used is Risk = Temperature / Humidity.
The result of Risk it's a decimal value and there are 5 different values range to classify this Risk: 0-0.49 , 0.5-0.99, 1-1.49, 1.5-1.99, >=2.
My problem is that I can't get decimal results. When I run it in the terminal it shows the value of Temperature and the value of Humidity but just a blank space in the value of Risk.
My code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "contiki.h"
#include <float.h>

PROCESS(temp_hum_fog, "Wildfire Control");
AUTOSTART_PROCESSES(&temp_hum_fog);

static struct etimer et;

PROCESS_THREAD(temp_hum_fog, ev, data)
{

    int16_t temp, hum;
    float risk;

    PROCESS_BEGIN()

    while(1) {
        etimer_set(&et, CLOCK_SECOND);
        PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

        temp = rand() % 45;
        hum = rand() % (85-5)+5;
        risk = (float)temp/(float)hum;

        printf("Temperature:%d ºC\nHumidity:%d HR\nRisk:%f\n", temp,hum,risk);

    }

    PROCESS_END();

}

If I change the type of temp and hum to float it won't show any results also so I'm not sure if float works in Contiki.
Does someone know any solution?

A: The C implementation you are using is not a full standard C implementation and does not support floating-point conversions in printf. Three options are:

*

*Check the documentation for your C implementation to see if support for floating-point can be enabled.

*Find another C implementation to use (particularly the standard C library).

*Use integer arithmetic, as in the example below, to do calculations.

This code will print the quotient to two decimal places, rounded down, using only integer arithmetic:
    int integer  = temp/hum;
    int fraction = temp%hum * 100 / hum;
    printf("Risk: %d.%02d\n", integer, fraction);

Note this assumes the values involved are positive; negative numbers could cause undesired outputs.

A: I have a few suggestions:

*

*Specify the literals with either a trailing 'f' or add a decimal place in

        temp = rand() % 45; hum = rand() % (85-5)+5;

*Declare temp and hum as floats and then cast the result of rand()


text:
Q: Trying to test input validity I've been working on a small project today, and after searching around for answers on StackOverflow and elsewhere, I've come to a roadblock.
I've been attempting to create a choose-your-own-adventure style game in Java and I'm beginning with creating a character using three characteristics (name, race, gender). I plan on using these to allow for branches in the story.
The problem is that I'm not getting the results I'm looking for. Currently, I've gotten my code to work, with a print statement showing the selections made by the player.
//list out character description

    System.out.println("You are " + Name + ", a " + characterGender + " " +
    characterRace + ".");

I had it working properly until I attempted to implement a test on the input given to root out invalid entries. I've attempted to use do-while loops and try-catch statements, but it just runs forward to the next option regardless of whether or not there is a valid input.
The general idea I'm looking to implement is:
display input options
check input to verify it is valid
if input is not valid, re-attempt to check for another input
if input is valid, move forward to next question
//create test to verify validity of race selection

    boolean raceBoolean;

    if (raceInt < 0 || raceInt > 4) {

        raceBoolean = true;

    try {

        do {

    //selection list that defines options

                if (raceInt == 1)
                    characterRace = "human";

                else if (raceInt == 2)
                    characterRace = "elf";

                else if (raceInt == 3)
                    characterRace = "orc";

                else if (raceInt == 4)
                    characterRace = "undead";

        }

        while (raceBoolean = false);

            System.out.println("Nice try. Enter a valid number for one of the four races!");

        }

            finally {

        }

I'm honestly at a loss. I know that this is simple stuff, but I'm trying to teach myself. I appreciate any help that may be provided. Other topics aren't very helpful given that they don't provide much context for why there was an issue in the first place.
Thank you in advance. I'm honestly seeking to learn how to do this properly.
Full code below:
import java.util.Scanner;

public class Adventure {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    //insert input tool
    Scanner input = new Scanner(System.in);

    //create inventory object for gold and items
    int gold = 10;

    //create health points object

    //address player with greeting
    System.out.println("Welcome to your adventure!");

    //ask for character name, race, and gender

    System.out.println("What will your adventurer's name be?");

    String Name = input.nextLine();

    System.out.println("What will your adventurer's race be?");
    System.out.println("1. Human");
    System.out.println("2. Elf");
    System.out.println("3. Orc");
    System.out.println("4. Undead");

    int raceInt = input.nextInt();

    String characterRace = "";

    //create test to verify validity of race selection

    boolean raceBoolean;

    if (raceInt < 0 || raceInt > 4) {

        raceBoolean = true;

    try {

        do {

    //selection list that defines options

                if (raceInt == 1)
                    characterRace = "human";

                else if (raceInt == 2)
                    characterRace = "elf";

                else if (raceInt == 3)
                    characterRace = "orc";

                else if (raceInt == 4)
                    characterRace = "undead";

        }

        while (raceBoolean = false);

            System.out.println("Nice try. Enter a valid number for one of the four races!");

        }

            finally {

        }

    }

    //ask for character gender

    System.out.println("What will your adventurer's gender be?");
    System.out.println("1. Male");
    System.out.println("2. Female");

    int genderInt = input.nextInt();

    String characterGender = "";

    if (genderInt == 1)
        characterGender = "male";

    else if (genderInt == 2)
        characterGender = "female";

    //list out character description

    System.out.println("You are " + Name + ", a " + characterGender + " " + characterRace + ".");

    //introduce player to adventure with different introductions for different races

    System.out.print("You came to Glassolin with only ten gold pieces to your name. ");

    if (characterRace == "human")
        System.out.print("Glassolin is home to many humans; some from the far reaches of the realm. You feel right at home, more or less,"
                + " as long as you ignore the occasional odd look from the cityfolk staring at someone dressed in farmer's clothes.");
    else if (characterRace == "elf")
        System.out.print("While an elf isn't the most common sight around town, the locals seem like they don't care one way or another "
                + "about you wandering the streets. ");

}

}

A: you had given  while (raceBoolean=false) (assignment operator) in comparison . And secondly were comparing string using == operator . But in java strings are compared using .equals() method. I have modified your code .
Here is the full working code
import java.util.Scanner;

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    //insert input tool
    Scanner input = new Scanner(System.in);

    //create inventory object for gold and items
    int gold = 10;

    //create health points object

    //address player with greeting
    System.out.println("Welcome to your adventure!");

    //ask for character name, race, and gender

    System.out.println("What will your adventurer's name be?");

    String Name = input.nextLine();

    //create test to verify validity of race selection

    boolean raceBoolean=true;
    String characterRace = "";

    try {

        do {

    //selection list that defines options
                                 System.out.println("What will your adventurer's race be?");
                                System.out.println("1. Human");
                                System.out.println("2. Elf");
                                System.out.println("3. Orc");
                                System.out.println("4. Undead");

                                int raceInt = input.nextInt();
                                if (raceInt < 0 || raceInt > 4) {
                                raceBoolean = false;

                                }
                        else{
                                raceBoolean = true;
                            }

                if (raceInt == 1){
                    characterRace = "human";

                    }

                else if (raceInt == 2)
                    characterRace = "elf";

                else if (raceInt == 3)
                    characterRace = "orc";

                else if (raceInt == 4)
                    characterRace = "undead";
                System.out.println(raceInt);

        }
        while (raceBoolean==false);
        }

            finally {

        }

    //ask for character gender
    System.out.println("What will your adventurer's gender be?");
    System.out.println("1. Male");
    System.out.println("2. Female");

    int genderInt = input.nextInt();

    String characterGender = "";

    if (genderInt == 1)
        characterGender = "male";

    else if (genderInt == 2)
        characterGender = "female";

        System.out.println(characterRace);
    //list out character description

    System.out.println("You are " + Name + ", a " + characterGender + " " + characterRace + ".");

    //introduce player to adventure with different introductions for different races

    System.out.print("You came to Glassolin with only ten gold pieces to your name. ");

    if (characterRace.equals("human"))
        System.out.print("Glassolin is home to many humans; some from the far reaches of the realm. You feel right at home, more or less,"
                + " as long as you ignore the occasional odd look from the cityfolk staring at someone dressed in farmer's clothes.");
    else if (characterRace.equals("elf"))
        System.out.print("While an elf isn't the most common sight around town, the locals seem like they don't care one way or another "
                + "about you wandering the streets. ");

}

}

A: Starting after:
  System.out.println("4. Undead");

This code should continue to ask for a valid answer until one is given.
//create test to verify validity of race selection
String characterRace = "";
boolean raceBoolean = false;

Do{
int raceInt = input.nextInt();

    if (raceInt == 1){
        characterRace = "human";
        raceBoolean = true;
        }else{
            if (raceInt == 2){
            characterRace = "elf";
            raceBoolean = true;
            }else{
                if (raceInt == 3){
                characterRace = "orc";
                raceBoolean = true;
                }else{
                    if (raceInt == 4){
                    characterRace = "undead";
                    raceBoolean = true;
                    }else{
                        raceBoolean = false;
                        System.out.println("Nice try. Enter a valid number for one of the four races!");
                    }
                }
            }
        }
    }while(raceBoolean = false)

It puts the input inside of a do while statement so it can repeatedly ask for a different input.  Also, I initialized the Boolean as false just as a fail safe.  The while statement at the end tests if a valid input was given.
Testing is done with nested if/else statements.


text:
Q: How does the push-down automaton have to look like? Could you give me a hint how to find a push-down automaton for the language:
$$L=\{ a^n b^{2n} | n \in \mathbb{N}\}$$
How does the push-down automaton have to look like?

A: I'm reposting mjqxxxx's comment because it hits the nail on the round flat part.

Start in state $A$ with an empty stack. For each a you read in state $A$, push two tokens on the stack. When you encounter your first b, move to state $B$ and pop a token from the stack. For each additional b you read in state $B$, pop a token from the stack. REJECT if you try to pop from an empty stack, if you encounter an a while you're in state $B$, or if the stack isn't empty when you're done reading the string; otherwise ACCEPT.


text:
Q: At Vis.js, timeline, refresh display on change data i have set a html-form in this text box i change the title, content, start- and end-time. By a click on 'okay'-button change the dataitem.
How can i refresh the timline?
Code from onlclick-Button
    var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData._data[selItemNr].start = start;
        timeline.itemsData._data[selItemNr].end = end;
        timeline.itemsData._data[selItemNr].title = tbTitle.value;
        timeline.itemsData._data[selItemNr].content = tbContent.value;
        timeline.redraw();
    }
};

The values of item is correct set also the start and end, but the timline shows nothing change.
regards Mario

A: i have found the solution:
The javascrtipt class store the _data.id into cuItemId
and in the OnClick function i call timeline.itemdData.update().
var onClickEditOkay = function () {
    if (selItemNr != null){
        var start = new Date(dummyDate);
        var sh = tbStart.value.split(":");
        start.setHours(parseInt(sh[0]));
        start.setMinutes(parseInt(sh[1]));
        var end = new Date(dummyDate);
        sh = tbEnd.value.split(":");
        end.setHours(parseInt(sh[0]));
        end.setMinutes(parseInt(sh[1]));
        timeline.itemsData.update({id: cuItemId, start: start,end: end, title: tbTitle.value, content: tbContent.value});
    }
};

That works fine.
regards Mario


text:
Q: Weird results of modulo arithmetic with negative numbers and unsigned denominators I have an array in C that I want to address in manner similar to a circular buffer, so for example: a[-1] would return me the last element of the array.
To do that I tried to use modulo arithmetic (obviously), problem is, I'm getting quite weird results when negative numbers are involved:
-1 % 4 = -1
-1 % 4U = 3

So far, so good.
-1 % 4000 = -1
(-1+4000U) % 4000U = 3999
(-1) % 4000U = 3295

Question: The value (3295) does hold for the (a/b)*b + a%b shall equal a, truncated towards zero (for a=-1, b=4000) from C standard (6.5.5#6) so it's not a bug per se, but why is the standard defined this way?! Surely, there must be some logic in this...
How do I have to write a%b to get sensible results for negative a (as (a+b)%b stops working when abs(a)>b)?
Test application:
#include <stdio.h>
int main(int argc, char **argv) {
  int i=0;
#define MAX_NUM 4000U
  int weird = (i-1)%MAX_NUM;
  printf("%i\n", weird);
  printf("%i\n", (i-1+MAX_NUM))%MAX_NUM);
  printf("a: %i, b: %i, a from equation: %i\n", i-1, MAX_NUM,
    ((i-1)/MAX_NUM)*MAX_NUM + weird);
  return 0;
}

A: Arithmetic in C always (short of some oddities with bit shift operators) promotes all operands to a common type before performing the operation. Thus:
(-1) % 4000U

is promoted as (assuming 32 bit ints):
0xffffffffu % 4000u

which yields 3295.
If you want to use modular arithmetic for array offsets that could be negative, you first need to abandon using unsigned arithmetic on the offsets. As such, your results will now be in the range -MAX_NUM+1 to MAX_NUM-1, due to C's ugly definition of signed integer division and remainder. If the code is not performance critical, just add if (result<0) result+=MAX_NUM; and be done with it. If you really need to avoid the branch (and you've measured to determine that you need to avoid it) then ask again how to optimize this computation and myself or someone brighter than me on SO will surely be able to help. :-)

A: As 6.5.3 says, "The usual arithmetic conversions are performed on the operands."  In the case of your example:
(-1) % 4000U

that means converting the -1 into an unsigned int.  Your -1, therefore, is really being interpreted as 4294967295... for which the remainder is exactly what you're seeing: 3295.
The "Usual arithmetic conversions" are described in 6.3.1.8.


text:
Q: A puzzling "failure" of the Chain Rule Consider the standard transformation equations between Cartesian and polar
coordinates:
\begin{align*}
x&=r \cos \theta\\
y&=r \sin \theta
\end{align*}
and the inverse: $r=\sqrt{x^2+y^2}, \theta=\arctan\frac{y}{x}$.
Now consider the following product of derivatives: ${\displaystyle f=\frac{\partial r(x,y)}{\partial y}\frac{\partial y(r,\theta)}{\partial r}}.$
By the chain rule ${\displaystyle f=\frac{\partial r(x,y)}{\partial y}\frac{\partial y(r,\theta)}{\partial r} =
\frac{\partial r}{\partial r} = 1}.$ However, if we calculate each multiplicand in isolation, then transform the
mixed-coordinate result into a single coordinate system, we get:
\begin{align*}
\frac{\partial r(x,y)}{\partial y}& =\frac{y}{\sqrt{x^2+y^2}}=\sin\theta\\
\frac{\partial y(r,\theta)}{\partial r}& = \sin\theta
\end{align*}
and therefore, ${\displaystyle f=\frac{\partial r(x,y)}{\partial y}\frac{\partial y(r,\theta)}{\partial r} = \sin^2\theta}$
But we've shown by the chain rule that
$f=1$!
:giantfireball:
I must be abusing the chain rule in some way (in the original context in which I stumbled on this, the correct result is $\sin^2\theta$), but I can't see what I did wrong.  What's going on?

A: This is what Penrose calls "the second fundamental confusion of calculus". The problem is that with partial derivatives, what is held constant is just as important as what is varied. A simple example is if we change coordinates by
$$ x = u+v \\
y = v, $$
or
$$ u = x-y \\
v = y $$
Then
$$ \frac{\partial y}{\partial u} = 0, \quad \text{but} \quad \frac{\partial u}{\partial y} = -1, $$
which is quite different from in one dimension. Even weirder,
$$ \frac{\partial u}{\partial v} = 0, \quad \text{ but }  \quad \frac{\partial u}{\partial y} = -1,  $$
even though $v=y$!
The reason is that in the first expression, $u$ is implicitly held constant, whereas in the second, $x$ is held constant, and although $u=y$, clearly $u \neq x$. This is why partial derivatives are such a nuisance compared to differentials: a partial derivative is moving along a line, and a line requires specifying everything that is constant along it, whereas differentials act more like hyperplanes, which only need a normal to be specified.

A: Thanks to @InterstellarProbe  for the memory jog.
Recall the multivariable chain rule:
$\displaystyle  \frac{\partial u(r,\theta)}{\partial r}=\frac{\partial u(x(r,\theta),y(r,\theta))}{\partial r} = \frac{\partial u}{\partial x}\frac{\partial x}{\partial r}+\frac{\partial u}{\partial r}\frac{\partial r}{\partial y}$
Clearly,
$\displaystyle  \frac{\partial u(x(r,\theta),y(r,\theta))}{\partial r} \ne \frac{\partial u}{\partial r}\frac{\partial r}{\partial y}$
which is what the OP assumes, for the case $u=r$. You could calculate each term seperately as in OP, or, just to show the multivariable chain rule hasn't failed us yet ( using the chain rule identity above with $u=r$):
${\displaystyle f=\frac{\partial r(x,y)}{\partial y}\frac{\partial y(r,\theta)}{\partial r} = \frac{\partial r}{\partial r} -  \frac{\partial r}{\partial r}\frac{\partial r}{\partial y} = 1 - \cos(\theta)^2 = \sin(\theta)^2
}$
Which agrees with result in OP.
In summary, with multivariate functions you cannot simply "cancel" differentials. Any muscle memory from single variable calculus needs
to be corrected.
Update:
There is a case where partial derivatives can be cancelled, though it's a matter of notation. If we use Einstein Summation, then it is true that:
$$
\frac{\partial u(x^1,x^2,\ldots,x^n)}{\partial \bar{x}^i}\frac{\partial \bar{x}^i}{\partial x^j}=\frac{\partial u}{\partial x^j}
$$
Assuming $x^i=f_i(\bar{x}^1,\bar{x}^2,\ldots,\bar{x}^n)$.
Of course this works only because the repeated $i$ index on the LHS indicates a summation, so that the LHS is actually the correct application of the chain rule  for the partial derivative on the RHS.

A: One of my favorites in the hall of shame of differential cancellation: Consider the plane $x+y+z=0.$ At every point on this plane, each of the variables can be solved explicitly(!) as a function of the other two. We easily find
$$\frac{\partial x}{\partial y}=\frac{\partial y}{\partial z} = \frac{\partial z}{\partial x}=-1.$$
Now consider
$$\frac{\partial x}{\partial y}\cdot\frac{\partial y}{\partial z} \cdot \frac{\partial z}{\partial x}$$
This is a merry canceler's delight: All differentials cancel and so the product is $1$! But as we've seen, each factor is $-1,$ so the product is  actually $-1.$


text:
Q: Handle events raised from a dynamically loaded .NET dll I have a VB.NET application which loads some dll files dynamically. All plugins are in a folder and my application loads all dll files from this folder.
In order to load a dll, I use the following code
_aAssembly = Reflection.Assembly.LoadFile(_File.FullName)
_aClass = _aAssembly.GetType(_AssemblyName & "." & ClassName)
_aAddin = Activator.CreateInstance(_aClass)

To run a method in this dll
Function RunMethod(ByVal Method As String, Optional ByVal Paramter() As Object = Nothing) As Object
    Dim aMethode As MethodInfo = _aClass.GetMethod(Method)
    Return aMethode.Invoke(_aAddin, Paramter)
End Function

This works perfect. But now I'd like to fire an event in my dll files and handle them in my main application. I started with adding the following code to my dll:
Public Shared Event GotSomethingToSend(Str As String)

And I fire the event with
RaiseEvent GotSomethingToSend(Str)

My problem is that I have no clue on how to "catch" the event in my main application. Is it even possible?
I already tried GetEvent():
Dim ei As EventInfo = _aAssembly.GetType(_AssemblyName & "." & ClassName).GetEvent("GotSomethingToSend")

But I didn't get very far... Any help on this?

A: You already have an EventInfo instance, you just need to wire it up to a method in your app. Try calling EventInfo.AddEventHandler, e.g.
ei.AddEventHandler(_aAddin, DirectCast(AddressOf MyGotSomethingToSendHandlerMethod, GotSomethingToSendEventHandler))

Private Delegate Sub GotSomethingToSendEventHandler(str As String)

Private Sub MyGotSomethingToSendHandlerMethod(str As String)
    ' TODO: Event handling code.
End Sub

Note - The type cast is required because the compiler can't infer the correct delegate type in this late-binding scenario.
ADDENDUM
Although the above code should do what you want, Microsoft recommend that you stick to their common standard for all event signatures (sender As Object, e As TEventArgs). If you want to do this, you can re-design the code as follows:
' Encapsulate all event data in a dedicated class.
Public Class GotSomethingToSendEventArgs
    Inherits EventArgs
    Public Property Data As String
End Class

' Handler method now looks like this.
Private Sub MyGotSomethingToSendHandlerMethod(sender As Object, e As GotSomethingToSendEventArgs)
End Sub

' Wire-up code now looks like this.
ei.AddEventHandler(_aAddin, DirectCast(AddressOf MyGotSomethingToSendHandlerMethod, EventHandler(Of GotSomethingToSendEventArgs)))


text:
Q: Azure WebRole + Flask: AttributeError: 'module' object has no attribute 'wsgi_app' Unlike
Azure Flask Deployment - WSGI Interface problem, deploying Flask app to Azure Web Role throws a following problem.

AttributeError: 'module' object has no attribute 'wsgi_app'

What is this error?

A: I got it finally.
The startup .py file has to define wsgi_app after the Flask app definition.
app = Flask(__name__)

# define for IIS module registration.
wsgi_app = app.wsgi_app

if __name__ == '__main__':
    app.run()

And also, {StartupModule}.wsgi_app is defined in Project properties >  Web > WSGI Handler.
To shorten trial-and-error time, it would be good to start with newly created Azure WebRole Python project template.
Whooa. spent a whole day.


text:
Q: I need to convert some code so that it does not contain the 'auto' keyword I have created a program but in the code I used 'auto' and have found out that im not allowed to. I can not figure out how to not use it as ive always just used it. Any help or tips would be much appreciated.
Here is the code i have:
string reverse_word(string str)
{
    string output_str;

    output_str.reserve(str.length());

    char save_non_alpha = 0;

    for (auto it = str.rbegin(); it != str.rend(); it++) {

        if (it == str.rbegin() && !is_letter(*it)) {
            save_non_alpha = *it;
        }
        else {
            output_str += *it;
        }
    }
    if (save_non_alpha != 0) {
        output_str += save_non_alpha;
    }
    return output_str;
}

A: You should use the right returned type by the str.rbeghin() to replace the auto so i guess this should be enough
for (std::string::reverse_iterator it=str.rbegin(); it!=str.rend(); ++it)

A: Your question is a bit confusing, as you haven't explained why you ain't able to use it, I'm gonna assume it rejects your program.
For a long time, Gcc was defaulting to c++98. If you are still using it, try changing the default standard. This can be done with the flag -std=.
Some possible values include: c++11 (official standard that introduced it), c++0x (pre-release implementation of c++11), c++14, c++17, c++2a
In case you use a different compiler, like Clang, you can use the same flag. MSVC uses /std=, and the only supported values are c++14, c++17 and c++-latest.
If your compiler is too old to support any of these, I recommend upgrading your compiler.


text:
Q: SP2007 Workflow: Lookup XXXX property for XXX by Title? Does anybody know if there is a way to use the Look site user property but search by the user's title instead of their NTLogin/Username?
Example:
Lookup JobTitle property for John Smith, store in Variable: JobTitle
I am received the following error: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: User not found.
Is there a different way I can format this request that still allows me to use the user's title instead of their username?
Thanks!

A: I was able to accomplish this by using a "Person or Group" column. I used the workflow to update the "Person or Group" column with the user's title, and then used the "Person or Group" column to perform the property lookup in the workflow.


text:
Q: How to show show or hide text boxes in SSRS How can I show or hide text boxes when i export to CSV or EXCEL in SSRS ?
I have parameter called Reports_Export which tells to show or hide those text boxes when i export to csv or excel.
If Reports_export = 1 show otherwise hide when export.

A: Hide a TextBox based on an expression

*

*Right click on the TextBox => Text Box Properties

*In Visibility, select Show or hide based on an expression

*Enter your formula

If you want to hide the Text Box based on the output format, you may consider using the Globals!RenderFormat.Name variable.
Example:
=Iif(Globals!RenderFormat.Name = "CSV" Or Globals!RenderFormat.Name = "EXCEL", True, False)

Here is an article on this:

*

*Hide/Show Items Dependant On Export Format (SSRS)
That way you won't rely on a parameter to hide the elements.


text:
Q: Classification of orientable non-closed surfaces How does the classification of closed (compact, boundaryless) surfaces imply the classification of all orientable not-necessarily-compact surfaces with boundary? It seems to be that they are all obtained by deleting points and the interiors of closed disks from closed surfaces. This gives three indices: (genus, number of disks deleted, number of points deleted). Why is this exhaustive? Why is there only one such triple for every surface? Clearly the second index is unique (it determines the number of boundary components), but how do you know you can't change both the first and third and wind up with the same space?

A: It is a long way from classification of closed 2-dimensional manifolds to the classification of all (connected) 2-dimensional manifolds (possibly with boundary). This was accomplished by E. Brown and R. Messer,  "The classification of two-dimensional manifolds", Trans. Amer. Math. Soc., vol. 255 (1979), 377–402,
about 100 years after closed surfaces were classified.


text:
Q: Google map script to angular directive Could someone help me translate it to angular directive?
var mapa;
var marker;

function mapaStart() {
mapOpc = {
    center: new google.maps.LatLng(52.348763181988076, 18.61083984375),
    zoom: 6,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapa = new google.maps.Map(document.getElementById("doMeeting"), mapOpc);

marker = new google.maps.Marker({
    position: new google.maps.LatLng(52.348763181988076, 18.61083984375),
    draggable: true,
    map: mapa,
});
marker.setMap(mapa);

// zdarzenia dla markera
google.maps.event.addListener(marker, 'drag', uaktualnijWspolrzedne);
google.maps.event.trigger(marker, 'drag');

// zdarzenia dla mapy
google.maps.event.addListener(mapa, 'click', function (event) {
    marker.setPosition(event.latLng);
    uaktualnijWspolrzedne();
});

}

function uaktualnijWspolrzedne() {
var input_lat = document.getElementById('lat');
var input_lng = document.getElementById('lng');
var punkt = marker.getPosition();

input_lat.value = punkt.lat();
input_lng.value = punkt.lng();
}
google.maps.event.addDomListener(window, 'load', mapaStart);

EDIT
Maybe it wasnt good idea to put in on jsfiddle becouse of configuration jsfiddle .
I put it in on plnkr to make it clear:
http://plnkr.co/edit/EyPOmok6vmvA6Cc2yQws?p=preview
But when i try to implement to my project i get blank border instead google map, (module Geolocation work)

A: Here is your updated Fiddle. There was a problem in the setup and ng-app was not initialized.
// just a comment

A: Problem is in configuring JSFiddle, not in your code. You need to do:

*

*Remove angular.js script from resources

*Select angular.js from dropdown in Fiddle Options (under Frameworks & Extensions)

*Select options "No wrap - in head"

Explanations here: Simple AngularJS running on JSFiddle


text:
Q: Heroku reset JSON file edited by admin panel I have a node.js app deployed correctly on Heroku. It's a simple app that stores some values in a JSON file and it read or update that file (like it is a database).
Everything works fine (creation of new nodes in JSON, deletion, editing etc...) but it seems that every X hours the JSON file is resetted as it is in the last commit pushed to Heroku.
Is there a way to handle this without using a database? (like MongoDb for example)
Thanks

A: Even with a minimal Heroku deployment, the design needs to account for a layer capable of storing state ( ie u mention Mongo ).
Your design should include a separate node from the Heroku ( app layer ) where the state resides and where your app has authorization to do HTTP actions (POST, GET) on the state stored in your JSON.
The reason for your intermittent resets/reverts of the JSON is involved with  Heroku's service tier and with the fact that your apps state is cycling UP and DOWN .
Look for a sample Heroku app with minimal persistent layer....


text:
Q: PHP match values between 2 arrays not same key I have made researches and havent fount any solutions for this yet. So final thought is come to Stackoverflow and ask the question.
I have 2 array like below:
BigArray
Array
(
    [0] => Array
        (
            [id] => 1
            [category_name] => Accountancy
            [category_name_vi] => Kế toán
            [category_id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [category_name] => Armed forces
            [category_name_vi] => Quân đội
            [category_id] => 2
        )

    [2] => Array
        (
            [id] => 3
            [category_name] => Admin & Secretarial
            [category_name_vi] => Thư ký & Hành chính
            [category_id] => 3
        )

    [3] => Array
        (
            [id] => 4
            [category_name] => Banking & Finance
            [category_name_vi] => Tài chính & Ngân hàng
            [category_id] => 4
        )
)

and SmallArray:
Array
(
    [0] => Array
        (
            [id] => 7
            [category_id] => 2
            [jobseeker_id] => 1
        )

    [1] => Array
        (
            [id] => 8
            [category_id] => 3
            [jobseeker_id] => 1
        )
)

Ok, now I wanted to match each category_id from SmallArray link with respectively category_name from BigArrayand the output I only need matched values between SmallArray and BigArraywhere category_id of SmallArray is key and category_name of BigArray is value like below:
Matched array:
Array
    (
        [0] => Array
            (
                [2] => Armed forces
            )

        [1] => Array
            (
                [3] => Admin & Secretarial
            )
    )

So far, I have tried array_intersect, 2 foreach loops but no luck. Any advise would be very appreciated :(
Thanks

A: This should do that:
foreach ($smallArray as $smallKey => $smallElement) {
    foreach ($bigArray as $bigKey => $bigElement) {
        if ($bigElement['id'] == $smallElement['category_id']) {
            $smallArray[$smallKey] = array(
                $bigElement['id'] => $bigElement['category_name'],
            );
            break; // for performance and no extra looping
        }
    }
}

After these loops, you have what you want in $smallArray.


text:
Q: How to get Django admin's "Save as new" to work with read-only fields? I want to implement the "Save as new" feature in Django's admin for a model such as this one:
class Plasmid (models.Model):
    name = models.CharField("Name", max_length = 255, blank=False)
    other_name = models.CharField("Other Name", max_length = 255, blank=True)
    selection = models.CharField("Selection", max_length = 50, blank=False)
    created_by = models.ForeignKey(User)

In the admin, if the user who requests a Plasmid object is NOT the same as the one who created it, some of the above-shown fields are set as read-only. If the user is the same, they are all editable. For example:
class PlasmidPage(admin.ModelAdmin):

    def get_readonly_fields(self, request, obj=None):

        if obj:
            if not request.user == obj.created_by:
                return ['name', 'created_by',]
            else:
                return ['created_by',]
        else:
            return []

    def change_view(self,request,object_id,extra_context=None):

        self.fields = ('name', 'other_name', 'selection', 'created_by',)
        return super(PlasmidPage,self).change_view(request,object_id)

The issue I have is that when a field is read-only and a user hits the "Save as new" button, the value of that field is not 'transferred' to the new object. On the other hand, the values of fields that are not read-only are transferred.
Does anybody why, or how I could solve this problem? I want to transfer the values of both read-only and non-read-only fields to the new object.

A: Did you try  Field.disabled attribute?

The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.

I did a quick test in my project. When I added a new entry the disabled fields were sent to the server.
So something like this should work for you:

class PlasmidPage(admin.ModelAdmin):

    def get_form(self, request, *args, **kwargs):
        form = super(PlasmidPage, self).get_form(request, *args, **kwargs)
        if not request.user == self.cleaned_data['created_by'].:
            form.base_fields['created_by'].disabled = True
            form.base_fields['name'].disabled = True

    def change_view(self,request,object_id,extra_context=None):

        self.fields = ('name', 'other_name', 'selection', 'created_by',)
        return super(PlasmidPage,self).change_view(request,object_id)

A: It happens because Django uses request.POST data to build a new object, but readonly fields are not sent with the request body. You can overcome this by making widget readonly, not the field itself, like this:
form.fields['name'].widget.attrs = {'readonly': True}
This has a drawback: it's still possible to change field values by tampering the form (e.g if you remove this readonly attribute from the widget using devtools console). You could protect from that by checking that values haven't actually changed in clean() method.
So full solution will be:
class PlasmidForm(models.ModelForm):
    class Meta:
        model = Plasmid

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and not self.instance.created_by == request.user:
            self.fields['name'].widget.attrs = {'readonly': True}

    def clean(self):
        cleaned_data = super().clean()
        if self.instance and not self.instance.created_by == request.user:
            self.cleaned_data['name'] = instance.name  # just in case user tampered with the form
        return cleaned_data

class PlasmidAdmin(admin.ModelAdmin):
    form = PlasmidForm
    readonly_fields = ('created_by',)

    def save_model(self, request, obj, form, change):
        if obj.created_by is None:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

Notice I left created_by to be readonly, and instead populate it with the current user whenever object is saved. I don't think you really want to transfer this property from another object.


text:
Q: Query the database using discriminator values I am using single table inheritance strategy. I want to perform a search in the database by filtering it using the discriminator type. How am I to write a function in JPA to perform this operation.
The normal way of defining methods using findBy... method does not produce results.
Here is my parent class
@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name="Leave_Type",
        discriminatorType=DiscriminatorType.STRING
        )
public class LeaveQuota {
// the fields and the required methods
}

Here are the two child entities
@Entity
@DiscriminatorValue("Annual")
public class AnnualLeave extends LeaveQuota {
// the fields and the required methods
}

@Entity
@DiscriminatorValue("Casual")
public class CasualLeave extends LeaveQuota {
// the fields and the required methods
}

I want to query the database by filtering the Annual leaves and Casual leaves separately. Which means when I search for annual leaves, all records in the discriminator column with value "annual" should be retrieved. How can I implement this.
Thanks in advance!

A: Create a repository for AnnualLeave.java namely AnnualLeaveRepo.java and CausualLeave.java namely as shown below:
AnnualLeaveRepo.java
@Repository
public interface AnnualLeaveRepo extends JpaRepository<AnnualLeave,Integer>   {

    @Query("from AnnualLeave")
    public List<AnnualLeave> getLeaves();

    //consider noOfLeave is member of AnnualLeave.java class
    public List<AnnualLeave> findByNoOfLeave(int noOfLeave);

}

CausalLeaveRepo.java
@Repository
public interface CausalLeaveRepo extends JpaRepository<CausalLeave,Integer>   {

    @Query("from CausalLeave")
    public List<CausalLeave> getLeaves();
}

Now when you use findAll() or getLeaves() or findByNoOfLeave(int) methods or any other custom abstract method of AnnualLeaveRepo class, it will automatically filter result with Leave_Type="Annual".
similarly, when you use findAll() or getLeaves() methods or any other custom abstract method of CausalLeaveRepo class, it will automatically filter result with Leave_Type="Causal".
You don't have to filter out explicitly.
note
If you have any properties in your class having relationships(@OneToMany etc..) with LeaveQuota entity or it's inherited entities then don't forget to use the @JsonIgnore annotation on those properties. Else you'll get a stackoverflow error


text:
Q: Detect clusters from graph &nbsp&nbsp&nbsp&nbsp&nbspSorry for my English but I will try to explain my problem statement.I have a csv with near about 156 columns. I want to plot the Scatter graph with one of the columns as X axis and another one as Y axis. By making combinations of 150 columns i will be generating 11K graphs.Now i have to go through each graph to see is there distinguishable clusters in graph.but to go with visual route it will take whole lot of time.and in feature if graph changes i have to repeat the work. So i am looking for solution where i can detect which graph has clusters.
I will provide one of the sample graph generated by using python matplot library.Image link here
I will also sharing some of the column structure which i am having.

col1           col2           col3           col4           col5
0.05414   0.0027070  0.012994    0.0508931   0.042772063
0.00155    0.0001942      0.000388   0.0120453  0.0069943
I am intermediate at Python-2.7


text:
Q: Does python have a built in min-heap data structure? Does python have a built in min-heap data structure in 2.7.3?
I don't want to import code.
I want something like
myheap = minheap(key=lambda x: x[1])
myheap.add(obj)
o = myheap.pop()

Is this possible?

A: Like everybody says, heapq is it -- but, as nobody's mentioned yet, it doesn't support a key=!  So you need to fall back to the good old DSU (decorate-sort-undecorate) idiom that key= uses internally wherever it's supported (alas not in heapq, except for the functions nlargest and nsmallest that don't really have much to do with the rest of the module).
So you can wrap heapq functionality, with the addition of a key, e.g in a class of your own:
import heapq

class MyHeap(object):
    def __init__(self, key, data=())
        self.key = key
        self.heap = [(self.key(d), d) for d in data]
        heapq.heapify(self.heap)

    def push(self, item):
        decorated = self.key(item), item
        heapq.heappush(self.heap, decorated)

    def pop(self):
        decorated = heapq.heappop(self.heap)
        return decorated[1]

    def pushpop(self, item):
        decorated = self.key(item), item
        dd = heapq.heappushpop(self.heap, decorated)
        return dd[1]

    def replace(self, item):
        decorated = self.key(item), item
        dd = heapq.heapreplace(self.heap, decorated)
        return dd[1]

    def __len__(self):
        return len(self.heap)

See https://docs.python.org/2/library/heapq.html for the distinction between pushpop and replace (and the other auxiliary functions supplied by standard library module heapq).

A: Python comes with heapq, which you don't have to download, but you still have to import.
Python has very little in the way of data structures you can use without using the import statement altogether. Do you really want your language to have its entire standard library loaded in memory and namespace for every project?


text:
Q: difficulty with for loops and appending in python 2.7 I need to write a for loop for the following process:
elements = [
            [ "a", ['aft','fwd','starboard']],
            [ "b", ['plastic','metal','wood']]
            ]

query1 = []
query2 = []
temp1 = []
temp2 = []
final = []

for keyword in elements[0][1]:
   a = do_something.search(keyword)
   query1.append(a)

temp1.append(elements[0][0])
temp1.append(query1)

for keyword in elements[1][1]:
    a = do_something.search(keyword)
    query2.append(a)

temp2.append(elements[1][0])
temp2.append(query2)

final.append(temp1)
final.append(temp2)

where do_something is a SQL query. The expected answer is something of the following:
final = [['a', [['result1','result2','result3'],['result4','result5']]],
        ['b', [['resultA','resultB']]]]

where results 1-5 are returned SQL queries associated with value 'a' and values A and B are returned SQL queries associated with value 'b'
My attempt:
query = []
temp = []
final = []

for i in range(0,len(elements)):
    for keyword in elements[i][1]:
       a = do_something.search(keyword)
       query.append(a)

 temp.append(elements[i][0])
 temp.append(query)
 final.append(temp)

but I seem to be over appending and I can't figure out the problem

A: I think you have condensed it ok you just aren't using clean containers
I would personally scope them in the loop :
#query = []
#temp = []
final = []

for i in range(0,len(elements)):
    temp = []
    query = [] # use an empty list
    for keyword in elements[i][1]:
       a = do_something.search(keyword)
       query.append(a)

    temp.append(elements[i][0]) # before the temp still contained first iteration data.
    temp.append(query)
    final.append(temp)


text:
Q: Using reactNative with GitHub and mixing between MAC and PC? Someone how has got problems when using reactNative with GitHub and mixing between MAC and PC? We got problems when cloning a repository
After typing npm start we get following error message...

react-native-scripts start

sh: /Users/juliafalk/Desktop/J3/node_modules/.bin/react-native-scripts: Permission denied
npm ERR! code ELIFECYCLE
npm ERR! errno 126
npm ERR! J3@0.1.0 start: react-native-scripts start
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the J3@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/juliafalk/.npm/_logs/2018-03-28T07_09_02_393Z-debug.log
student251-74:J3 juliafalk$
This only occurs between MAC and PC and not between MAC and MAC or PC and PC.... Anyone that have had the same problem and that have any solutions for this??


text:
Q: Mocking a method based on the parameter in Spock Im trying to figure out mocking and for some reason it keeps returning the correct answer (win) not the one i want it to return (mac)
/**
 * This is an empty imple class.  Its intention is to allow operating
 * system specific information to be mocked for unit testing.
 */
class OsImpl extends Os {

}

/**
 * A utility convenience class that helps with pulling a variety of machine information for the build system
 */
class ProjectInfo {
    static String operatingSystem(){
        operatingSystem(new OsImpl())
    }
    /**
     * Returns a 3 char code on the operating system of the local machine.
     * @return String Code ['win', 'mac', 'nix']
     */
    static String operatingSystem(OsImpl os){
        if (os.isFamily(os.FAMILY_WINDOWS)) {
            'win'
        } else if (os.isFamily(os.FAMILY_MAC)) {
            'mac'
        } else if (os.isFamily(os.FAMILY_UNIX)) {
            'nix'
        } else {
            null
        }
    }
}

class ProjectInfoTest extends Specification {

    def "trying this out"(){
        when:
        OsImpl os = Mock(OsImpl)

        and: 'mock a mac'
        1 * os.isFamily(os.FAMILY_WINDOWS) >> false
        1 * os.isFamily(os.FAMILY_MAC) >> true

        then: 'should return a mac os'
        ProjectInfo.operatingSystem(os) == 'mac'
    }
}

In easymock i would normally do a when(...).return(...) but im not sure how to do the same thing with spock.
Second try
def "trying this out"(){
        setup:
        OsImpl os = Mock(OsImpl)
        1 * os.isFamily(os.FAMILY_WINDOWS) >> false
        1 * os.isFamily(os.FAMILY_MAC) >> true

        when:
        String shouldBe = 'mac'

        then: 'should return a mac os'
        ProjectInfo.operatingSystem(os) == shouldBe
    }

Still returns windows, not mac
Heres another example of this.  I suppose i just suck at mocking.  But here's the method i want to test
def switchArtifactoryOffline(){
    def config = new XmlSlurper().parseText( artifactoryClient.system().configuration())
    if (config.offlineMode == false){
        config.offlineMode = true
        artifactoryClient.system().configuration(XmlUtil.serialize( config ))
    }
    log.lifecycle("Disabled Artifactory Internet Access")
}

and my test method
def "check that it switches artifactory offline"(){
    when:
    Artifactory arti = Mock(Artifactory)
    arti.system().configuration() >> "<client><offlineMode>false</offlineMode></client>"
    ArtifactoryWorker worker = new ArtifactoryWorker(arti)

    then:
    worker.switchArtifactoryOffline()
}

I keep getting a null on the system() object.  Now, in addition to mocking it out, how do i retrieve the value that the method put into artifactoryClient.system().configuration(XmlUtil.serialize( config )) so i can make sure that it actually did change the value and compiled the xml correctly?  This all seems pretty trivial stuff to me, i can't understand why im having such a problem with it.  Maybe I do need to switch back to mockito.
Ok, after messing around some more, i came up with this, and it seems to work, now back to the statics.....
def "check that it switches artifactory offline"(){
    given:
    Artifactory arti = Mock(Artifactory)
    ArtifactorySystem arti_system = Mock(ArtifactorySystem)

    arti_system.configuration() >> "<client><offlineMode>false</offlineMode></client>"
    arti.system() >> arti_system

    ArtifactoryWorker worker = new ArtifactoryWorker(arti)

    when:
    worker.switchArtifactoryOffline()

    then:
    1 * arti_system.configuration(_ as String) >> {
        def config = new XmlSlurper().parseText(it)
        assert config.offlineMode == true
    }
}

A: Move the mocking statements down into your "then:" block.  Just keep them above the assertion.  The "and:" is what's tripping you up.  Mock callouts belong in the "setup/given" block or the "then" block.
Like so:
def "trying this out"(){
    setup:
    OsImpl os = Mock(OsImpl)

    expect: 'should return a mac os'
    1 * os.isFamily(os.FAMILY_WINDOWS) >> false
    1 * os.isFamily(os.FAMILY_MAC) >> true

    ProjectInfo.operatingSystem(os) == 'mac'
}


text:
Q: How do I fetch specific data when I select an option? MERN Stack I want to make a MERN application for car sales. Every car has its own brand and model. I want that when I select a brand, for example BMW, to get BMW models such as X3, X6, Serie 3 ... When I select Audi, the model should be A6, A5, Audi 80 ... How to do it? How do you make a mongoose model for something like that? Can anyone give me an idea how to do something like that. Nothing comes to mind at the moment.

A: you need to put models under cars in your MongoDb document like below, check below Mongo collection structure.
{
  "_id": {
    "$oid": "6227f6861b3a9764567e8eb3"
  },"cars":[{
    "name": "BWM",
    "Model": ["x1","x2","x3"]
   }]
}

A: might be this Help you. by creating two different schema models.for better data management.
const mongoose = require("mongoose");

const schema = new mongoose.Schema(
  {
    name: {
      type: String,
      index: true
    },
    company: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'company',
      index: true
    },
    type: {
      type: String,
      index: true
    },
    launchDate: {
      type: Date
    },
    variant: {
      type: String
    }
  },
  {
    versionKey: false,
    timestamps: true,
  }
);

module.exports = mongoose.model("models", schema);

const company = new mongoose.Schema(
  {
    name: {
      type: String,
      index: true
    }
  },
  {
    versionKey: false,
    timestamps: true,
  }
);

module.exports = mongoose.model("company", company);


text:
Q: Passing partial column names to function I am looking to use a function to speed up a data cleaning process. In the example shown I am looking to remove values reported in the am and pm columns if the ".no" column for that day has a value of 1.
df1 = data.frame (identifier = c(1:4),
                  mon.no = c(1,NA,NA,NA),mon.am = c(2,1,NA,3),mon.pm = c(3,4,NA,5),
                  tues.no = c(NA,NA,1,NA),tues.am = c(2,3,1,4),tues.pm = c(3,3,2,3))
I envisage using a function uses the day to clean the data:
clean1 = function (day) {
df1$day.am[df1$day.no==1] = NA
df1$day.pm[df1$day.no==1] = NA
return (df1)}
df2 = clean1(mon)

However this returns the following error.
Error in `$<-.data.frame`(`*tmp*`, "day.am", value = logical(0)) :
replacement has 0 rows, data has 4

I assume that this is because the function expects a full column name and cannot fill in the gaps around a text input? Is it possible to use a function in that way?
Having read these notes I think that it would be better practice to have my data in a tidy format and am working on a solution which involves reorganising my data. However it would also be handy to be able to do this while the data is in it's original format.
Thanks.

A: You're really close. @Tyler Rinker in comments has explained why it doesn't work. Here's a fix:
clean1 = function (day) {
  day.am = paste(day, "am", sep=".") # make a string from the variable day and the suffixes
  day.pm = paste(day, "pm", sep=".")
  day.no = paste(day, "no", sep=".")
  df1[day.am][df1[day.no]==1] = NA
  df1[day.pm][df1[day.no]==1] = NA
  return (df1)}

df2 = clean1("mon")   # "mon" should be a string

Somebody else might offer more efficient ways of doing this. Note that you're only ever working from your original df1 here. If you now run
df3 = clean1("tues")

you won't get a dataframe with both days cleaned. You could fix this by supplying the dataframe to be acted on to the function too:
clean2 = function(df, day){...


text:
Q: C++ VIDEOHDR to Image File in capVideoStreamCallback I've been working on a Webcam video recorder and I got interested in trying everything when it comes to this topic but there's this problem that I can't solve.
Everything that you might wonder about can be found here
https://msdn.microsoft.com/en-us/library/windows/desktop/dd757677%28v=vs.85%29.aspx and here
https://msdn.microsoft.com/en-us/library/windows/desktop/dd757694%28v=vs.85%29.aspx
Now, in this code
if (capSetCallbackOnVideoStream(hCapWnd, capVideoStreamCallback))
{
    capCaptureSequenceNoFile(hCapWnd); //Capture
}

I make sure that every frame that gets captured is sent to capVideoStreamCallback.
Now what I'm trying to do is transform a frame to an image and save it somewhere, this might be useless but it's interesting and it is surely possible.
Here is my capVideoStreamCallback function (it's commented):
LRESULT CALLBACK capVideoStreamCallback(HWND hWnd, LPVIDEOHDR lpVHdr)
{
    BYTE *Image;
    BITMAPINFO * TempBitmapInfo = new BITMAPINFO;
    ULONG Size;

    // First we need to get the full size of the image
    Size = capGetVideoFormat(hWnd, TempBitmapInfo, sizeof(BITMAPINFO)); //header size
    Size += lpVHdr->dwBytesUsed; //bytes used

    Image = new BYTE[Size];
    memcpy(Image, TempBitmapInfo, sizeof(BITMAPINFO)); //copy the header to Image

    // lpVHdr is LPVIDEOHER passed into callback function.
    memcpy(Image + sizeof(BITMAPINFO), lpVHdr->lpData, lpVHdr->dwBytesUsed); //copy the data to Image

    //write the image
    ofstream output("image.dib", ios::binary);
    for (int i = 0; i < Size; i++)
    {
        output << (BYTE)Image[i];
    }
    output.close();

    return (LRESULT)TRUE;
}

So, the information about every frame that gets sent to capVideoStreamCallback can be found in lpVHdr which is a structure (https://msdn.microsoft.com/en-us/library/windows/desktop/dd757688%28v=vs.85%29.aspx) and what I'm trying to do here is to take that information and transform it to an image.
I first start by getting the full size of the image by retrieving the size of the header and the size of the data and then I dynamically declared a BYTE Array called Image and copied the header and the data to Image using memcpy. I finally used ofstream to write the bytes to a file and that's pretty much it.
The problem is that everything works just fine but the image is somehow corrupted because it cannot be opened.
What is wrong in what I'm doing? It seems so logical but it's not working.
Please share your ideas and thanks for reading.

A: Here's the answer thanks to Frankie-C from http://codeproject.com who reminded me that I needed a BITMAPFILEHEADER structure at the top of the BITMAP File.
There's also few extra stuff that you need to do to get the image to show up the way it should be such as flipping bytes to get BGR instead of RGB etc, here's a nice tut explaining that: http://tipsandtricks.runicsoft.com/Cpp/BitmapTutorial.htm


text:
Q: MS ACCESS Compact and Repair using Python is giving the error file can not open exclusively I tried the following script but that is giving me the error

IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
  pywintypes.com_error: (-2146959355, 'Server execution failed', None, None)

objAccess = win32com.client.Dispatch("Access.application")
objAccess.compactRepair(srcDB, destDB)

Can anybody help me with this please.

A: To open the database in exclusive mode, you need to change "/" to "backslash" \ in the path:
path_bdd_access = path_bdd_access.replace('/', chr(92))


text:
Q: How to convert jiffies to percentages from virt plugin i have installed collectd on our compute node. and enabled virt plugin inside it. we push the result to influxdb. we try to get the instance CPU utilization to be displayed inside grafana. however, we can see the output is using jiffies. Can anyone advise, how can we display correctly the graph in percentage instead of jiffies.
thanks.

A: Just use a visualisation which does a derivative


text:
Q: JQuery: different versions clashing - is there a way I can isolate the versions? on my site I am using a few of the newish JQuery UI controls like the datepicker and dialog.
I recently found a cool project online showing how to make the google dashboard, which is also used on the bbc.co.uk website.
This allows the user to have widgets that move around nicely when selected.
I created a test solution, it worked.
When I integrated it into my exisitng solution with currect Jquery controls and versions it causes a number of errors shown in firebug.
These are:
$("#menu").mouseleave is not a function
$('#menu').mouseleave(function() {

for this piece of code:
    $('#menu').mouseleave(function() {
        setSubItemVisibility();
    });

for the datepicker JQuery ui control:
$(".startdate").datepicker is not a function
$(".startdate").datepicker({ dateFormat: 'dd/mm/yy' });

for the dialog:
$("#inputupdatecontrol").dialog is not a function
position: 'top center'

These all work fine until I put in the inettuts with cookies dashobard solution in found here: http://james.padolsey.com/javascript/inettuts-with-cookies/
This includes the following JQuery versions and files:
jquery-1.2.6.min.js
jquery-ui-personalized-1.6rc2.min.js
cookie.jquery.js
inettuts.js

Is there any way I can seperate the functionality that comes with these files from my existing JQuery versions?
I am currently using the latest Jquery version out and have no problems, its only when i add this functionality from the old versions that I face problems.
I am only using this old version of Jquery on one page, but ofcourse the new versions are needed to.
Cheers

A: Okay here is the full pattern, put the following in:
<script src="jQuery1.3.js"></script>
<script>
    jq13 = jQuery.noConflict(true);
</script>
<script src="jQuery1.3.1.js"></script>
<script>
    jq131 = jQuery.noConflict(true);
</script>

<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>

The variables jq13 and jq131 would
  each be used for the version-specific
  features you require.

Jquery in the command above returns a reference to its self essentially 'boxing' it in another variable.
So to call a function on 1.3 you would call
jq13('#'+ myId).bind('onclick',function(){});

NOTE : You must load the first version of javascript that was developed last.

A: Yes you can use jQuery.noConflict.


text:
Q: how to give two different date to same query in php? I have two date format one is 2013-01-01 to 2013-01-10 and i have time two time one is 20:00:00 to 23:59:59 and 00:00:00 to 07:00:00 and i am using the for loop for iteration start date to end date and i expect  the following
query:
select * from user where login >='$starttime' and logout <='$endtime' and  date='$StartDate';

Expect Result:
select * from user where login >='20:00:00' and logout <='23:59:59' and  date='2013-01-01';
select * from user where login >='00:00:00' and logout <='07:00:00' and  date='2013-01-02';

how to use if condition to get the expect result

A: select * from user where (login >='20:00:00' and logout <='23:59:59' and  date='2013-01-01') OR (login >='00:00:00' and logout <='07:00:00' and  date='2013-01-02');

if the times are identical but you need this for a range of date:
SELECT * FROM `user`
WHERE `login` >='20:00:00' AND `logout` <='23:59:59' AND  `date` between '2013-01-01' AND '2013-01-02';


text:
Q: Extract two lines following a line with a specific value I have a text file and I would like to extract the two lines of data following a line containing only "Name" as a value.

Name
032
Express intent to engage in diplomatic cooperation (such as policy
support)
Description
Name
033
Express intent to provide material aid, not specified below
Description

So, the output from above would be a file that has:

032 Express intent to engage in diplomatic cooperation (such as policy support)
033 Express intent to provide material aid, not specified below

A: awk '/Name/ { readline; num=$0; readline; print num, $0; }' < inputfile

readline reads the next line of the input into $0. So when Name is matched, it reads the next line, puts it into the num variable, then reads the second line, and then prints num and that line together on one line.


text:
Q: Tips to organize a successful math workshop I am a PhD student from India working on representations of quantum groups. I want to organize a workshop on Hopf Algebra and Quantum groups but there are only 2 or 3 specialists in India currently working on it. So I googled some professors outside India who are currently working on this field. Now the problem is how to approach them   to participate as a speaker. Since I have no experience organizing such a workshop I want some help. I donot know what offers I have to make to them. I mean giving air fares both ways and lodging and broading will be enough or do I need to arrange some honorarium. Also there is another problem. To propose a workshop, I have to give details of the speakers, the topics they are covering and outcome of the proposed workshop. After recieving all the data the working committee is either going to accept or reject the proposal. If they accept it then they are going to give the funding. Now it may happen that the funds given may not be enough or in  worse case they can reject the proposal. Now if some professor gets interested at the prospect and later find that the proposal is rejected, what they will think about me.
So I will be very grateful if someone comes up some piece of advise how to proceed.

A: The Lorentz Center has some advice that you might find useful, I have organized several workshops there and followed a route similar to the one you describe.
Tentative answers to your specific questions:

*

*Since you can only invite speakers conditional on the acceptance of the workshop proposal, it is crucial that you invite them well in advance, so that they can block their calendar without interfering with other commitments. I would invite at least a year in advance --- of course now with COVID a two-year advance seems more reliable. Don't worry about "what they will think of me" if the proposal gets rejected: if you explain in advance that the invitation depends on the acceptance by some agency they will understand.

*I would initially offer to reimburse "local expenses" (= hotel and meals) and explain that you have some funds for travel expenses which you can distribute according to need. Some speakers may be able and willing to use their own funds for travel. You could further motivate this by explaining that if speakers can help in this way with the expenses you will be able to support junior participants.

*Honorarium? No, for academic lectures that is unusual and not needed --- at least not for lectures delivered "in real life". The idea being that the hospitality which the host will offer (e.g. taking you out to a nice restaurant) is sufficient compensation. Since COVID I have seen a modest honorarium (a few hundred $) being offered for online lectures, mainly to secure commitment from the speaker.


text:
Q: Which filter to use when in case of sensor fusion? I'm trying to fuse GPS and Accelerometer data to estimate position and velocity using the motion equation

x = x' + vdt + 0.5dt^2.

So far, from what I've read it seems like Kalman Filter is the popular option - (1, 2, 3).
However, it seems like Kalman Filter is used when the system is linear.
Isn't the equation of motion non-linear because it's

dt^2?

Shouldn't they be using EKF/UKF? If not, can you please explain why? I'm confused. Thanks!

A: To specify a setup for kalman filtering you need to specify what you want to estimate ('the states') and what you are going to measure ('the observations'). In addition you need to say how the observations depend on the states, that is you need to express the observations as functions of the states, and how to carry the states forward in time, that is you need to express the states at a later time as functions of the states at a earlier time. When talking about the linearity or otherwise of a filter what is being referred to is whether these two sets of equations (the observation equations and the prediction equations) are linear or not. That is, what matters is whether the observations are linear functions of the states, and whether the future states are linear functions of previous states. How either the states or the observations depend on time is irrelevant.
As a toy example suppose we had a 1d system, and could measure position P and accelaration A. As states we could take the position p, velocity v and accelaration a. Then the
observation equations are extremely simple:
P = p
A = a

The prediction equations are only a little more complex: On the left (with ') we have the predicted states at a time t greater than the time of the previously estimated states
p' = p + t*v + 0.5*t*t*a
v' = v + t*a
a' = a

Since each of these sets of equations are obviously linear in p,v and a, the system is linear.
However a real (3d) system could be significantly more complex. For example it could be that the readings from the accelerometers are relative to a coordinate frame fixed in the body, while the position (and velocity, if available) are relative to an entirely different coordinate frame. You will need to be able to relate these two frames. It may be that measurements, of say pitch roll and yaw, are available, and you could introduce new 'attitude' states; however it is likely that both the observations and predictions will then be non-linear functions of the states.

A: It's a linear system because the position can be expressed as multiply of matrices.


text:
Q: Fsck does not work Fsck isn't doing its job here. When I try running it, I get a

(No such file or directory) while executing fsck.ext2 for /dev/nve1n1p3.

What should I do?

A: At the initramfs prompt, type:
fsck -f /dev/nvme1n1p3


text:
Q: javascript constructor with optional parameters I am learning Javascript now and coming from the background of Java. In Java we have overloaded constructors wherein, at compile time, the compiler will decide which version of constructor to be called.
In case of Javascript, we can have only one constructor. In this case, if the constructor has 3 arguments, how to pass only the third parameter.
Ex:
class Addition {
 constructor(a,b,c){
   console.log(a+B+c);
 }
}

Addition obj = new Addition(null, 40, null);
//or
Addition onj2 = new Addition(undefined, undefined, 45);

Is there a better way to do this in Javascript?

A: There is no possibility of overloading in JS, but you can work with Object destructuring. They can even be complex and refer to other default parameters, like:

function rangeMessage({from=1, to=from+1, message=(counter) => `Hello ${counter}`}={}) {
  for(from; from <= to; from++) {
    console.log(message(from));
  }
}

rangeMessage({from: 10, to: 20});
rangeMessage({to: 10, message:(counter) => `Bye ${counter}`})
rangeMessage()

function sumABC({a=null, b=null, c=null}={}) {
  let result = 0;
  if(a) result += a;
  if(b) result += b;
  if(c) result += c;
  return result;
}

console.log(sumABC());
console.log(sumABC({a:10}));
console.log(sumABC({b:5}));
console.log(sumABC({b: 10, c: 5}));

The {} = {} part does the same as the other destructuring assignments - if no object was passed in, assume an empty object (which is then filled by the object destructuring statements from the left side).

A: You may use EcmaScript's parameter destructuring with default values to achieve that. Additionally, you need to use const (or let, or var) keyword to create variables.

class Addition {
  constructor({a = 0, b = 0, c = 0}) {
    console.log(a + b + c);
  }
}

const obj = new Addition({a: null, b: 40, c: null});
const onj2 = new Addition({c: 45});

A: I hope this solved you question :D

class Addition {
 constructor(a=null,b=null,c=null){
   console.log(a+b+c);
 }
}

var obj = new Addition(null, 40, null);
var onj2 = new Addition(undefined, undefined, 45);


text:
Q: Reusing slot numbers in Linux software RAID arrays When a hard disk drive in one of my Linux machines failed, I took the opportunity to migrate from RAID5 to a 6-disk software RAID6 array.
At the time of the migration I did not have all 6 drives - more specifically the fourth and fifth (slots 3 and 4) drives were already in use in the originating array, so I created the RAID6 array with a couple of missing devices. I now need to add those drives in those empty slots. Using mdadm --add does result in a proper RAID6 configuration, with one glitch - the new drives are placed in new slots, which results in this /proc/mdstat snippet:
...
md0 : active raid6 sde1[7] sdd1[6] sda1[0] sdf1[5] sdc1[2] sdb1[1]
      25185536 blocks super 1.0 level 6, 64k chunk, algorithm 2 [6/6] [UUUUUU]
...

mdadm -E verifies that the actual slot numbers in the device superblocks are correct, yet the numbers shown in /proc/mdstat are still weird.
I would like to fix this glitch, both to satisfy my inner perfectionist and to avoid any potential sources of future confusion in a crisis. Is there a way to specify which slot a new device should occupy in a RAID array?
UPDATE:
I have verified that the slot number persists in the component device superblock. For the version 1.0 superblocks that I am using that would be the dev_number field as defined in include/linux/raid/md_p.h of the Linux kernel source. I am now considering direct modification of said field to change the slot number - I don't suppose there is some standard way to manipulate the RAID superblock?
UPDATE 2:
To modify the slot assignments in the device superblock I would need to do the following:

*

*Modify dev_number

*Modify the dev_roles array to mark the old slot as empty and place the proper role at the new slot

*Re-compute the superblock checksum

(1) and (2) are relatively simple and can be automated via a script or small program. (3) started to push things a little - I would have to rip the superblock checksum code from the md driver, modify it to work with a userspace program and hope for the best.
Rather than spend my time debugging a C application and risk killing my arrays with a bug, I decided to try to trick md/mdadm into doing my work for me, as mentioned in my answer. This seems to have worked, although it may still have a degree of risk...