text:
Q: data.table: How do I pass a character vector to a function get data.table to treat its contents as column names? Here is a data.table:
library(data.table)
DT <- data.table(airquality)

This example produces the output I want:
DT[, `:=`(New_Ozone= log(Ozone), New_Wind=log(Wind))]

How can I write a function log_those_columns such that the following code snippet outputs the same result?
old_names <- c("Ozone", "Wind")
new_names <- c("New_Ozone", "New_Wind")
log_those_columns(DT, old_names, new_names)

Note that I need old_names and new_names to be flexible enough to contain any number of columns.
(I see from the similar StackOverflow questions on this topic that the answer probably involves some combination of .SD, with=F, parse(), eval(), and/or substitute(), but I can't seem to nail which of those to use and where).

A: Picking up MichaelChirico's comment, the function definition can be written as:
log_those_columns <- function(DT, cols_in, cols_new) {
  DT[, (cols_new) := lapply(.SD, log), .SDcols = cols_in]
}

which returns:
log_those_columns(DT, old_names, new_names)
DT

     Ozone Solar.R Wind Temp Month Day New_Ozone New_Wind
  1:    41     190  7.4   67     5   1  3.713572 2.001480
  2:    36     118  8.0   72     5   2  3.583519 2.079442
  3:    12     149 12.6   74     5   3  2.484907 2.533697
  4:    18     313 11.5   62     5   4  2.890372 2.442347
  5:    NA      NA 14.3   56     5   5        NA 2.660260
 ---
149:    30     193  6.9   70     9  26  3.401197 1.931521
150:    NA     145 13.2   77     9  27        NA 2.580217
151:    14     191 14.3   75     9  28  2.639057 2.660260
152:    18     131  8.0   76     9  29  2.890372 2.079442
153:    20     223 11.5   68     9  30  2.995732 2.442347

as expected.
A more flexible approach
The function used to transform the data can be passed as a parameter as well:
fct_those_columns <- function(DT, cols_in, cols_new, fct) {
  DT[, (cols_new) := lapply(.SD, fct), .SDcols = cols_in]
}

The call:
fct_those_columns(DT, old_names, new_names, log)
head(DT)

works as expected:

   Ozone Solar.R Wind Temp Month Day New_Ozone New_Wind
1:    41     190  7.4   67     5   1  3.713572 2.001480
2:    36     118  8.0   72     5   2  3.583519 2.079442
3:    12     149 12.6   74     5   3  2.484907 2.533697
4:    18     313 11.5   62     5   4  2.890372 2.442347
5:    NA      NA 14.3   56     5   5        NA 2.660260
6:    28      NA 14.9   66     5   6  3.332205 2.701361

The function name can be passed as character:
fct_those_columns(DT, old_names, new_names, "sqrt")
head(DT)

   Ozone Solar.R Wind Temp Month Day New_Ozone New_Wind
1:    41     190  7.4   67     5   1  6.403124 2.720294
2:    36     118  8.0   72     5   2  6.000000 2.828427
3:    12     149 12.6   74     5   3  3.464102 3.549648
4:    18     313 11.5   62     5   4  4.242641 3.391165
5:    NA      NA 14.3   56     5   5        NA 3.781534
6:    28      NA 14.9   66     5   6  5.291503 3.860052

or as an anonymous function:
fct_those_columns(DT, old_names, new_names, function(x) x^(1/2))
head(DT)

   Ozone Solar.R Wind Temp Month Day New_Ozone New_Wind
1:    41     190  7.4   67     5   1  6.403124 2.720294
2:    36     118  8.0   72     5   2  6.000000 2.828427
3:    12     149 12.6   74     5   3  3.464102 3.549648
4:    18     313 11.5   62     5   4  4.242641 3.391165
5:    NA      NA 14.3   56     5   5        NA 3.781534
6:    28      NA 14.9   66     5   6  5.291503 3.860052

An even more flexible approach
The function below derives the names of the new columns by prepending the names of the input columns with the name of the function automatically:
fct_those_columns <- function(DT, cols_in, fct) {
  fct_name <- substitute(fct)
  cols_new <- paste(if (class(fct_name) == "name") fct_name else fct_name[3], cols_in, sep = "_")
  DT[, (cols_new) := lapply(.SD, fct), .SDcols = cols_in]
}

DT <- data.table(airquality)
fct_those_columns(DT, old_names, sqrt)
fct_those_columns(DT, old_names, data.table::as.IDate)
fct_those_columns(DT, old_names, function(x) x^(1/2))
DT

     Ozone Solar.R Wind Temp Month Day sqrt_Ozone sqrt_Wind as.IDate_Ozone as.IDate_Wind x^(1/2)_Ozone x^(1/2)_Wind
  1:    41     190  7.4   67     5   1   6.403124  2.720294     1970-02-11    1970-01-08      6.403124     2.720294
  2:    36     118  8.0   72     5   2   6.000000  2.828427     1970-02-06    1970-01-09      6.000000     2.828427
  3:    12     149 12.6   74     5   3   3.464102  3.549648     1970-01-13    1970-01-13      3.464102     3.549648
  4:    18     313 11.5   62     5   4   4.242641  3.391165     1970-01-19    1970-01-12      4.242641     3.391165
  5:    NA      NA 14.3   56     5   5         NA  3.781534           <NA>    1970-01-15            NA     3.781534
 ---
149:    30     193  6.9   70     9  26   5.477226  2.626785     1970-01-31    1970-01-07      5.477226     2.626785
150:    NA     145 13.2   77     9  27         NA  3.633180           <NA>    1970-01-14            NA     3.633180
151:    14     191 14.3   75     9  28   3.741657  3.781534     1970-01-15    1970-01-15      3.741657     3.781534
152:    18     131  8.0   76     9  29   4.242641  2.828427     1970-01-19    1970-01-09      4.242641     2.828427
153:    20     223 11.5   68     9  30   4.472136  3.391165     1970-01-21    1970-01-12      4.472136     3.391165

Note that x^(1/2)_Ozone is not a syntactically valid name in R and needs to be put in backquotes:
DT$`x^(1/2)_Ozone`

A: you only need to write a function:
log_those_columns <- function(D,old_names,new_names)
DT[,(new_names) := lapply(mget(old_names),log)]
log_those_columns(DT,old_names,new_names)
DT
     Ozone Solar.R Wind Temp Month Day New_Ozone New_Wind
  1:    41     190  7.4   67     5   1  3.713572 2.001480
  2:    36     118  8.0   72     5   2  3.583519 2.079442
  3:    12     149 12.6   74     5   3  2.484907 2.533697
  4:    18     313 11.5   62     5   4  2.890372 2.442347
  5:    NA      NA 14.3   56     5   5        NA 2.660260
 ---


text:
Q: Mathematics: A Spectacular Sport. Are there (unscripted) vlogs of people actually doing mathematics?
Are there vlogs of people regularly attempting to solve mathematics problems, warts & all?

I haven't found any.
I know of puzzle-attempt YouTube channels, like  CanChrisSolve?, so why aren't there mathematics problem solving vlogs?
What I'm not looking for are channels like LetsSolveMathProblems; such channels are great but they're too scripted, focusing on the finished product rather than the process of solving a mathematical problem.
I want to see the mistakes, the experiments, the dead ends; swearing, blaspheming, gesticulating; the banging of heads against walls and the a-ha! moments of fleeting insight. I want a stream of consciousness.
"Solving a good mathematics problem could take weeks or even months of effort," I hear you object. That's no obstacle, though, really, since ongoing projects from elsewhere, like Wintergatan's Marble Machine X, have strong followings and considerable longevity. There's practically nothing a little montage can't fix.
A hypothetical example of how an episode might start would be something like this:

Hi, so today I'm going to try & prove that the product of $n$ consecutive integers is always divisible by $n!$. Let's jump straight into it.
Okay, so, my initial thoughts are that it has something to do with how multiples of $k$ for each $k$ from $1$ to $n$ are . . . Erm . . . "distributed". There's a multiple of $k$ every $k$ integers, so $n$ consecutive integers must have a multiple of $k$ for a given $k$ from $1$ to $n$, right? Right.
But there's a tricky issue of whether or not one counts such a multiple twice in the factorial. For instance, in $4\times 5\times 6$, divisible by $3!$, we have that $6$ is both a multiple of $2$ and a multiple of $3$, but there's another multiple of $2$ - namely, $4$ - and what I need to do . . . I think . . . is to show that there's always a number, like $4$, that's a . . . Erm . . . "sensible alternative" to some other number, like $6$, or that the overlap doesn't matter. Does that make sense? I'm not sure.
F¥¢k.

You get the idea: each episode a soliloquy of problem solving, filmed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix: Cannot create property 'header' on string I'm trying to create a pdf using jspdf from json data. But it is causing an error which i'm not able to understand. Please help me solve the issue.
Data:
fileDataSpecific = [{ Date: "01/Jan/2019",
    ServerName: "prlhpcms01",
    ServerRequest: "Front End License returned",
    ServerStatus: "57 timed out",
    Time: "01:03:32",
    UserName: "root",
    srno: 1 }]

displayColumns = [
    { "val": "srno", "col": "Sr. No." },
    { "val": "ServerName", "col": "Server Name" },
    { "val": "UserName", "col": "User Name" },
    { "val": "Date", "col": "Date" },
    { "val": "Time", "col": "Time" },
    { "val": "ServerRequest", "col": "Server Request" },
    { "val": "ServerStatus", "col": "Server Status" }];

My function:
PrintData() {
    var pdfData = this.fileDataSpecific
    var pdfCol = this.displayedColumns
    var doc = new jsPDF()
    var col = [], row = []
    pdfCol.forEach(element => {
      col.push(element.col)
    });
    pdfData.forEach(element => {
      var tempArray = []
      pdfCol.forEach(element1 => {
        tempArray.push(element[element1.val])
      });
      row.push(tempArray)
      tempArray = []
    });
    doc.autoTable(col, row);
    doc.save('Test.pdf');
  }

Error:

Please someone help! Thanks.

A: You need treat your var pdfData = this.fileDataSpecific as array var pdfData = [this.fileDataSpecific]

fileDataSpecific = { Date: "01/Jan/2019",
    ServerName: "prlhpcms01",
    ServerRequest: "Front End License returned",
    ServerStatus: "57 timed out",
    Time: "01:03:32",
    UserName: "root",
    srno: 1 }

let displayedColumns = [
    { "val": "srno", "col": "Sr. No." },
    { "val": "ServerName", "col": "Server Name" },
    { "val": "UserName", "col": "User Name" },
    { "val": "Date", "col": "Date" },
    { "val": "Time", "col": "Time" },
    { "val": "ServerRequest", "col": "Server Request" },
    { "val": "ServerStatus", "col": "Server Status" }];

function PrintData() {
    var pdfData = [fileDataSpecific]
    var pdfCol = displayedColumns
    //var doc = new jsPDF()
    var col = [], row = []
    pdfCol.forEach(element => {
      col.push(element.col)
    });
    pdfData.forEach(element => {
      var tempArray = []
      pdfCol.forEach(element1 => {
        tempArray.push(element[element1.val])
      });
      row.push(tempArray)
      tempArray = []
    });
    console.log(row)
    //doc.autoTable(col, row);
    //doc.save('Test.pdf');
  }

  PrintData();


text:
Q: Is there a length limitation of qDebug()< In my code, I found one qDebug()<<s; didn't output the content given to it. It's very strange, so I output s.length(). It says 135254, so I'm wondering whether there is a limitation of length which is shorter than 135254? I have read the source header and do not find the result.

A: i noticed something similar...
This might narrow it down a bit (using Qt 5.5.1 with Windows mingw):
45000 character trace did not show up in qDebug.
10000 character trace did show up in qDebug.
I was able to qDebug my 45000 characters as 5 separate qDebug calls, each was something like this:
qDebug()<<foo.mid(20000, 10000);

then piece them together in a text editor.
it may have been a little nicer to use qDebug's noQuotes feature too, but i don't need to run my script again today so I'm not prettying it up right now.


text:
Q: Current object value in jquery All,
in the below code How to edit the current added value.i.e, in the edit function how to get the value in td .Also how can we check for duplicates.

A: First off: you're mixing clunky inline onXXX handlers with more elegant jQuery event handlers. Why?
As for your "how to get the value in td" question: your edit(obj) will get the image passed as as the obj parameter, since the onclick is on the img element. You can find the container td like this: var td = $(obj).closest('td'). Then get its .text() or whatever you want.
But again: you could do this better using live binding.


text:
Q: Python, How to download images from yandex and google I found this "https://github.com/hardikvasa/google-images-download" and i'm usually using it with -u url link, but how i can make it download related images in each images result ? Each images in result have 7 related images when you clicked on it and 6 related images on yandex.
i'm looking for a solution to download(or get direct link) all images + related images with provided image search link (google/yandex)
Thank


text:
Q: software for ssrs security and for subscription? Could anyone suggest me software to manage security and subscriptions for SSRS reports. I have been searching google to find any software but no luck. any help would be much appreciate.
Thanks.

A: That is what the Report Manager is for...
Go to http://<servername>/reports and you will be able to set up your report subscriptions and the security profiles for who can access what based on your Active Directory accounts.


text:
Q: How can I bring back my world clock widget? I love my world clock widget, but today I don't see it. How can I bring it back?

A: Go to System Preferences → Extensions and click on 'Today' to see the World Clock widget.  Make sure it has a check next to it.  When you go back to Notification Center, you should see the clock.
I've had problems where some of my widgets would disappear for no obvious reason.  I don't know why this happens but I always end up going back to Extensions to add them back.


text:
Q: attribute extraction using Xpath I have an XML as Java String:
String abc = "<Tags  Value = '635' Type = 'Number'/>";

I am trying to extract the Value of such an XML object using Xpath
What I tried until now is something like this:
InputSource doc = new InputSource(abc);
XPath xPath =  XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile("/Tags[@Value]");
System.out.println(expr.evaluate(doc));

A:  InputSource doc = new InputSource(abc);
 XPath xPath =  XPathFactory.newInstance().newXPath();
 XPathExpression expr = xPath.compile("/Tags/@Value");
 System.out.println(expr.evaluate(doc));

A: try it
public class Example {

    public static void main(String[] args) throws FileNotFoundException, XPathExpressionException {
        String abc = "<Tags  Value = '635' Type = 'Number'/>";
        InputSource doc = new InputSource(new StringReader(abc));
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = xPath.compile("/Tags/@Value");
        System.out.println(expr.evaluate(doc)); // 635
    }

}


text:
Q: Angular UI-Grid How to filter by display value instead of actual value? I have a gender column in my grid and its actual value is a integer and it gets transformed into strings such as Male, Female etc... Filtering won't work if I try to filter it by the text, filtering by actual integer value works fine.
How can I filter it by the text that is displayed rather than the value behind the text?
Plunker http://plnkr.co/edit/JgjKWsVWCV7v4hA8mak3?p=preview

Thank you.

A: There is a better way to do this by using the dropdown instead of a textbox. Since you will have male/female as the options you can add a dropdown and use that to filter.
http://ui-grid.info/docs/#/tutorial/103_filtering has that approach clearly explained.
But if you really want to search based on a textbox input, you can as well do that using a condition property on the filter. This function will compare the values in the textbox with the values in the cells, but you can reverse lookup the male/female values and return true or false.
The example basically has 1 as male and 2 as female.
 { field: 'gender', filter: {
        condition: function(searchTerm, cellValue) {

          if("male".match(searchTerm))
          {
            return cellValue.match(1);
          }
          if("female".match(searchTerm))
          {
            return cellValue.match(2);
          }
          return false;
        }

      },

This plnkr shows that http://plnkr.co/edit/trJeHAG908NiEQM7TXrd?p=preview


text:
Q: Simple ASP Query Question How can I make the SelectCommand use a textbox from the default page so that I can add that to the where clause? Please include an example I am new to programming and it helps me understand the concept better. thanks in advance.

Example WHERE (BADGE = 10000 +
  xBadgeTextBox.Text)?

string Badge = "100000" + Request.Form["xBadgeTextBox"];

 <asp:SqlDataSource ID="Time" runat="server"
         ConnectionString="<%$ ConnectionStrings:Time %>"
         ProviderName="<%$ ConnectionStrings:Time.ProviderName %>"
         SelectCommand="SELECT CLOCK_IN_TIME, CLOCK_OUT_TIME, BADGE FROM CLOCK_HISTORY WHERE (BADGE = 100000342)"> // use the badge number instead.
     </asp:SqlDataSource>

A: You'll want to add parameters to the query and specify them within the SqlDataSource object.  Take a look here:
http://msdn.microsoft.com/en-us/library/z72eefad.aspx
Also, please PLEASE be very careful of SQL injection attacks here.  At some point you may be tempted to just concatenate the string from the textbox to the select command.  Don't :)


text:
Q: What is the best way to replace 2 possible strings with another string? If the string starts with either foo.com or bar.me replace with baz.co. Is this the most efficient / concise way?
string1.replace('foo.com', 'baz.co').replace('bar.me', 'baz.co')

We could have an array of strings: ['foo.com', 'bar.me']

A: You can use a regular expression:
string1.replace(/foo\.com|bar\.me/, 'baz.co')

"Starts with" would require to anchor the expression:
string1.replace(/^(foo\.com|bar\.me)/, 'baz.co')

A: I would suggest the solution of Felix Kling.
A more generalized way to solve such "chained" operations (In case that those can't be expressed with a RegExp) would be to use the Array.reduce functionality:

let string1 = 'bar.me.test'

string1 = ['foo.com', 'bar.me'].reduce((previousValue, valueFromArray) => {
  return previousValue.replace(valueFromArray, 'baz.co')
}, string1);

console.log(string1)

A: I understood you question. You would like to replace a couple of strings in an array with "baz.co". You have two arrays. 1) array with multiple strings. 2) array with string which you will replace (needle). And a string which you use for the replacement.

const arr = ['foo.com', 'bar.me', 'not.re'];
const nee = ['foo.com', 'bar.me']
const rep = 'baz.co'
const n = [];

arr.forEach(i => {
  n.push( nee.includes(i) ? rep : i);
})

console.log(n)


text:
Q: Obtain file name from SetClipboardData hook I used EasyHook to hook into the SetClipboardData() function.
HANDLE mySetClipBoardData (UINT uFormat, HANDLE hMem){
    return SetClipboardData(uFormat, hMem);
    //return NULL;
}

I can either pass the data to the original function or return NULL.
The goal is to prevent the user from copying specific files.
This DLL will be injected into Explorer.exe and will be called whenever a user tries to copy a file.
How to obtain the filename being copied?
Is there any other way to achieve this?

A: Files can be copied/pasted using a number of different clipboard formats, and multiple formats can reside on the clipboard at the same time.

*

*CF_HDROP

*CFSTR_FILECONTENTS

*CFSTR_FILEDESCRIPTOR

*CFSTR_FILENAME

*CFSTR_FILENAMEMAP

*CFSTR_MOUNTEDVOLUME

*CFSTR_SHELLIDLIST

*CFSTR_SHELLIDLISTOFFSET

Refer to Shell Clipboard Formats for specific details about each format.  In particular, see Formats for Transferring File System Objects.
So, you would need something like this:
const UINT ui_CFSTR_SHELLIDLIST = RegisterClipboardFormat(CFSTR_SHELLIDLIST);
const UINT ui_CFSTR_FILENAMEA = RegisterClipboardFormat(CFSTR_FILENAMEA);
const UINT ui_CFSTR_FILENAMEW = RegisterClipboardFormat(CFSTR_FILENAMEW);
...

HANDLE WINAPI mySetClipBoardData (UINT uFormat, HANDLE hMem)
{
    if (!hMem) // DELAYED RENDERING! The real data will come later...
        return SetClipboardData(uFormat, hMem);

    if (uFormat == CF_HDROP)
    {
        LPDROPFILES pDF = (LPDROPFILES) GlobalLock(hMem);
        if (pDF->fWide)
        {
            LPWSTR pFiles = (LPWSTR) (((LPBYTE)pDF) + pDF->pFiles);
            while (*pFiles)
            {
                LPWSTR pFile = pFiles;
                if (pFile refers to the desired file)
                {
                    GlobalUnlock(hMem);
                    SetLastError(...);
                    return NULL;

                    // alternatively, build up a new string to place on the clipboard that omits this file...
                }
                pFiles += (lstrlenW(pFile) + 1);
            }
        }
        else
        {
            LPSTR pFiles = (LPSTR) (((LPBYTE)pDF) + pDF->pFiles);
            while (*pFiles)
            {
                LPSTR pFile = pFiles;
                if (pFile refers to the desired file)
                {
                    GlobalUnlock(hMem);
                    SetLastError(...);
                    return NULL;

                    // alternatively, build up a new string to place on the clipboard that omits this file...
                }
                pFiles += (lstrlenA(pFile) + 1);
            }
        }

        GlobalUnlock(hMem);

        /* alternatively:

        TCHAR szFile[MAX_PATH];
        UINT count = DragQueryFile((HDROP)hMem, (UINT)-1, NULL, 0);
        for (UINT i = 0; i < count; ++i)
        {
            DragQueryFile((HDROP)hMem, i, szFile, MAX_PATH);
            if (szFile refers to the desired file)
            {
                SetLastError(...);
                return NULL;

                // alternatively, build up a new string to place on the clipboard that omits this file...
            }
        }
        */
    }
    else if (uFormat == ui_CFSTR_SHELLIDLIST)
    {
        #define HIDA_GetPIDLFolder(pida) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[0])
        #define HIDA_GetPIDLItem(pida, i) (LPCITEMIDLIST)(((LPBYTE)pida)+(pida)->aoffset[i+1])

        LPIDA pIDA = (LPIDA) GlobalLock(hMem);
        LPCITEMIDLIST pidlParent = HIDA_GetPIDLFolder(pIDA);

        for (UINT i = 0; i < pIDA->cidl; ++i)
        {
            LPCITEMIDLIST pidlFile = HIDA_GetPIDLItem(pIDA, i);

            if (pidlParent+pidlFile refers to the desired file)
            {
                GlobalUnlock(hMem);
                SetLastError(...);
                return NULL;

                // alternatively, build up a new array to place on the clipboard that omits this file...
            }
        }

        GlobalUnlock(hMem);
    }
    else if (uFormat == ui_CFSTR_FILENAMEA)
    {
        LPSTR pFile = (LPSTR) GlobalLock(hMem);
        if (pFile refers to the desired file)
        {
            GlobalUnlock(hMem);
            SetLastError(...);
            return NULL;
        }
        GlobalUnlock(hMem);
    }
    else if (uFormat == ui_CFSTR_FILENAMEW)
    {
        LPWSTR pFile = (LPWSTR) GlobalLock(hMem);
        if (pFile refers to the desired file)
        {
            GlobalUnlock(hMem);
            SetLastError(...);
            return NULL;
        }
        GlobalUnlock(hMem);
    }
    else
    {
        // handle other shell formats as needed...
    }

    return SetClipboardData(uFormat, hMem);
}


text:
Q: mysqli_query() expects parameter 1 to be mysqli, null given in, como resolver? Quero inserir os valores do formulario no banco de dados, porém apresenta o erro.

mysqli_query() expects parameter 1 to be mysqli, null given in

Código linkar php:
<?php
    include_once('_php/conn.php');
    if (isset($_POST['addProdutoVenda'])){
        addProdutoVenda();
    }
?>

Código do formulário:
<form class="formVenda"  method="post">

NOVA VENDA

    Codigo:
    <input required="yes" type="search" name="codigo" list="listaCodigoProduto" placeholder="00000">

    Descrição:
    <input required="yes" type="search" name="descricao" list="listaNomeProduto" placeholder="Camisa Rosa V">

    QTD:
    <input required="yes" type="number" name="quantidade" placeholder="6">

    <input type="submit" name="addProdutoVenda" name="">
</form>

Arquivo PHP conexão e inserção:
<?php

$con = mysqli_connect('localhost','root','','nik') or die(mysqli_error());

function addProdutoVenda(){

$cod = $_POST['codigo'];
$desc = $_POST['descricao'];
$qtd = $_POST['quantidade'];

$sql = "INSERT INTO produtos VALUES";
$sql.= "('$cod', '$desc','$qtd')";

$query = mysqli_query($con, $sql);

}

?>

A: Não possível (nem desejavel) acessar variáveis globais dentro de um função. A funçao addProdutoVenda() não enxerga a variável $con, por isso o erro ( conexão inválida).
Para solucionar isso, passe a conexão como argumento da função:
mude a assinatura para:
function addProdutoVenda($con){

E a chamada deve ser assim:
$con = mysqli_connect('localhost','root','','nik') or die(mysqli_connect_error());
addProdutoVenda($con);

A ideia de criar funções é ter blocos de códigos que possam ser reaproveitados em várias situações, ao utilizar elementos externos ($_POST) dentro sua função fica dependente de um form enviado por post, a sugestão para eleminar essa problema é a mesma, passar o $_POST como argumento.
A função não retorna nenhuma valor nem trata o erro, logo não é possível saber se a operação foi realizada com sucesso ou não.


text:
Q: Realtek HD audio broken? I came here because my Realtek audio won't allow me to use my headphones and my speakers.
I have two audio devices, my speakers and my headphones. My USB dongle for my headphones broke and I had to get a female to male 3.5mm jack to replace the dongle. Now I have two 3.5mm jacks plugged into two ports and Realtek HD audio only recognises it as one device and doesn't allow me to split the audio. My front audio panels don't work for whatever reason. (I've plugged them into the right ports, I believe they are broken. Any help would be appreciated. My drivers are up to date as well.

A: I recommend you use an audio splitter  .
What you try to do is not good for the audio card.


text:
Q: LinkedBlockingQueue and addAll() If an attempt to add a collection to a blocking queue that exceeds the blocking queue's remaining size, what is supposed to happen? This isn't clear from the documentation I've read so far.
     LinkedBlockingQueue<Integer> foo = new LinkedBlockingQueue<Integer>(3);
        foo.add(1);
        foo.add(2);
        LinkedBlockingQueue<Integer> tenElements = new LinkedBlockingQueue<Integer(10);
        for(int i = 0; i < 10; i++)
            tenElements.add(i);

        foo.addAll(collectionWith10elements);

A: The documentation of add() state that an IllegalStateException is thrown if the queue is full:

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

When you try the following code:
public static void main(String[] args) throws Exception {
    ArrayList<Integer> l = new ArrayList<Integer>();
    l.add(10);
    l.add(20);
    l.add(30);
    l.add(40);
    l.add(50);
    LinkedBlockingQueue<Integer> foo = new LinkedBlockingQueue<Integer>(3);
    foo.add(1);
    foo.add(2);
    foo.addAll(l);
}

You will get the following exception:
Exception in thread "main" java.lang.IllegalStateException: Queue full
    at java.util.AbstractQueue.add(AbstractQueue.java:98)
    at java.util.AbstractQueue.addAll(AbstractQueue.java:187)
    at Test.main(Test.java:16)

A: Elements persisted in the queue should be consumed once the capacity reached, otherwise we will get this Exception :-
Exception in thread "main" java.lang.IllegalStateException: Queue full
    at java.util.AbstractQueue.add(AbstractQueue.java:98)
    at java.util.AbstractQueue.addAll(AbstractQueue.java:187)

A: I tested it on my IDE and it got
Exception in thread "main" java.lang.IllegalStateException: Queue full
    at java.util.AbstractQueue.add(AbstractQueue.java:98)
    at java.util.AbstractQueue.addAll(AbstractQueue.java:187)

If you want to learn more, go here.


text:
Q: Python QC field calculator I am new to Python and am trying to run a simple QA/QC on a particular set of fields.
I basically want to verify that fields x and y add up to z, I may have to incorporate rounding since a small difference doesn't make a difference and will throw off my results.  This is what I have currently and it is not processing:
def Qcontrol(check):
  if (!Forest_Acres! + !NonForest_Acres!) = !ACRES!:
     return 0
  else:
    return 1

Qcontrol(!check!)

all fields are double. **Also need to compensate for Nulls in Forest and Non_forest...

A: you need to put all the fields needed for the calculation as arguments. Also the output field does not need to be mentioned and the equality test is ==, not = (which is for setting a value). Finally, verify your indentations, they are of paramount importance in Python (your second "return" was not well indented)
this will look like this
def Qcontrol(f_acre, nf_acre, tot):
    if (f_acre + nf_acre) == tot:
        return 0
    else:
        return 1

called:
Qcontrol(!Forest_Acres!, !NonForest_Acres!, !ACRES!)

A: You could write this to loop through each record in the feature class or table using the following:
import arcpy

# Creates a update cursor
cur = arcpy.UpdateCursor('FEATURE CLASS NAME or TABLE NAME')

# Loops through records
for row in cur:
   # if they are equal (after rounding) - calcs QControl to 0
   if round(row.FOREST_ACRES,0) + round(row.NONFOREST_ACRES,0) == round(row.ACRES,0):
        row.QControl = 0
   # if they are different - calcs QControl to 1
   else:
        row.QControl = 1
   cur.updateRow(row)

A: To handle null values, use this... (Python as parser, no need to use Code Block...)
0 if (!Forest_Acres! or 0 + !NonForest_Acres! or 0) == !ACRES! or 0 else 1


text:
Q: ScrollView Animation and scrolling behavior I share with you the SNACK of the CODE. Please open it because is very difficult to explain the problem, but once you have read the post and try it you have a very clear picture of the problem.
I have different cards displayed in column one after the others.
This means that if the height of the card is 250px the first card start at 0 and end at 250, the second one start at 250 and end at 500 and so on...
I'm refers to this positioning of cards as POSITION 1, you can see the POSITION 1 in this screen
The scroll event fire an animation that translates the cards in a manner that they are partially overlapped.
Specifically the first card start at 0, the second one at 50, the third on at 100 and so on.
This is the POSITION 2, you can see the POSITION 2 in this screen
This is pretty simple result to achieve.
I'have used an Animated Scroll View that are placed on top of my list of cards because List is a component whose style is StyleSheet.absoluteFill
 //other code
 <List array={cards}/>

 <Animated.ScrollView
    scrollEventThrottle={16}
    contentContainerStyle={styles.content}
    showsVerticalScrollIndicator={false}
    onScroll={Animated.event(
    [
     {
       nativeEvent: {contentOffset: { y }}
     }
    ],
    { useNativeDriver: true }
    )}
    >
  </Animated.ScrollView>
  //other code

List component aiming at display the cards and managing the  translation from POSITION 1 to POSITION 2.
This is the general scenario. Now I'll introduce you to the PROBLEM.
User runs the application and the cards are showed in POSITION 1.
In this ways user can see only 2/3 cards.
When user scroll, animation fire, cards are translated in POSITION 2.
In this way user can see more cards, in the image are showed 11 cards.
If I have only 11 cards all is good.
But If I have 12 cards or 100?
User are not able to see them because List is not scrollable.
I have tried to put List inside the Animated.Scrollview in this way
//other code
 <Animated.ScrollView
    scrollEventThrottle={16}
    contentContainerStyle={styles.content}
    showsVerticalScrollIndicator={false}
    onScroll={Animated.event(
    [
     {
       nativeEvent: {contentOffset: { y }}
     }
    ],
    { useNativeDriver: true }
    )}
    >
   <List array={cards}/>
  </Animated.ScrollView>
  //other code

And I obtain  this result
NOW THE PROBLEM:
I want that scroll of the List starts only when a certain amount of cards are in POSITION 2, in this case 11 cards. Why 11? because is the maximum number of the cards that user can see when the cards are in POSITION 2.
For a better understanding of the problem I suggest to you to play with SNACK and ANDROID EMULATOR.


text:
Q: Struts2/Dojo compatibility issues on IE I designed a web app based on struts2. It works well in firefox but doesnt work anymore on the newer versions of IE. I get the following error on a dojo operation. Can anyone help please?
Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0;     SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)
Timestamp: Mon, 19 Nov 2012 08:13:29 UTC
Message: Invalid argument.
Line: 5814
Char: 3
Code: 0
URI: https://mysite.com/myappName/struts     /dojo/struts_dojo.js.uncompressed.js

A: I strongly suggest you to get rid of the Struts2 Dojo plugin, and to use a pure-Dojo library instead.
Struts2 Dojo plugin is:

*

*deprecated since Struts2 2.1.x

*way behind current Dojo releases

*buggy

let's try, you don't have a lot of work to do, just replace the import and see what happens.
Hope that helps.


text:
Q: WooCommerce Variable Products - Can't choose products with '0' as an attribute - Error 'please choose all product options' I've been developing an e-commerce store for a client using WooCommerce and I've come across a very strange issue. All of my products are variable products and I have set them up like this:
Variation 1 - Weight (0,0.5,1.0,1.5,2.0...5.0 in Kgs)
Variation 2 - Units  (0,1,2,3,4,5...10)
Variation 3 - Cut Type (Ground, Slices, Whole etc)
I set the variations in such a way that a customer has to choose either Variation 1 or Variation 2 (weight or in units) and Variation 3. If they choose to purchase a product by Weight (Weight is great than '0') the only choice in 'Units' is 0 and vice versa. This worked for me for a day or two and stopped working, I keep getting an error 'please select product options'..
I then changed the '0' value to 'Zero' and the combination works, has anyone come across this problem before?
I tried to switch to the default theme of WP and shut off all plugins except WooCommerce but nothing works.
Any ideas?
Link to a product page - http://www.best-foods-for-fat-burning.com/wordpress/?product=%D7%90%D7%A1%D7%90%D7%93%D7%95
Thanks,
Ofer

A: This is a bug. I've tested it on several different installation. Using the latest versions of Woocommerce 2.0.20 and WordPress 3.8.1. The best thing to do is add additional info like 0-Kgs to your attribute slug and that solves the problem until woothemes fixes this bug.


text:
Q: Make ComboBox Edit Active When View Is Opened I have a view that opens up on a button click. The view has a combo box that the user is requesting that when the view opens, the combo box is already selected so they don't have to click on it. Is there anyway to achieve this?

A: Are you saying that you would like to have an initial value selected in the ComboBox when you load the view? If you defined your ComboBox with static content, meaning the ComboBox's ItemSource property isn't bound to an object that was constructed using the results of a database query, you could set the IsSelected property of the ComboBoxItem you want selected to true. For example:
If I want to have the apples initially selected in the example below, I could do the following:
<ComboBox Name="fruits" >
   <ComboBoxItem Content="apples" IsSelected="true"/>
   <ComboBoxItem Content="pears"/>
   <ComboBoxItem Content="oranges"/>
</ComboBox>


text:
Q: Azure - Automate service creation Today I stumbled upon an issue with Azure's services: if I ever delete all my services and maybe want to recreate them in another account, how can I do that in a automatic and reliable way? I've seen Azure CLI as an option but it seems very basic, I've researched also the Docker containers which seem a better option but still I wanted to have a better overall view.
Is there a procedure to follow to create X Azure services in a script-like fashion?
Are there any "one-button-click" options or are bash scripts the only option?
Thanks in advance!


text:
Q: Find MAC address of a device on the other end of an Ethernet cable Before anyone points it out, this is a different question to Check MAC address of a device on the other end of an Ethernet cable.
I'm interested in an automated way (rather than Wireshark, etc) of finding only the MAC address of the device on the other end of an ethernet cable, rather than mapping the entire network. Is this even possible?
Update: The scenario is that my user has several boxes running embedded Linux connected to a network along with other equipment. I can figure out how those boxes are connected to each other by detecting the MAC or IP address each one is connected to.

A: Assuming you're talking about doing this from a PC, by looking at the ARP table you should be able to find the MAC address you're looking for. Of course, you also need to know the devices IP address so you're looking at the right one.
The command you want to use in cmd is arp -a


text:
Q: UITableView overlap cells (force) I want to accomplish a table view cell overlap since I want to accomplish this effect:

So basically cells would kind of stack one on another. I'm targeting iOS7+ (currently testing with iOS8).
I'm currently doing a CAGradientLayer which gets positioned in layoutSubviews. I'm positioning it with:
CGRect gradientLayerFrame = self.contentView.bounds;
gradientLayerFrame.origin.y = -6.0f;
gradientLayerFrame.size.height += 6.0f;
self.gradientLayer.frame = gradientLayerFrame;

And I also did the
self.clipsToBounds = NO;
self.contentView.clipsToBounds = NO;
self.contentView.superview.clipsToBounds = NO;

in init so that nothing would clip. Now the cell clips the first time it gets rendered but when I scroll the table view down and then up again so that it displays the cells again they don't get clipped.
I already tried setting backgroundColor to clear in willDisplayCell with no luck. Also tried recursively traversing all of the cells subviews and set clipping to NO but the same thing all over again. Also tried hacking and forcefully setting setNeedsDisplay so that things would re-render but no luck.
Any help on this issue would be much appreciated.

A: It shouldn't be a TableView.
Try this library: TGLStackedViewController

A: I faced the same issue some time back.
The solution that worked for me is using a Collection view instead of a TableView. Create a custom class by extending it from UICollectionViewFlowLayout and use that in your Collection View instead.
class OverlappedCustomFlowLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()

        // This allows us to make intersection and overlapping
        // A negative number implies overlapping whereas positive implies space between the adjacent edges of two cells.
        minimumLineSpacing = -100
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let layoutAttributes = super.layoutAttributesForElements(in: rect)
        for currentLayoutAttributes: UICollectionViewLayoutAttributes in layoutAttributes! {

            // zIndex - Specifies the item's position on the z-axis.
            // Unlike a layer's zPosition, changing zIndex allows us to change not only layer position,
            // but tapping/UI interaction logic too as it moves the whole item.
            currentLayoutAttributes.zIndex = currentLayoutAttributes.indexPath.row + 1
        }
    }

    return layoutAttributes
}

P.S. - As per Apple's developer document of zIndex

This property is used to determine the front-to-back ordering of items
  during layout. Items with higher index values appear on top of items
  with lower values. Items with the same value have an undetermined
  order. The default value of this property is 0.

Hope it helps! :)


text:
Q: Преобразование массива в строку без null элементов Есть класс с полями name, description, String[] comments = new String[10] и т.д.
Как переопределить метод toString таким образом, чтобы избавиться от null значений массива?
@Override
public String toString() {
    return "№: " + getId() + "; " +
            "Имя: " + getName() + "; " +
            "Описание: " + getDescription() + "; " +
            "Время создания: " + getCreate() + "; " +
            "Комментарии: " + Arrays.toString(getComments());
}

При текущей реализации получаем:

№: 1482208198038; Имя: name; Описание: desc; Время создания: 10 01
  2017 10:40:18; Комментарии: [comment, null, null, null, null, null,
  null, null, null, null].

ArrayList не подходит.

A: Воспользуйтесь стримами:
Arrays.stream(getComments())
      .filter(Objects::nonNull)
      .collect(Collectors.joining(", ")

A: можно побороть таким методом:
private String toString(String[] strArray) {
    StringBuilder sb=new StringBuilder();
    int k=0;
    for(int i=0; i < strArray.length; i++) {
      if(strArray[i]!=null) {
         if(k > 0)
           sb.append(", ");
         sb.append(strArray[i]);
         k++;
      }
    }
    return sb.toString();
}


text:
Q: ARR module related error logged in 'Event Viewer' We have an issue on the production site and it throws 500 error. When I checked the 'Event Viewer', I saw the below error logged:-
The description for Event ID 11 from source Microsoft-Windows-IIS-IISManager cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
IISMANAGER_MODULE_INITIALIZATION_THREW_EXCEPTION

The Initialize method for module "Microsoft.Web.Management.WebFarm.WebFarmModule, Microsoft.Web.Management.WebFarmClient, Version=7.1.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" of type "WebFarmFramework" threw an exception.

Exception:System.IO.FileNotFoundException: Could not find file 'Microsoft.Web.Management.WebFarmClient.resources'.
   at System.Reflection.RuntimeAssembly.InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, Boolean throwOnFileNotFound, StackCrawlMark& stackMark)
   at System.Resources.ManifestBasedResourceGroveler.GetSatelliteAssembly(CultureInfo lookForCulture, StackCrawlMark& stackMark)
   at System.Resources.ManifestBasedResourceGroveler.GrovelForResourceSet(CultureInfo culture, Dictionary`2 localResourceSets, Boolean tryParents, Boolean createIfNotExists, StackCrawlMark& stackMark)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo requestedCulture, Boolean createIfNotExists, Boolean tryParents, StackCrawlMark& stackMark)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents)
   at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
   at Microsoft.Web.Management.WebFarm.WebFarmModule.Initialize(IServiceProvider serviceProvider, ModuleInfo moduleInfo)
   at Microsoft.Web.Management.Client.Connection.Initialize(WebManagementInfo webManagementInfo)

Process:InetMgr

The version details are:-
IIS versoin 8.5.9600
ARR 3.0.1750
WebFarm Framework: 1.1.0490
I tried re-installing the ARR module on the server but I do not see the 'Server Farms' node in IIS even after installation.
Can anyone please help?
Thank you

A: The exception seems to imply that the module hasn't been properly installed.  You can install it via the Web Platform Installer, or if your Installer had become corrupt, locate the file on a known good installation and copy it over.
From memory the module is located in C:\windows\system32\inetsrv


text:
Q: Hibernate One Entity Multiple Tables per Country I'm developing a web app, that becouse of legal issues, I have to divide the tables per country.
I can divide by schema such as schema_name will contain data config tables, schema_name_ar will contain AR data, schema_name_ES will contain ES data, etc.
I could also developed to have to name the tables like TABLE_A_ES, TABLE_A_AR, TABLE_A_ZA, etc.
For now there will be no difference in table columns so I want to reuse the entity.
Depending on the user who logs in he will be able to CRUD on specific tables.
Can Hibernate/JPA do this ?
Thanks

A: Unfortunately, there is no such feature in 'pure' JPA.
However, I guess you could implement your requirement using multi-tenancy features provided by some of the persistence providers (EclipseLink: https://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant, Hibernate: https://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch16.html).
Basically, you could use the table-per-tenant approach and treat each country as a separate tenant. You would also need to keep your user entity shared across tenants, and store the tenant identifier alongside other user data.


text:
Q: How to get the average of the last X values? If I have a table with two columns - value and time_stamp - how can I use SQL to get the average of the last X values?
One statement or several, it doesn't matter.
Maybe something like SELECT value FROM table ORDER BY time_stamp DESC LIMIT x ? Then in my program, I could get each value, total them and average them? That's my best guess so far as I am a SQL beginner.
I am aware that SQL can total / average, but I am unsure how to combine that with a request to apply it to the latest X values...

Note to anyone else seeking to do this: in addition to the accepted answer for the last X values, I also found by googling that it is easy to do for a time period, such as a minute or hour, by using something like SELECT AVG(somefield) FROM sometable WHERE datefield BETWEEN '2003-08-10' AND '2003-08-26'.

A: You  use the AVG() aggregate on the result of a subselect which does the initial LIMIT.  Just be sure to substitute the correct LIMIT value for n on the inner query.
SELECT AVG(a.value) AS the_average
FROM (SELECT value FROM tbl ORDER BY time_stamp DESC LIMIT n) a;


text:
Q: Cannot filter on Column in some views of a doc library I have a 2010 site that has a document library with a threshold of 7500 items. The library is currently sitting at over 8000 items, so we have created multiple views that filter on indexed columns.

Each of these views work and return an item amount under the threshold with most returning around 500 items. The issue is, that when I go to filter on a column in the view, I get the following error for only SOME of the views:

I am pretty stumped on this one since there seems to be no consistency on when the error shows. For instance:

*

*View 'Starts with A' returns 538 items in 4 groups (Group By one indexed column), and it receives the error

*View 'Starts with T' returns 2262 items in 4 groups, and does not receive the error

I have compared the working views to the non-working views:

*

*CAML is the same (except for the filter criteria)

*View setup is the same (again, different filter criteria)

Also, there are no lookup fields in the library.
Any help/advice would be appreciated, thanks.


text:
Q: SQL Stored Process: If statement not behaving as expected Attempting to create a stored process for MySQL.  It contains a basic if-statement. The current script is below:
DROP PROCEDURE IF EXISTS sp_pay_raise;

DELIMITER @@
CREATE PROCEDURE sp_pay_raise
     (IN inEmpId INT,
      IN inPercentageRaise DOUBLE(4,2),
      OUT outErrorCode INT)
BEGIN
    IF (@inPercentageRaise <= 0.0) THEN
        SELECT -3 INTO errorCode
    ELSE
        SELECT -2 INTO errorCode
    END IF;
END @@
DELIMITER ;

The above doesn't work as expected.  If I provide a inPercentageRaise which is less than zero, for ex.
CALL sp_pay_raise(0,-1.0, @out)
SELECT @out;

The database shows @out = -2.  Is the if-statement which is written incorrectly?

A: @ is used for Session variables. While inside a stored procedure, you don't need to use @ for the input params. Otherwise, MySQL will look for a similar name pre-defined Session variable. Since it does not find it; it assumes its values as Null
There are other errors also. You have a typo; instead of using outErrorCode param, you are using a different undefined variable errorCode
DROP PROCEDURE IF EXISTS sp_pay_raise;

DELIMITER @@
CREATE PROCEDURE sp_pay_raise
     (IN inEmpId INT,
      IN inPercentageRaise DOUBLE(4,2),
      OUT outErrorCode INT)
BEGIN
    IF (inPercentageRaise <= 0.0) THEN  -- Remove @ from here.
        SELECT -3 INTO outErrorCode  -- It should be outErrorCode instead of errorCode
    ELSE
        SELECT -2 INTO outErrorCode  -- It should be outErrorCode instead of errorCode
    END IF;
END @@
DELIMITER ;


text:
Q: Outlook Web App no longer working after web server rebuilt Recently a server of ours went down and was rebuilt. The server hosted a website, and had links to various resources as well. At the moment, everything seems to be up and the website is accessible, except for one link: on the page is a link that when clicked is supposed to send you to the outlook web app login page. (Exchange is installed onto another server.) Before the server went down the page would load and people could get to their e-mail via the internet. Now, when you click on the page it results in a "server not found: can't find the server at [the website you're on]." However, the outlook office program and email connections on mobile devices like phones and ipads are still working correctly, pointed at that address, "mail.[address]." that address is just not accessible via the internet, and I don't know why.
Any thoughts?
Details: Exchange Server 2010
[Update] When we put in the ip for the server instead of the address name it works.

A: Compare the link (on the webpage) with the actual public URL of your OWA server. If you don't know how to find that, it's in the Exchange Management Console, Exchange Management Shell, or Exchange Control Panel (depending on your version of Exchange, which you didn't tell us.)
You must have the wrong link on the webserver, since the OWA server (presumably a different webserver) is still up and running.

A: From what you've written, it could be that the server has a new ip address and perhaps your DNS has a record for the old OWA host name pointing to an incorrect old static address.
You may also want to check the bindings for the OWA site in IIS to make sure that traffic is being routed correctly, although given you can browse it with an ip address this is unlikely to be the culprit.


text:
Q: Measure script running time in Python I've had this question for a long time, and I have searched for an answer in several places, without success...
My question: How to measure the time that a given script takes to fully complete?
Imagine I had this silly script to calculate the sum of all the numbers from 0 to 10^12:
x = 0
for i in range(pow(10,12)):
    x += i
print(x)

How could I know how much time it took my PC to complete that?
Thanks in advance,
RSerrao

A: I already know you can do one clever thing:
import time
# at the beginning:
start_time = time.time()

# at the end of the program:
print("%f seconds" % (time.time() - start_time))

It is not 100% accurate, but it is quite good for my purposes

A: If you are looking for a useful one-liner and are using IPython then %timeit magic function may be useful (This has not been mentioned on the linked post so adding it for the sake of completeness):
%timeit [x for x in range(1000)]

Gives (on my machine):
10000 loops, best of 3: 37.1 µs per loop

In the case of your script, I would define a function first:
def sumx(y,z):
    x = 0
    for i in range(pow(y,z)):
        x += 1
    print(x)

Then do:
%timeit sumx(5,7)

Which gives:
100 loops, best of 3: 4.85 ms per loop

A: You can use the python profiler cProfile to measure CPU time and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where the bottlenecks are. This answer to another SO question is pretty good. It's always good to have a look in the docs too.
Here's an example how to profile a script using cProfile from a command line:
$ python -m cProfile euler048.py

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}


text:
Q: Testing ejb with stub and openejb framework I am trying to test an EJB that have another one injected in it.
For the tests purpose I want to use a stub for the injected EJB. I had use openEJB as framework for the EJB for the testing.
Here is the EJB :
@Stateless
@Local(IService.class)
public class Service implements IService {

    @EJB
    private IBean bean;

    @Override
    public String doService(String data) {
        return bean.process(data);
    }
}

The real injected EJB :
@Stateless
@Local(IBean.class)
public class Bean implements IBean {

    private static Logger logger = Logger.getLogger(Bean.class);

    @Override
    public String process(String data) {
        logger.info("Bean processing : " + data);
        return "Bean processing : " + data;
    }
}

The stub version of the EJB :
@Stateless
@Local(IBean.class)
public class BeanStub implements IBean {

    private static Logger logger = Logger.getLogger(BeanStub.class);

    @Override
    public String process(String data) {
        logger.info("Stub processing : " + data);
        return "Stub processing : " + data;
    }
}

And the JUnit test used :
public class ServiceTest {

    private static Logger logger = Logger.getLogger(ServiceTest.class);

    private static InitialContext context;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        // openEJB
        Properties p = new Properties();
        p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");
        p.put("openejb.altdd.prefix", "stub"); // use specific ejb-jar
        p.put("openejb.descriptors.output", "true");

        context = new InitialContext(p);
    }

    @Test
    public void testServiceStub() {
        try {
            IService service = (IService) context.lookup("ServiceStubLocal");
            assertNotNull(service);
            String msg = service.doService("service");
            assertEquals("Stub processing : service", msg);
        } catch (NamingException e) {
            logger.error(e);
            fail(e.getMessage());
        }
    }
}

I had try to override the use of the real EJB by the stub one, using a specific ejb-jar (I want to use "BeanStub" instead of default "Bean" in my service) :
 <ejb-jar>
    <enterprise-beans>
    <session id="ServiceStub">
        <ejb-name>ServiceStub</ejb-name>
        <ejb-class>tests.Service</ejb-class>
        <ejb-local-ref>
            <ejb-ref-name>tests.Service/bean</ejb-ref-name>
            <ejb-link>BeanStub</ejb-link>
        </ejb-local-ref>
    </session>
    </enterprise-beans>
</ejb-jar>

Unfortunatly I have a problem the EJB are declared :

    Apache OpenEJB 3.1.4    build: 20101112-03:32
http://openejb.apache.org/
17:14:29,225  INFO startup:70 - openejb.home = D:\Workspace_Java\tests\testejb
17:14:29,225  INFO startup:70 - openejb.base = D:\Workspace_Java\tests\testejb
17:14:29,350  INFO config:70 - Configuring Service(id=Default Security Service, type=SecurityService, provider-id=Default Security Service)
17:14:29,350  INFO config:70 - Configuring Service(id=Default Transaction Manager, type=TransactionManager, provider-id=Default Transaction Manager)
17:14:29,381  INFO config:70 - Found EjbModule in classpath: D:\Workspace_Java\tests\testejb\target\test-classes
17:14:29,412  INFO config:70 - Found EjbModule in classpath: D:\Workspace_Java\tests\testejb\target\classes
17:14:29,428  INFO config:70 - Beginning load: D:\Workspace_Java\tests\testejb\target\test-classes
17:14:29,428  INFO config:70 - AltDD ejb-jar.xml -> file:/D:/Workspace_Java/tests/testejb/target/test-classes/META-INF/stub.ejb-jar.xml
17:14:29,850  INFO config:70 - Beginning load: D:\Workspace_Java\tests\testejb\target\classes
17:14:29,850  INFO config:70 - AltDD ejb-jar.xml -> file:/D:/Workspace_Java/tests/testejb/target/classes/META-INF/stub.ejb-jar.xml
17:14:29,850  INFO config:70 - Configuring enterprise application: classpath.ear
17:14:29,912  INFO config:70 - Configuring Service(id=Default Stateless Container, type=Container, provider-id=Default Stateless Container)
17:14:29,912  INFO config:70 - Auto-creating a container for bean ServiceStub: Container(type=STATELESS, id=Default Stateless Container)
17:14:29,912  INFO options:70 - Using 'openejb.descriptors.output=true'
17:14:29,912  INFO options:70 - Using 'openejb.descriptors.output=true'
17:14:29,928  INFO config:70 - Dumping Generated ejb-jar.xml to: C:\TEMP\ejb-jar-6391test-classes.xml
17:14:29,959  INFO config:70 - Dumping Generated openejb-jar.xml to: C:\TEMP\openejb-jar-6392test-classes.xml
17:14:29,959  INFO options:70 - Using 'openejb.descriptors.output=true'
17:14:29,959  INFO config:70 - Dumping Generated ejb-jar.xml to: C:\TEMP\ejb-jar-6393classes.xml
17:14:29,975  INFO config:70 - Dumping Generated openejb-jar.xml to: C:\TEMP\openejb-jar-6394classes.xml
17:14:30,006  INFO config:70 - Enterprise application "classpath.ear" loaded.
17:14:30,084  INFO startup:70 - Assembling app: classpath.ear
17:14:30,131  INFO startup:70 - Jndi(name=ServiceStubLocal) --> Ejb(deployment-id=ServiceStub)
17:14:30,131 ERROR startup:46 - Jndi name could not be bound; it may be taken by another ejb.  Jndi(name=openejb/Deployment/ServiceStub/tests.IService!Local)
17:14:30,131  INFO startup:70 - Undeploying app: classpath.ear
17:14:30,147 ERROR startup:50 - Application could not be deployed:  classpath.ear
org.apache.openejb.OpenEJBException: Creating application failed: classpath.ear: Unable to bind business local interface for deployment ServiceStub
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:679)
    at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:450)

Is there something wrong in the approach, or in the way to write the ejb-jar ?

A: I had similar problems and hurdles with OpenEJB. If you need stubbing and mocking for tests (who doesn't) have a look who I finally managed to handle it (with a great help from David - OpenEJB co-founder). In the latest version (3.1.4) OpenEJB works pretty much like Arquillian, allowing inner-class test driver, without ejb-jar.xml and classpath scanning.
I've described my hurdles here: http://jakub.marchwicki.pl/posts/2011/07/01/testing-ejb-application-openejb-without-classpath-scanning/. Have a look, maybe that will make your testing easier.

A: Why don't you simply use a mocking framework like EasyMock or Mockito to test this. You wouldn't need any deployment descriptor, EJB container, JNDI lookup, etc. Just this kind of code :
@Test
public void testDoService() {
    IBean mockBean = EasyMock.createMock(IBean.class);
    mockBean.process("data");
    EasyMock.replay(mockBean);

    Service serviceToTest = new Service(mockBean);
    serviceTotest.doService("data");
    EasyMock.verify(mockBean);
}

And it would certainly run much faster, too.


text:
Q: How can I get an nfs mount in fstab to use the bg option to mount a server when it eventually comes up I've got an NFS server and several NFS clients, if I reboot the server, then when the client comes up (if the server is unavailable), I can get it to either skip the NFS mount or prompt me to ask how to continue.
However in man nfs it talks about a bg option, which should fork the mount to the background and retry the connection periodically (dmesg says every 90 seconds).  When I try that, the client skips the non-existent server, but never seems to retry the connection when the server does come up.
How can I make it work?  This is my fstab setting:
server:/var/www /var/www nfs rsize=8192,wsize=8192,timeo=14,intr,bg,retry=100,nobootwait 0 0

Any ideas?

A: I think what you really want to use is auto mounting.  Auto mounts only mount when they are needed and dismount when inactive.  They also "solve" the problem you are seeing as long as you don't try to access the remote mount until the server is up.
See the Ubuntu Community Docs on Autofs for more information on setting it up.


text:
Q: How do I stop this person (IP address) from trying to connect to my Mac via screensharing? I have screensharing enabled on my Mac. I make use of the feature often to remotely control my Mac from public computers.
However, while looking through the console today, I noticed this message appearing about once every ten seconds:
screensharingd[13223]: Authentication: FAILED :: User Name: N/A :: Viewer Address: 60.6.38.2 :: Type: VNC DES

So, it seems that someone with the IP address 60.6.38.2 is trying to connect to my computer via screen-sharing, and possibly attempting to brute-force my password. Is there any way I can block this guy without actually turning off screen sharing?
Edit: I should probably note that I'm aware my system is not ideal from a security perspective. I just want a way to block this one IP.

A: The bigger question here is why is your Mac not behind a firewall that is doing some sort of port filtering/forwarding as well as stateful packet inspection?
If you were behind a firewall you could block/filter out IP addresses, but this is only temporary because all the attacker has to do is change their IP.
Instead of VNC, which in my opinion is very weak in terms of both security and functionality and instead go for a product like TeamViewer (free for personal use) and you don't have to open any ports on your firewall to use it.
By the way, your attacker is coming from China....


text:
Q: Localization of the injective hull Let $R$ be a Noetherian commutative ring. Let $E(M)$ denote the injective hull of $M$. I want to show that $E(M)_\mathfrak{p}\simeq E(M_\mathfrak{p})$ for any $\mathfrak{p}\in \text{Spec}(R)$.
To do so I was trying to use the characterization of the injective hull, $M\subseteq E$ is an essential extension and $E$ is an injective $R$-module. It is easy to see that $M_\mathfrak{p}\subseteq E(M)_\mathfrak{p}$, and that the latter is an injective $R_\mathfrak{p}$-module. But I'm struggling to see that the extension is essential. My naive attempt: Let $0\neq \frac{x}{s}\in E(M)_\mathfrak{p}$, where $s\not\in\mathfrak{p}$. Since $M\subseteq E(M)$ is essential, there is $r\in R$ such that $rx\in M$ and $rx\neq 0$. Then:
$$\dfrac{r}{1}\cdot \dfrac{x}{s}=\dfrac{rx}{s}\in M_\mathfrak{p}$$
but I'm not assure $rx/s\neq 0$. Is this a good strategy? Is there another way of proving the result I'm looking for? Thanks in advance.

A: In Lemma 6 of Chapter 18 of 'Commutative ring theory' Matsumura proves the following.
Lemma: Let $A$ be a Noetherian ring, $S \subset A$ a multiplicative set, $M$ and $A$-module and $N \subset M$ a submodule. Assume that $M$ is an essential extension of $N$; then $M_S$ is an essential extension of $M_S$.


text:
Q: Calculating real part of a square wave i'm trying to understand how Bruno putzey in
Globally Modulated Self-Oscillating Amplifier with Improved Linearity
in section 4.2 Analysis comes to the equation in presented in (2), see snapshot below.
I've tried to do common fourieseri of a square, wave but i do not get the same answear, it annoys me very hard!
I wish someone could help me understand how to come to the same answear?

More information:
I've tried to calculate the rectangulare fourier series,but I still do not come to the same result as in the article, but I think I'm getting closer.
Se link to calculations in comments (due to not enough reputation)


text:
Q: Email to Salesforce - link to all matching contacts? In the Email to Salesforce documentation, it states: "If Email to Salesforce matches an email address to multiple lead or contact records in Salesforce, you can associate the email with all matching records, the oldest record, or the record with the most activity."
Where can I make this change? It's not in the Email to Salesforce section of Setup. Right now I think our selection is oldest record but I would like to change it to all matching records
Thanks very much :)

A: This is a per user setting. Users can go to My Settings, Email, My Email to Salesforce, and specify the desired setting under Email Associations.


text:
Q: Error while trying to compile Curl library in debian wheezy I downloaded curl library using the following commands:
apt-get build-dep cur
apt-get source curl
cd curl-7.26.0/
./configure
make

After running make, an error is shown as below:
strdup.o: In function `Curl_memdup':
strdup.c:(.text+0x1e): undefined reference to `Curl_cmalloc'
collect2: error: ld returned 1 exit status
make[2]: *** [curl] Error 1
make[2]: Leaving directory `/home/kia/Desktop/curl/curl-7.26.0/src'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/kia/Desktop/curl/curl-7.26.0/src'
make: *** [all-recursive] Error 1

I'm going to add the curl library to a minimized kernel which I built it before.


text:
Q: Data recovery of QFSK signal in GNURadio I'm pretty new to using GNURadio and I'm having trouble recovering the data from a signal that I've saved into a file.  The signal is a carrier frequency of 56KHz with a frequency shift key of +/- 200hz at 600 baud.
So far, I've been able to demodulate the signal that looks similar to the signal I get from the source:

I'm trying to get this into a repeating string of 1s and 0s (the whole telegram is 38 bytes long and it continuously repeats). I've tried to use a clock recovery block in order to have only one byte per sample, but I'm not having much luck.  Using the M&M clock recovery block, the whole telegram sometimes comes out correct, but it is not consistent.  I've tried to adjust the omega and Mu values, but it doesn't seem to help that much.  I've also tried using the Polyphase Clock sync, but I keep getting a runtime error of 'please specify a filter'.  Is this asking me to add a tap? what tap would i use?
So I guess my overall question would be:  What's the best way to get the telegram out of the demodulated fsk signal?
Again, pretty new at this so please let me know if I've missed something crucial.  GNU flow graph below:

A: You're recovering the bit timing, but you're not recovering the byte boundaries – that needs to happen "one level higher", eg. by a well-known packet format with a defined preamble that you can look for.


text:
Q: In SceneKit clipping one object geometry when intersecting with another I'm trying to determine how I can clip one object with another.

The sphere is stationary, but the plane moves around the scene and should clip the sphere as it passes through it. Everything is working, up to the part where the plane clips the sphere.
Can SceneKit accomplish this without resorting to a custom SCNProgram shader?
Progress Update
Calculate the plane equation
Not 100% certain this is exactly correct. In broad strokes - I have a 'fake' cutting plane that I keep around (not strictly necessary), extract the vertices, apply the affine transform, and try to derive the plane equation from, finally passing the value to the vertex shader.
let planeSources = _planeNode?.geometry?.geometrySourcesForSemantic(SCNGeometrySourceSemanticVertex)
if let planeSource = planeSources?.first {
    let stride = planeSource.dataStride
    let offset = planeSource.dataOffset
    let componentsPerVector = planeSource.componentsPerVector
    let bytesPerVector = componentsPerVector * planeSource.bytesPerComponent

    let vectors = [SCNVector3](count: planeSource.vectorCount, repeatedValue: SCNVector3Zero)
    let vertices = vectors.enumerate().map({
        (index: Int, _) -> SCNVector3 in
        var vectorData = [Float](count: componentsPerVector, repeatedValue: 0)
        let byteRange = NSMakeRange(index * stride + offset, bytesPerVector)
        planeSource.data.getBytes(&vectorData, range: byteRange)
        return SCNVector3Make(vectorData[0], vectorData[1], vectorData[2])
    })

    let mat4Transform = SCNMatrix4ToMat4(transform)
    let transformedVertices = vertices.map({
        (vertex: SCNVector3) -> vector_float3 in
        let float4Vector = SCNVector4ToFloat4(vertex.to4(1.0))
        let transformedVertex = matrix_multiply(mat4Transform, float4Vector)
        return vector3(transformedVertex.x, transformedVertex.y, transformedVertex.z)
    })

    if transformedVertices.count >= 3 {
        let vertex0 = transformedVertices[0]
        let vertex1 = transformedVertices[1]
        let vertex2 = transformedVertices[2]

        let v1v0 = vertex1 - vertex0
        let v2v0 = vertex2 - vertex0
        let normal = vector_cross(v1v0, v2v0)
        let distance = vector_dot(normal, vertex0)
        let planeEquation = -1.0 * vector4(normal, distance)
        let planeEquationValue = NSValue(SCNVector4: SCNVector4FromFloat4(planeEquation))

        self._heartNode?.geometry?.setValue(planeEquationValue, forKey: "plane_equation")
    }
}

Vertex shader snippet
varying float clipFragment;

#pragma body
uniform vec4 plane_equation;

float distance = dot(_geometry.position.xyz, plane_equation.xyz) + plane_equation.w;
if (distance <= 0.0) {
    clipFragment = 1.0; // Discard fragment
} else {
    clipFragment = 0.0; // Keep fragment
}

This is working in so far that the object is clipped based upon rotation of the plane in space, but not in the sense that the plane is touching.

A: The algorithm should be the following (described abstractly, as I'm not familiar with that API):

*

*Let Mi be the inverted Model matrix of the sphere (any vector algebra API seems to provide some way to calculate matrix inversion);

*Let Ax+By+Cz+D=0 be an equation of the clipping plane (CP) in world coordinates (I guess you meant, that the plane equation is described in world space);

*Multiplication transpose(invert(mat3_from_mat4(Mi)))*(A,B,C) produces N'=(A',B',C');

*Let P be some point, belonging to CP. Example: P=(0,0,-D/C), provided, that C is not zero;

*Multiplication Mi*(P.x,P.y,P.z,1.0) produces P'=(A0',B0',C0',W0');

*Getting rid of w-component in P' produces P"=(A0'/W0',B0'/W0',C0'/W0')=(A0",B0",C0"), which is a CP's point in sphere's object space coordinates;

*The desired equation is A'x+B'y+C'z-dot(N',P")=0.

EDIT: If the plane is defined in its local space, and the corresponding MVMs are defined for both sphere and plane, then the algorithm is a bit different. Instead P should be first transformed to the common eye space using plane's MVM, and then the obtained values should be transformed using sphere's inversed MVM. N should be transformed by premultiplying with transpose(mat3_from_mat4(MVM(Sphere)))*transpose(invert(mat3_from_mat4(MVM(Plane)))).

A: The Plan in Swifty Pseudocode
The most simplistic scenario is to measure the distance from the plane that represents the marker and the vertex that is about to get rendered.
Compute the plane equation
// Using something like SKLinearAlgebra for cross(), dot(), and to4()
// The marker vertices - these need to be counter-clockwise?
let origin = vertices[0]
let vector1 = vertices[1]
let vector2 = vertices[2]
let normal = SCNVector3.cross(vector1, vector2)
let distance = SCNVector3.dot(normal, vector0)

let planeEquation = normal.to4(distance)

Calculate the signed distance - in the vertex shader
// Given the plane equation
let distance = planeEquation.x * vertex.x +
               planeEquation.y * vertex.y +
               planeEquation.z * vertex.z +
               w

If the distance is less than or equal to zero the fragment is discarded otherwise do what you normally do.


text:
Q: Android: как передать current location в AsyncTask Приложение погода. Через asyntask отправляю запрос в openweathermap и в postexecute начинаю биндить результат в ui, с заранее определенным  городом все проходит на ура, добавил функцию запроса геолокации пользователя и сохраняю его в статическое поле, но asynctask выполняется до запроса геолокации, как сделать чтоб чтобы async task работал после запроса данных геолокации
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

        getLastLocation()

        weatherTask().execute()

    }

public class Common {

    public static final String APP_ID = "a6g096e9c7045fffc90db97209788939";

    public static Location current_location = null;

}

методом сохраняя координаты в common.current_location
                mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
                    val location: Location? = task.result
                    if (location == null) {
                        requestNewLocationData()
                    } else {
                        Common.current_location.latitude = location.latitude
                        Common.current_location.longitude = location.longitude
                        Toast.makeText(this, "${location.latitude}", Toast.LENGTH_LONG).show()
//                        latTextView.text = location.laлtitude.toString()
//                        lonTextView.text = location.longitude.toString()
                    }
                }

может как то возможно передать координаты в asynctask
        override fun doInBackground(vararg params: String?): String? {
            return try{
                URL("https://api.openweathermap.org/data/2.5/weather?lat=${Common.current_location.latitude}&lon=${Common.current_location.latitude}&appid=${Common.APP_ID}").readText(
                    Charsets.UTF_8
                )
            }catch (e: Exception){
                null
            }
        }


text:
Q: Pandas: rename a index label in multiindex dataframe if NaN How can I replace the inner index label of the df below?
Question                                 profile_gender. Gender
Values                                    Male     Female
Question                    Values
XCS_3. Think of a problem?  NaN        25.192318  25.900784

to:
Question                                 profile_gender. Gender
Values                                    Male     Female
Question                    Values
XCS_3. Think of a problem?  Okay Done   25.192318  25.900784

My failed attempt:
df.index = df.index.set_levels(['Okay Done'], 1)

Does nothing, doesn't even throw an error code

A: Looks like I have to replace the entire index which is very annoying.
df.index = pd.MultiIndex.from_tuples([('XCS_3. Think of a problem?', ' Okay Done')],
                                     names=['Question', 'Values'])


text:
Q: MVC JQuery Ajax Busy Indicator overlay on Form I have created a simple form which is submitted using JQuery Ajax and works very well. What I am trying to achieve is that a busy indicator "loader image" is displayed on the entire form as an overlay. I have seen many example but most of them are related to show and hide a simple div containing the image and it doesn't act as overlay on the form. What I have achieved so far is to just show the loading indicator on the center of the screen with the help of css. Below is code for my div and css for it.

and here is the css,

Ajax call might not be important in this scenario but I will put just in case it is needed,
$(function () {
    $('#RegisterForm').submit(function () {
        if ($(this).valid()) {
            $("div#spinner").fadeIn("fast");
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $("div#spinner").fadeOut("fast");
                    $("div#result").html(result);
                }
            });
        }
        return false;
    });
});

Now as I said with this code the loader image is displayed on the center of screen but it is not overlay. But I want the loader image to be overlayed on the form only. But it should adjust itself according to form size on runtime because I am not specifying any height. Is this achievable? If yes then how?

A: What's a little weird is that you have loader.gif and also spinner.gif... I'm guessing you are purposely using both for a reason. I'll take that into account.  I'm assuming #spinner is a child of #RegisterForm. If that's the case you could have the styles be as follows:

What this does is stretch out the spinner DIV to cover all of the #RegisterForm. I also added the opacity so you can see how it's overlayed. The JavaScript looks fine and should do the trick.

A: I have found another solution which is simple enough for me and works out of the box. The solution is to use jQuery.BlockUI. It can not only block the whole page but also can block any element on the page. The css is rendered by default but css can be changed if desired. I have added the package from NuGet. Added the reference file and updated my Ajax call like this,
$(function () {
    $('#RegisterForm').submit(function () {
        if ($(this).valid()) {
            $("#RegisterForm").block({
                message: '',
                css: { width: '4%', border: '0px solid #FFFFFF', cursor: 'wait', backgroundColor: '#F2F2F4' },
                overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.5, cursor: 'wait' }
            });
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $("#RegisterForm").unblock();
                    $("div#result").html(result);
                }
            });
        }
        return false;
    });
});

It works like a charm. I can change the background and loading image too. So if anyone is looking for the same solution then this might be helpful.


text:
Q: How to initialize List? I tried to do so:
rotation[0] = new double[3][];
for (int i = 0; i < 3; i++)
{
    rotation[0][i] = new double[3];
}

but it doesn't work.

A: Assuming that rotation is your List<double[][]>, you can do it like this:
var tmp = new double[3][];
for (int i = 0; i < 3; i++) {
    tmp[i] = new double[3];
}
rotation.Add(tmp);

You can also do it using LINQ:
rotation.Add(Enumerable.Range(0, 3).Select(i => new double[3]).ToArray());

Both fragments above add a single 3x3 array of doubles to a List<double[][]>.
If you need a list of three items, you can do it like this:
List<double[][]> rotation = new List<double[][]>();
for (int r = 0 ; r != 3 ; r++) {
    var tmp = new double[3][];
    for (int i = 0; i < 3; i++) {
        tmp[i] = new double[3];
    }
    rotation.Add(tmp);
}

or
List<double[][]> rotation = new List<double[][]>();
for (int r = 0 ; r != 3 ; r++) {
    rotation.Add(Enumerable.Range(0, 3).Select(i => new double[3]).ToArray());
}

or even
var rotation = Enumerable
    .Range(0, 3)
    .Select(r => Enumerable.Range(0, 3).Select(i => new double[3]).ToArray());


text:
Q: GQL query with "like" operator
Possible Duplicate:
Google App Engine: Is it possible to do a Gql LIKE query?

In SQL (T-SQL at least) you can write a query that uses the "like" operator, something like this:
select * from MyTable where MyColumn like '%something%'

Is there any way to do this in GQL?


text:
Q: Using Entity Framework Set DateCreated on a poco object when saving I am evaluating Entity Framework 4.0 and I am wondering how I can get access to entities just before they are saved to set DateCreated.
With NHibernate this could be done using a listener, if that helps?

A: You could use the ObjectContext event SavingChanges, retrieve the entities that have an the state EntityState.Added, and set the DateCreated for those objects. You might need a helper interface to facilitate a more agnostic handler and avoid the use of reflection. You might also be able to use dynamic, although you would run the chance of runtime exceptions being thrown, which would hurt performance:
private void context_SavingChanges(object sender, EventArgs e)
{
    ObjectContext context = sender as ObjectContext;
    if (context != null)
    {
        foreach (ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries (EntityState.Added)
        {
            IEntityWithTimestamps entity = entry.Entity as IEntityWithTimestamps;
            if (entity != null)
            {
                entity.DateCreated = DateTime.Now;
            }
        }
    }
}


text:
Q: Ansible with_items conditional check against json I am trying to write a playbook which checks for the windows features installed. If they are installed, it should skip them, otherwise install them from my list of vars.
- name: win command
  win_command: 'powershell.exe "Get-WindowsFeature | Where Installed | Select -exp Name | ConvertTo-Json"'
  register: result

- name: Register vars
  set_fact:
    featureinstalled: '{{ result.stdout | from_json }}'

- name: Installing features
  win_feature:
    name: '{{ item }}'
    state: Present
  with_items:
    '{{features_to_install}}'
  when: '{{ item }} != {{ featureinstalled }}'

My features_to_install vars in a separate /vars/ file:
---
features_to_install: [FileAndStorage-Services,File-Services,.....]

I want the playbook to skip installing the feature if the feature is present in the JSON. The error Im getting:

{  "failed": true,
      "msg": "The conditional check '{{ item }} != {{ featureinstalled }}' failed. The error was: template error while templating string:
  expected token ',', got 'string'. String: {% if
  FileAndStorage-Services != [u'FileAndStorage-Services',
  u'Storage-Services', u'FS-SMB1', u'WoW64-Support'] %} True {% else %}
  False {% endif %}\n\nThe error appears to have been in
  '/tmp/worldengine/src/roles/webserver/tasks/windows_features.yml':
  line 31, column 3, but may\nbe elsewhere in the file depending on the
  exact syntax problem.\n\nThe offending line appears to be:\n\n\n-
  name: Installing features\n  ^

A: There are handy filters available to manipulate sets:
- name: Installing features
  win_feature:
    name: '{{ item }}'
    state: Present
  with_items: '{{ features_to_install | difference(featureinstalled) }}'

This will iterate over features from features_to_install list, but that are not in featureinstalled list.


text:
Q: Funcion AJAX con VUE quisiera saber de que forma se puede hacer el siguiente código pero con VUE, me gustaría incursionar en esta nueva tecnología pero no tengo mucho conocimiento sobre ella entonces me gustaría pasar la siguiente llamada ajax pero con VUE, ya tengo cargada la librería al proyecto.
    <script>
   $("#del-"+<?php echo $persona["id"];?>).click(function(e){
        e.preventDefault();

    id = document.getElementById("id-"+<?php echo $persona["id"];?>).value//obtener valor del input

                                   var url = "enviar.php";
                                   $.ajax({
                                      type: "POST",
                                      url: url,
                                      data:{id:id},
                                      success: function(data)
                             {

                           }
                       });

                           });
    </script>

A: puedes hacerlo asi:
data="{'id','id'}";
//nombre del metodo
getPersona(url,data) {
// puede ser post o get
  this.$http.post(url,data).then((response) {
  this.message = response;
});


text:
Q: HTTP Chunked transfer encoding: How do you send "\r\n"? Say the body I'm trying to send via chunked encoding includes "\r\n", how do I avoid that being interpreted as the chunk delimeter?
e.g. "All your base are\r\n belong to us"
http://en.wikipedia.org/wiki/Chunked_transfer_encoding

A: By design, that is not a problem at all.  Each chunk specifies the byte size of its data block.  The contents of each data block are arbitrary, and must be received as such, so it can include line breaks in it.  If the client is reading each chunk correctly (read a line and parse the byte size from it, then read the specified number of bytes, then read a line break), it won't matter if there are line breaks in the data, since the client is reading the data based on byte size, not on line breaks.

A: "\r\n" isn't really a chunk delimiter.  The chunk size specifies the number of bytes made up by that chunk's data.  The client should then read the "\r\n" embedded within your message just fine.


text:
Q: Problema de Cast num método genérico que recebe um array de enum's (enum[]) Pretendo fazer um método genérico que recebe um enum[] e que retorne uma string representando os itens do array separados por virgula.
public static string ToSeparatedCommaString<T>(T[] enums)
    where T : struct, IComparable, IFormattable, IConvertible//Não garante que seja enum mas sempre limita alguma coisa
{
    var commaString = string.Empty;
    foreach (var item in enums)
    {
        commaString += ((Enum)item).GetStringValue() + ",";
    }
    return commaString.TrimEnd(',');
}

O problema surge quando quero aceder ao Extension Method GetStringValue().
A tentativa de fazer cast, como era de esperar, não é permitida.
Há alguma forma de conseguir isto?
GetStringValue() é um método que retorna uma string cujo valor é o indicado no atributo associado ao elemento do enum

A: Uma forma fácil de resolver o problema é fazer o box do item em um object e depois dar outro cast para o tipo final Enum.
Mais algumas sugestões:

*

*testar o tipo de T para garantir que este seja um tipo de enum, e lançar uma exceção descritiva do problema que ocorreu caso não seja

*usar LINQ faz o código mais fácil (eu acho, é apenas uma sugestão)
return string.Join(",", enums.OfType<Enum>().Select(item => item.GetStringValue()));

Como disse que GetStringValue é método de extensão, dá pra fazer assim também:
return string.Join(",", enums.OfType<Enum>().Select(NomeDaClasse.GetStringValue));

Código final... sem usar LINQ pois isso é questão de estilo e é pessoal:
public static string ToSeparatedCommaString<T>(T[] enums)
    where T : struct, IComparable, IFormattable, IConvertible
{
    if (!typeof(T).IsEnum)
        throw new Exception("O método de extensão `ToSeparatedCommaString` suporta apenas Enums no parâmetro genérico `T`.");

    var commaString = string.Empty;
    foreach (var item in enums)
    {
        commaString += ((Enum)(object)item).GetStringValue() + ",";
    }
    return commaString.TrimEnd(',');
}

A: Você sabe que sem dar a garantia, não dá para ter um código confiável, então vai ter que resolver em tempo de execução se é possível fazer a operação ou não. Tem algumas formas possíveis, algumas melhores que outras, algumas te darão mais poder de como manipular o erro, se ele ocorrer. Pode fazer isto:
public static string ToSeparatedCommaString<T>(T[] enums)
    where T : struct, IComparable, IFormattable, IConvertible {
    var commaString = string.Empty;
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("Tipo de enums é inválido");
    }
    foreach (var item in enums) {
        Enum enumerador = item as Enum;
        commaString += enumerador.GetStringValue() + ",";
    }
    return commaString.TrimEnd(',');
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Fiz uma comparação de performance da abordagem que eu propus com a da resposta do Miguel que resolve bem também. O resultado desta foi melhor. Isto foi debatido nos comentários abaixo.


text:
Q: NSAttributedString setFont does not apply to emoji characters I am using Nimbus NIAttributedLabel class to display text which sometimes contain emoji characters. I set the font size to [UIFont systemFontOfSize:15] but emoji characters seem to ignore that. With UILabel all characters are displayed correctly.
NIAttributedLabel internally calls
[self addAttribute:(NSString*)kCTFontAttributeName value:(id)fontRef range:range];

I suppose NSAttributedString has to switch to a different font when it sees emoji characters. Is there any trick to make sure it uses the same font size?


text:
Q: I cannot register a user using Django-Rest-Framework I can't add a new user using Django Rest Framework. Here is my code from models.py:
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    password = models.CharField(max_length=15, default= None)
    first_name = models.CharField(max_length=100, validators=[name_validator])
    last_name = models.CharField(max_length=100, validators=[name_validator])
    email = models.CharField(max_length=100, validators=[mail_validator])
    created_at = models.DateTimeField(auto_now_add=True)

As you can see I am using models.OneToOneField cause I want to extend the default user to add some more fields.
Bellow is my serializers.py file:
class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        permissions_classes = [
            permissions.AllowAny
        ]
        fields = '__all__'

The viewset is the following:
class UserViewset(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

When I go to my endpoints and try to add a new user, I cannot put anything in the "user" field:
Click for image
I am a beginner and it would be of great help.
Thank you!

A: you can to this
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    password = models.CharField(max_length=15, default= None)
    first_name = models.CharField(max_length=100, validators=[name_validator])
    last_name = models.CharField(max_length=100, validators=[name_validator])
    email = models.CharField(max_length=100, validators=[mail_validator])
    created_at = models.DateTimeField(auto_now_add=True)

serializer.py
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

class ProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = Profile
        fields = '__all__'

views.py
class UserViewset(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = [permission. AllowAny,]

A: When you want to extend the default user to add some more fields, the best way for that is substituting a custom User model by inheritance the AbstractUser model. Using this way, you can CRUD the user easily.


text:
Q: VBA Loop Print to CSV Output I'm trying to create a CSV output file in VBA but I can't seem to get it. I need to loop through a spreadsheet and pull numbers from column 'I' based on whether column D has a "1" in it or not. Then I want to paste the contents of column 'I' into column 'A' of the CSV output file. Could someone please help me complete this? I'd like to incorporate all of the following:
Sub Test()

Dim FileNum, bOutputLine, bFile As String
Dim bOUTPUT, iRow As Integer

bOUTPUT = FreeFile                                   'Define bOUTPUT as a FreeFile
bFile = "C:\Desktop\Test.csv"                        'set the filepath equal to a string

For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
If Trim(range("D" & iRow)) <> "" Then
FileNum = Trim(range("I" & iRow))
End If
Next

Open bFile For Output As bOUTPUT                     'Open the file
bOutputLine = FileNum
Print #bOUTPUT, bOutputLine
Close #bOUTPUT                                       'Close the file

End Sub

A: You either need to put the file interaction inside the for-next loop and open as append instead of output, or build a string variable in the loop that will print out at the bottom.  Here's the two options:
Sub Test()

Dim FileNum, bOutputLine, bFile As String
Dim bOUTPUT, iRow As Integer

bOUTPUT = FreeFile                                   'Define bOUTPUT as a FreeFile
bFile = "C:\Users\HPUser\Desktop\Test.csv"                        'set the filepath equal to a string
Open bFile For Append As bOUTPUT                     'Open the file
For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
    If Trim(range("D" & iRow)) <> "" Then
        FileNum = Trim(range("I" & iRow))

        bOutputLine = FileNum
        Print #bOUTPUT, bOutputLine

    End If
Next
Close #bOUTPUT                                       'Close the file
End Sub

or
Sub Test()

Dim FileNum, bOutputLine, bFile As String
Dim bOUTPUT, iRow As Integer

bOUTPUT = FreeFile                                   'Define bOUTPUT as a FreeFile
bFile = "C:\Users\HPUser\Desktop\Test.csv"                        'set the filepath equal to a string

For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
    If Trim(range("D" & iRow)) <> "" Then
        bOutputLine = bOutputLine & Trim(range("I" & iRow)) & vbcrlf
    End If
Next

Open bFile For Output As bOUTPUT                     'Open the file
Print #bOUTPUT, bOutputLine
Close #bOUTPUT                                       'Close the file

End Sub

A: One way is to write to it directly in the loop:
Open bFile For Output As bOUTPUT
For iRow = 2 To ActiveSheet.UsedRange.Rows.Count
If InStr(1, Range("D" & iRow), "1") <> 0 Then
Print #bOUTPUT, Trim(Range("I" & iRow))
End If
Next
Close #bOUTPUT

The InStr will look for the value "1" in Column D's cell (as by the wording of the question, it seems it could be something like "AAA1A". It returns 0 if "1" is not found.


text:
Q: Compute $\lim_{x \to 0} x \lfloor x - \frac{1}{x} \rfloor$ Let $f: \mathbb{R} \to \mathbb{R}$ be the following function:
$f(x) = x \lfloor x - \frac{1}{x} \rfloor$
Show that $f(x)$ admits a limit at zero, and compute its value.

Using epsilon delta, I can prove that $\lim_{x \to 0} x \lfloor x - \frac{1}{x} \rfloor = - 1$:
$|x \lfloor x - \frac{1}{x} \rfloor + 1|$
$\leq |x \lfloor x - \frac{1}{x} \rfloor| + |1|$
$\leq |x| |\lfloor x - \frac{1}{x} \rfloor| + |1|$
$\leq |x| |x| + |1|$
$\leq |x|^2 + |1| < \epsilon$ if $|x| < \delta = \sqrt{\epsilon - 1}$
Is that right? If not, how can I do prove it?
But how do I show that $\lim_{x \to 0} x \lfloor x - \frac{1}{x} \rfloor$ exists?

A: By definition of the floor function
$$x-\frac{1}{x}-1<\left\lfloor x-\frac{1}{x}\right\rfloor \le x-\frac{1}{x}$$
So for $x>0$
$$x^2-1-x < x \left\lfloor x-\frac{1}{x}\right\rfloor \le x^2-1$$
so by the Squeeze Theorem,
$$\lim_{x\to 0^+}{x \left\lfloor x-\frac{1}{x}\right\rfloor}=-1$$
Now for $x<0$ the direction of the inequality reverses so
$$x^2-1-x > x \left\lfloor x-\frac{1}{x}\right\rfloor \ge x^2-1$$
and again by the Squeeze Theorem,
$$\lim_{x\to 0^-}{x \left\lfloor x-\frac{1}{x}\right\rfloor}=-1$$
Since the two one-sided limits are the same, the limit as $x\to 0$ is $-1$.

A: Suppose that $\frac1{n+1}\le x<\frac1n$; then $n<\frac1x\le n+1$, so
$$-n-\frac{n}{n+1}=\frac1{n+1}-(n+1)\le x-\frac1x<\frac1n-n=-n+\frac1n\;,$$
and $\left\lfloor x-\frac1x\right\rfloor$ is either $-n-1$ or $-n$. Thus, $x\left\lfloor x-\frac1x\right\rfloor$ is either $-nx$ or $-(n+1)x$. Now use the limits on $x$ to bound $-nx$ and $-(n+1)x$, and let $n$ increase without bound.


text:
Q: Kotlin build error for a non nullable variable using let error Unresolved reference: length gradle 7.4.2
fun main() {
    var nullableName: String? = null
    nullableName?.let {
    println(it.length)
    }
}

Error message: /Nullables.kt: (30, 20): Unresolved reference: length