text:
Q: Check if $(0,0)$ is a local min or local max Let $f(y,z)=y^3+zy+z^3$. Is $(0,0)$ a local min or max? For this I tried using the 2nd derivative test:
$$D=f_{xx}\cdot f_{yy}-f_{xy}^2=36xy-1^2$$
Inserting $(0,0)$:
$$36\cdot 0 \cdot 0-1^2=-1<0$$
Therefore it is a saddle point. How do I use this to see if it is local min or max? Do I need to do something different?

A: If $(0,0)$ is a saddle point, then it isn't a local min nor max.
Note that $f(0,z) = z^3$. Then, for every $\delta >0$, there exist $z_1, z_2 \in B_{\delta}(0)$ with $z_1 <0 <z_2$ such that $f(0,z_1) < f(0,0) < f(0,z_2)$. Therefore, $(0,0)$ is not local min nor max.

A:
Inserting $(0,0)$:
$$36\cdot 0 \cdot 0-1^2=-1<0$$
Therefore it is a saddle point. How do I use this to see if it is local min or max?

Note- A point $P(x,y)$ can be a point of maxima, minima or a saddle point and all three cases are mutually exclusive.


text:
Q: Swift: How to set a value in a Dictionary at a given sublevel? Given this dictionary as an example:
var d = ["a": ["b": ["c": 30, "d": 20] ] ]

I would like to write a function that could add/update a value into this dictionary.
First example, if I call :
d.set(40, at: ["a", "b", "c"])

The function would progressively go into key a, then b, then c, and transform this dictionary into:
var d = ["a": ["b": ["c": 40, "d": 20] ] ]

Now if I call this instead:
d.set(60, at: ["a", "e", "f"])

I would like to get this dictionary instead:
var d = ["a": ["b": ["c": 40, "d": 20] ], "e": ["f": 60] ]

Could you help me writing this function?
Thank you for your help

A: Your example only requires this. Is your question actually larger than that? If so, please amend!
extension Dictionary {
  subscript<Value>(_ key0: Key, _ key1: Key, _ key2: Key) -> Value?
  where Self.Value == [Key: [Key: Value]] {
    get { self[key0]?[key1]?[key2] }
    set { self[key0, default: [:]][key1, default: [:]][key2] = newValue }
  }
}

d["a", "b", "c"] // 30
d["a", "b", "c"] = 40

d["a", "e", "f"] // nil
d["a", "e", "f"] = 60

A: This seems to do the trick:
Edit Now this covers all the provided uses cases
extension Dictionary where Value == Any {
    mutating func set<V>(_ value: V, at keyPath: [Key]) {
        var keyPath = keyPath
        guard !keyPath.isEmpty else { return }
        let topLevel = keyPath.removeFirst()
        guard !keyPath.isEmpty else {
            self[topLevel] = value
            return
        }
        guard keyPath.count > 1 else {
            self = merge(with: [topLevel: [keyPath.last!: value]])
            return
        }
        let leafKey = keyPath.removeLast()
        let nested = [leafKey: value].nest(in: keyPath)
        guard let child = self[topLevel] as? [Key: Any] else {
            self[topLevel] = nested
            return
        }

        self = self.merge(with: [topLevel: child.merge(with: nested)])
    }

    func merge(with other: [Key: Any] ) -> [Key: Any] {
        var result = self

        for key in other.keys {
            if !keys.contains(key) {
                result[key] = other[key]
            } else {
                switch (self[key], other[key]) {
                case let (lhs, rhs) as ([Key: Any], [Key: Any]):
                    result[key] = lhs.merge(with: rhs)
                default:
                    result[key] = other[key]
                }
            }
        }
        return result
    }

    func nest(in keys: [Key]) -> [Key: Any] {
        let initial: [Key: Any] = self as [Key: Any]
        let result: [Key: Any] = keys.reversed().reduce(into: initial) { result, key in
            result = [key: result]
        }
        return result
    }
}

var d: [String: Any] = ["a": ["b": ["c": 30, "d": 20] ] ] // ["a": ["b": ["c": 30, "d": 20]]]
d.set(40, at: ["a", "b", "c"]) // ["a": ["b": ["c": 40, "d": 20]]]
d.set(60, at: ["a", "e", "f"]) // ["a": ["b": ["c": 40, "d": 20], "e": ["f": 60]]]
d.set(["f": 42], at: ["a", "d"]) // ["a": ["b": ["c": 40, "d": 20], "e": ["f": 60], "d": ["f": 42]]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can't I put drop down menu under a button? I am so desperate right now. Have tried 2 days to solve this but still no avail. The dropdown menu cannot be put under the situation and the exercise button correctly. It shows on the left hand-side of the navbar instead of the bottom of the button, which may because i used float left at line 19 CSS in fiddle:
.navbar a,.sit,.exercise {
   float:left;
}

class "navbar" is for the whole navbar
class"dropdown1" is for the followings :class"sit" is for the button "situation", class"situ" is for the dropdown menu in "sit"
class"dropdown2" is for the followings :class"exercise" is for the button "exercise", class"exec" is for the dropdown menu in "exercise"
I have tried to put position: relative under class"sit" and class"exercise". However, the result is that a scrollbar shows up in the dropdown menu and you have to scroll it down to see the whole menu. The position doesn't even change!
here is the code in fiddle
https://jsfiddle.net/zo0raL86/
I expect the dropdown menu can be shown under the right button. Really hope that you can give me a helping hand! Thank you so much

A: Add this to your stylesheet:
.navbar > div{
  display: inline-block;
  width: 32.78%;
}

Then add some pixels to the top-Value of .situ and .exec then it will be display right under the button.
I also updated your html.

     About

    Situation

        s1
        s2
        s3

    Exercise

        e1
        e2
        e3

Remove the bottom Value from your dropdowns and add
.situ, .exec{
  top: 123px;
}

The value should be the sum of your margin-top and height to fit smoothly under the navigation.

A: Your basic problem is that you've set all your floats on the children of the elements you actually want to float.
For example:
You have
.navbar a,.sit,.exercise {
    float:left;
    width: 32.78%;
}

Whereas the float:left; and the width should be on their parent elements .i3, .dropdown1, and .dropdown2 like so ...
.i3,
.dropdown1,
.dropdown2 {
    width: 33.333%;
    float: left;
}

This will solve the basics of your problem and the additional width problem you've expressed in your fiddle.
Better still set the widths of .sit and .exercise to 100%.
I've updated your fiddle here so you can see the code in situ.


text:
Q: Is using System.Security.Cryptography.RSACng to sign and verify data thread safe? I have an instance of X509Certificate2 that holds an instance of System.Security.Cryptography.RSACngimported from .pfx file.
I don't want to read the file from disk every time I need to use it.
Is it safe to just have one global instance that is used by multiple threads?
I'm using .Net Core 3.1 on Linux and Windows.

A: No, RSACng class is not thread-safe.
Also, be aware that this class is not available on Linux or Mac. It is Windows-only implementation. So keed abstract RSA class reference everywhere in the application instead of this particular implementation.


text:
Q: Template binding not working when source is null/undefined Can anyone explain me what is wrong with my view model or template in this example jsfiddle?
It doesn't work as expected. Basically the view model contains an object and that object is null. In the view, there is a template binding to this object. As this object is null, it shouldn't render the template. However, it does try to render the template and fails in my example. If job object is null then I don't want to render the template.
According to this article by Ryan, if a viewmodel contains a null object and there is a "template binding" for this object, it won't render the template.
Here is my view model:
var job = function(title) {
    this.jobTitle = ko.observable(title);
}

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    //this.job = ko.observable(new job("software developer"));
    this.job = ko.observable(null);

    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();
    }, this);
};

ko.applyBindings(new ViewModel("FirstName", "LastName"));

And this is the view:

First name: <input data-bind='value: firstName' />

Last name: <input data-bind='value: lastName' />

Hello,  !

A: The linked artifice was written almost 3 years ago. By the time the latest version of Knockout was around 1.2.1.
And in Knockout 1.2.1 your code is working fine: Demo using KO 1.2.1
However since then Knockout has changed a lot so it is not supporting this behavior anymore.
Nowadays you need to use the  if option of the template binding

Demo JSFiddle.
Or the with (if) binding to achieve the same outcome:

First name: <input data-bind='value: firstName' />

Last name: <input data-bind='value: lastName' />

Hello,  !

Demo JSFiddle.

A: You could surround your template binding with a div which uses the 'if' data-binding to the job observable:

The editor template is hidden when job is null, and visible when not null.
EDIT:
A better solution is to pass the 'if' option to the template binding:


text:
Q: Removing straight line noise from image using openCV I'm trying to clean a captcha image that has straight lines as noise in them.

I'm very new to OpenCV but from what I understand the best approach is to turn the image to black and white then using a Hough Line Transform to detect the lines and then mask them.
I did that here:
im_gray  = cv2.imread('download.png', cv2.IMREAD_GRAYSCALE)

im_bw = cv2.threshold(im_gray, 120, 255, cv2.THRESH_BINARY)[1]
im_bw_inverted = cv2.bitwise_not(im_bw)

im_bw_inverted:

I then detected the lines using the Hough Lines:
rho = 1
theta = np.pi / 180
min_line_length = 1
max_line_gap = 20
threshold = 50
line_image = np.copy(im_bw) * 0
lines = cv2.HoughLinesP(im_bw_inverted, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)

for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(line_image,(x1,y1),(x2,y2),(255,0,0),1)

line_image:

Using inpaint to mask it:
line_image_dilate = cv2.dilate(line_image, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (4, 4)))

dst = cv2.inpaint(im_bw_inverted,line_image_dilate, 1, cv2.INPAINT_NS)

dst Result:

Is there a better way to approach cleaning the image? The resulting image doesn't look that good is there a way to improve the result?


text:
Q: Запуск исполняемого файла и коды возврата в php Что означают коды возврата? Ну, например, запускаю я исполняемый файл в php, мне возвращает 139.
<?php
echo '
';
system('/home/re1aps/insert', $retval);
echo '

'

Kod vozvrata: ' . $retval;'
?>

Собственно бинарник такой:
#include <mysql.h>

int main(int argc, char **argv)
{
  MYSQL *conn;

  int len, size;
  char data[1000*1024];
  char chunk[2*1000*1024+1];
  char query[1024*5000];

  FILE *fp;

  conn = mysql_init(NULL);
  mysql_real_connect(conn, "localhost", "root", "", "bd", 0, NULL, 0);

  fp = fopen("test.jpg", "rb");
  size = fread(data, 1, 1024*1000, fp);

  mysql_real_escape_string(conn, chunk, data, size);

  int val1= 1 ,val2= 2;

  char stat[] = "INSERT INTO img(id, pic, name) VALUES(\'%d\', \'%s\', \'%d\')";
  len = snprintf(query, sizeof(stat)+sizeof(chunk) , stat, val1, chunk, val2);

  mysql_real_query(conn, query, len);

  fclose(fp);
  mysql_close(conn);
}

В итоге, ничего не запускается и не добавляется. Да я знаю, все это можно сделать и на чистом php, но это только часть программы, основная программа сложный расчет - на php такое либо глупо делать, либо не реально, скорее первое. Да из консоли если запускать все работает.
P.s. Но если я пишу элементарный код - то все окей. К примеру, вывожу в консоль "hello world". То же самое выводится и в браузере, но стоит чуть усложнить и в браузере сыпятся ошибки. Конкретно какие были: 1, 127, 139 вроде это основные, по-поводу них ничего не нашел, что они вообще означают?
A: Код возврата это число от 0 до 255 (очевидно ему же сответствует -1), которое передается в функцию (системный вызов) exit, или возвращается оператором return из main.
В *nix некоторые коды возврата описаны в /usr/include/sysexits.h
Традиционно код возврата, отличный от нуля, говорит об ошибке. Если Вы явно не возврашаете код (из программы на С/C++), то он случаен.
Завершите свою программу
    return 0; // OK
или
    exit(0); // OK

A: Странно, конечно, но у меня при [чисто для теста!!! :)]
chmod 777 /var/www/
код на си:
#include <stdlib.h>

int main()
{
   system("echo yap > test.txt");
   return 0;
}
и код на php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$result = 0;
$result = system("/var/www/a.out");
echo "out: ".$result."
";
?>
Выдает:
out: 0
и в каталоге /var/www/ создается файл test.txt с текстом yap

Смотри, может с правами доступа у тебя проблема. Тем более запуск из терминала - это один пользователь (re1aps) и у него в /home/re1aps свои права и своя группа.
A: Коды ошибок windows.
Код ошибки: 139 (0x008B).
Попытка отобразить диск на папку, находящуюся на отображенном диске.
A: #include <stdlib.h>
#include <iostream>

main()
{
    system("/home/re1aps/insert");
    std::cout << "hello angry php:(" << std::endl;

    return 0;
}

Попытался запустить такой бинарник, ну собственно текст печатает, а систем не выполняет. В консоле опять же все ок.


text:
Q: CSS Menu Disappears after mouse hover I have a little issue with a menu on my Joomla 2.5 page. It's a module and I used several CSS properties like:
visibility:visible; z-index:99999!important

Yet, the menu does not delays for me to click it.
I want the menu to be clickable when the reader mouse over and mouse on the second level menu. I don't want it to disappear any more.
A sample of what I want the menu to look like can be found here: http://vitafoam.com.ng

A: On the css class ul.navi ul.level2 on menustyle.css, remove the top: 91px property. It is throwing your level2 menu down, and keeping you from hovering it.
Removing the top property fixed the problem, at least on my Chrome Debug.


text:
Q: without an extra "printf" my code give me segmentation fault (core dumped) error I am trying to write a C program in Linux.
#include<stdio.h>

void fun(int *r)
{
    *r=20;

     r--;
    *r=30;

     r--;
    *r=40;
}

int main()
{
    int a=2;
    int b=3;
    int c=4;

    fun(&c);

    printf("a=%d\nb=%d\nc=%d",a,b,c);

    return 0;
}

When I run the code it gives me a segmentation fault (core dumped).
But when I print the addresses of a, b, and c in the main function before the function call the code works.
#include<stdio.h>

void fun(int *r)
{*r=20;

r--;

*r=30;
r--;

*r=40;
}
int main()
{

int a=2;
int b=3;
int c=4;

printf("a=%p\nb=%p\nc=%p\n",&a,&b,&c);

fun(&c);

printf("a=%d\nb=%d\nc=%d",a,b,c);

return 0;
}

Can anyone please tell me why this happened?

A: In your code, c is a single variable, and you pass the address of this variable to fun(). Later, inside fun() you try to move the pointer and then dereference it. It actually invokes undefined behavior.
Only the array elements are guaranteed to be allocated contiguous memory locations, separate variables can very well be allocated in compiler-dependent way.
You can define an array like
 int a[3] = {0};

and then, call fun() like
 fun(&a[2]);

and get the desired result in a well-defined way.

A: It may have something to do with whatever optimizations your compiler applies (or doesn't). This certainly is not portable code. If it works at all, that is by luck only, as C makes no guarantees about the order in which variables are allocated. This program seems to depend on undefined behavior.


text:
Q: Can you tell from machine code if an instruction is relocatable? According to Assemblers And Loaders (a 24-year old book on how assemblers work):

...a one-pass assembler cannot generate a relocatable object file. The
  type of the instruction (absolute or relocatable) can be determined
  only by examining the original source instruction. The one-pass
  assembler loads the machine instructions directly in memory. Once in
  memory, the instruction is just a number. By looking at a machine
  instruction in memory, it is impossible to tell whether the original
  instruction was absolute or relocatable.

The book gives the following pseudo code of a relocatable and an absolute instruction:
    JMP TO
    ...
TO: ADD 1,2

Where the first instruction uses the symbol TO and the second instruction adds the values in register '1' and register '2'.
It is my understanding that you don't need the source code to know that the machine code of the first instruction is relocatable. It should be possible to use the opcode table to determine that it's the JMP instruction and that it must jump to an address which needs to be relocatable.
Is my assumption correct?
Background: although the book is old, I'm reading it get a better understanding of assembly for old CPUs like the 6502 and 65816.

A: Your book is misleading, a one pass assembler, as most people would understand the term, can generate a relocatable object file by emitting special data called relocations which tell the linker/loader how to relocate the code.  The book seems to using be a particular definition of a "one pass assembler", one that by its own definition isn't capable of outputting a "relocatable object file" with relocations.
However it is true that in general you can't tell if a given machine code instruction is relocatable unless there's a set of relocations available to tell what is or isn't relocatable (and how to relocate the instructions that aren't). Certain instructions make it obvious, for example you can tell if a JMP TO instruction is relocatable or not based on how the destination address is encoded.  If the destination address is encoded as a relative offset to the address of the JMP instruction then it's relocatable. On the other hand, if is encoded as an absolute address the instruction isn't relocatable. In the first case the program can be relocated in memory without modifications and the JMP instruction will still jump to the same code. In the second case the JMP instruction will always jump to the same address regardless where the code has been relocated to unless the instruction is changed to jump to correct place.
In x86 assembly a concrete example of the first case would be the following:
0056: EB 10     JMP LO

The first byte in the instruction, is the opcode EB (the numbers I'm using here are all in hexadecimal), which indicates a near JMP instruction with a 8-bit relative offset. The second byte in the instruction is that 8-bit relative offset. It's actually relative to the start of the following instruction, so the address jumped to is 0056 + 2 + 10 or 0068.
In 6502 assembly an example of the second case would be:
0056: 4C 68 00   JMP LO

In this case the opcode byte 4C indicates a JMP instruction which has uses 2-byte absolute address in encoded into the instruction.  The next two bytes make up that address in little-endian byte order: 0068.
Another easy example is something like ADD 1,2 which only uses registers. Since there are no addresses involved the instruction can be relocated without modification because there are no addresses encoded in the instruction. The problem is with an instruction like ADD #1000,2, which adds the literal value 1000 to the value stored in register 2. In this case the number 1000 is encoded in the instruction, and there's no way to know if that number being used as an address or not. Out of context, there's no way to know if instruction has an encoded address within it or not.
An example like ADD #1000,2 in 16-bit x86 assembly language would be the following:
0068: 81 C3 EB 03    ADD BX, 1000

The last two bytes of the instruction EB 03 is the value of 1000 in decimal and is where the immediate (literal) operand of the instruction is encoded.  The instruction adds 1000 to the BX register.  It's not possible to know without more context whether 1000 is supposed to be an address or not. For example, the code might calculating the address of something located in a table starting at address 1000.
You might want to find another book, as it seems to spend a lot of time dealing with machine architectures that were obsolete 24 years ago and are completely archaic today.


text:
Q: Edit Model - Is there any better way? I have a WebGrid on my form with one of the column having ActionLink as:
Html.ActionLink((string)item.Name, "Edit", new { id = item.Id })

The purpose of below code is to show Edit screen as a Modal popup and post updated object successfully.
Controller - Get:
public ActionResult Edit(int id)
{
    ... //Fetch employeeViewModel @id
    TempData["StateData"] = employeeViewModel ;
    TempData["ViewState"] = "Edit";

    return RedirectToAction("Index");
}

Index.cshtml:
@if (TempData.ContainsKey("ViewState") && TempData["ViewState"].ToString() == "Edit")
{
    EmployeeViewModel employeeViewModel = (employeeViewModel)TempData["StateData"];
    @Html.Partial("_EditEmployee", employeeViewModel)

}

Edit form:

...

All this is working fine with complete cycle of Get/Post model for editing.
However, I am concerned about the extra trip that I am making in Controller-Get method:
return RedirectToAction("Index");

Can anyone please guide for a better approach?
Thank you!

A: Just a general pointer: you don't need to go to the server to pop up a modal dialog in the browser. You can do this just fine in javascript alone. Several of the common javascript libraries already have modal popups that you can use/customise/borrow etc. to suit your needs. Just google "javascript popup form" for lots of information.

A:
The purpose of below code is to show Edit screen as a Modal popup and post updated object successfully.

Before directly answering your question I want to talk about this for a moment. You need to be sure that a modal is the right choice. Is there some state you need to preserve? Does a modal present a better user experience? Does the modal work across platforms and with older technology?
Using modals is almost always more complicated than simply redirecting to another page and then back. Weigh the extra complexity against the user experience. If it isn't justified then abandon it. Also think about the weird situations you can end up with. What happens when your modal needs to open another modal?
Now the real question...How to make it work. In short, use AJAX.
@Html.ActionLink((string)item.Name, "Edit", new { id = item.Id })

Have this open the modal. The modal contains an AJAX form element (Ajax.BeginForm()) and POST that to your Edit action.
Now there is no redirection. When the action completes execute a javascript function setup through the Ajax form's AjaxOptions that closes the modal (or shows validation). The user never leaves the page through the whole process.


text:
Q: jQuery in ASP.NET not returning data I'm new to jQuery and have been reading a lot of tutorials. I am having trouble with my script not returning my data. I have a page called, "users.aspx". In the code-behind page I have a method called, "getUserDetails()", which doesn't matter because it never gets called. My javascript gets called by clicking a td, and it sends the user id to the javascript function. That part works fine (passing in the parameter, "userId"). My div changes values, my colors change, but in the AJAX block, something is wrong. I want to send the userId value to my web method in the code-behind page to update my div contents. Based on various tutorials, this looked like the way to go.
<script type="text/javascript">
    function loadDetails(userId)
    {
        //Set selected menu colors
        {
            $('td').css('backgroundColor', 'white'); //Reset all background colors to white
            $('#' + userId).css('backgroundColor', '#cccccc');
            $('#divrightcontent').html("Hi there");
        }

        //Get user details based on user id
        $.ajax({
            url: 'users.aspx/getUserDetails',
            data: { "uid": userId },
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                 alert('We got the data');
                $("#divrightcontent").empty();
                $("#divrightcontent").html(data);
            },
            error: function (data, status, jqXHR) { $("#divrightcontent").html(jqXHR); }
        });
    }
    </script>


text:
Q: Used display:none for media queries and scroll is wrong fullPage.js I used display:none for one of sections so its visible only on devices with less than 576px. And anchors are wrong, and scrolling jumps from second to first section. How to fix it?
This is the
page

A: According to GitHub's plugin docs, this is still an open issue that needs to be fixed by the lib's developer. What he mentioned as a workaround is destroying fullpage.js and reinitializing it again without the faulty section. (Whenever you are going to do that is up to you to find appropriate, whether on screen width resize, page loads, etc etc)


text:
Q: Proof by Strong Induction for $a_k = 2~a_{k-1} + 3~a_{k-2}$ $$\begin{align}
a_0 &= 1 \\
a_1 &= 1 \\
a_k &= 2~a_{k-1} + 3~a_{k-2} \quad \text{ for } k \ge 2
\end{align}$$
Proof by Strong Induction: For all non-negative integers $n$, $a_n$ is an odd integer.
Proof by Strong Induction:
$$\begin{align}
P(n) &= a_n \text{ is an odd integer } \\
P(0) &= a_0 \text{ is an odd integer } \\
\end{align}$$
Assume $P(n)$, show $P(n+1)$
Basis Step: $P(0)$, $P(1)$, $P(2)$, $P(3)$, $P(4)$, $P(5)$
Inductive Step: Want to show for all integers $n \ge 5$, if $P(i)$ is true for all $0 < i < n$, then $P(n)$ is true
Let $c > 5$, be arbitrary and fixed
IH: Assume $P(i)$ for any $0<i<c$
I don't know where to go in the proof from here. Can anybody help me show that $P(i)$ is always odd, I am confused with strong induction, too many variables are introduced.

A: *

*IH  the induction hypothesis is $p(i)$ is true for any :$0< i< c$

*Goal we want to prove that $P(c)$ is true

We can use :
$$a_c=\underbrace{2a_{c-1}}_{\text{even}}+\underbrace{3a_{c-2}}_{\text{odd}} $$
and IH implies that both $a_{c-2}$ and $a_{c-1}$ are odd so $a_{c}$ is odd hence $P(c)$ is true.

A: For example, $\,a_0 = 1 = a_1\,$ are both odd so $\,a_2 = 2a_1 + 3a_0\,$ = even + odd = odd. That is precisely how the general induction step is proved, i.e. for $\,k\ge 2\,$ prove in the same way that $\,a_k\,$ is odd, given that, by (strong) induction hypothesis, both $\,a_{k-1}\,$ and $\,a_{k-2}\,$ are odd.
Remark $\ $ Insight is gained by viewing things mod $2.\,$ Then the recurrence reduces to simply $\, a_k \equiv a_{k-2},\,$ so by induction  $\,a_{2n} \equiv \color{#c00}{a_0}\,$ and $\,a_{2n+1}\equiv \color{#c00}{a_1}.\,$ But both base cases $\,\color{#c00}{a_0,a_1}$ are $\equiv 1.$
If instead $\,a_0\equiv 0,\ a_1\equiv 1\,$ then, since $\,a_{n}\equiv a_{n\ {\rm mod}\ 2},\,$ we get $\,a_n\,$ is even $\iff n\,$ is even

A: You verified the base step and you have the induction assumption. Here's how you can use it:
$$
a_{k+1}=\underbrace{2a_{k}}_{\text{even times odd is even}}+\underbrace{3a_{k-1}}_{\text{odd times odd is odd}}
$$
Since an even number plus an odd number is an odd number, this proves your result. Note that strong induction was necessary to conclude that $a_{k-1}$ was odd. That's really all you need.


text:
Q: Series radius of convergence We have to find the values of $x$ for which the given series $\sum_{n=0}^{\infty}(-4)^n(x-5)^n$ is convergent.
We know that a geometric series converges if $|r| < 1$. We start by expanding:
$1+(20-4x) + (20-4x)^2 + (20-4x)^3 + \ldots$
$|r| = |(20-4x)| < 1$
This is where my question is. The book shows:
$19 < 4x < 21$
Which implies that they added $20$ to both sides. But $20$ is positive. What am I missing?
The book yields:
The series is convergent for: $19/4 < x < 21/4$

A: There are several ways to deal with the inequality.
One of them is to divide by $4$, and get
$$|5-x|\lt \frac{1}{4}.$$
This says that the distance of $x$ from $5$ is $\lt \frac{1}{4}$, which says that $x$ is between $5-\frac{1}{4}$ and $5+\frac{1}{4}$.
Another way is to unwind the inequality $|20-4x|\lt 1$ as
$$-1\lt 20-4x \quad\text{and}\quad 20-4x\lt 1.$$
The first inequality is manipulated to $4x\lt 21$, which gives $x\lt \frac{21}{4}$. The second inequality is manipulated similarly.
Remark: I would recommend looking up the Ratio Test or (better here) the Root Test.


text:
Q: How do i take a specific last value from MySQL So, I query a database and I succeed with this query:
$sql = 'SELECT * FROM log WHERE dokumen_name LIKE "%A12345%" ORDER BY Id DESC LIMIT 1';

and the result is this:

Then I want to take from the red box to put it in here:

di Posisi sekarang: <?php echo $row["lokasi"];  ?>

but it did not show up, how do I do that?

A:
di Posisi sekarang: <?php echo $row["Lokasi"];  ?>

Don't forget capitals

A: My code is right, turn out i query after
di Posisi sekarang: <?php echo $row["lokasi"];  ?>
 this code, so it will not work. so, i put the query before the di Posisi sekarang: <?php echo $row["lokasi"];  ?>
 and it works. soory for my misconception.


text:
Q: A question on probability and expectation concepts Let A be an observable event. If the expectation of A is zero, does it imply that the probability of A is zero?

A: In general the answer is no, it does not. Oftentimes $A$ can be a positive or a negative quantity, so it can average to zero even when it never actually takes the value of zero.
For example, if you are measuring the position of an object relative to you, you might find it to be $10$ metres in front of you half of the time and $10$ metres behind you the other half of the time. On average, the object is exactly at the same position as you (so the expectation value is zero), but there is zero probability of finding the object exactly where you are.


text:
Q: What can the second LAN port be used for on a NAS? I've got a NAS with 2 ethernet ports.  I have one connected to the router.  I read that the second could be connected to double the speed of data to and from the NAS.  I don't need to do that, as the speed from one port is adequate.  I use the USB port for backup.
I'm interested in using the second port if I can.  I just don't know enough to know what to use it for.  I may find something to use it for I only I knew what is possible.
What can the second LAN port on a NAS be used for, other than link aggregation?
Thanks for your help.
Added:
The NAS is a QNAP TS-251.

A: So "double the speed" is a bit of misnomer. It is possible to increase the throughput of the NAS by having two ports aggregated together generally this is not to a factor of two.
Also, it is worth noting that link aggregation is not only useful for increasing throughput, but it can also be used to handle link failure, so if a physical port goes down for any reason, you will still have connectivity to the device.
That being said, I don't know about your NAS software specifically, but it is possible then to run segregated services on the secondary port. You could run maintenance services on that NIC, or even the management software from that port. This way you can perform you file transfer functionality on one port, and the misc. services on the other - keeping the port free for file transfers.
On my NAS I like to have a management port, and then the port(s) through which the actually NAS stuff happens.


text:
Q: ¿Cómo adaptar el contenido dependiendo el tamaño de la pantalla? estoy tratando de mantener el tamaño de la pantalla al achicar el tamaño responsivo de la pantalla, adjunto imágenes para que se entienda mejor
En la siguiente imagen funciona todo bien, el tamaño de la pantalla es de 425px de ancho

Pero al bajar de los 425px pasa esto

Y al seguir achicando la pantalla se sigue achicando el contenido

¿Cómo hago para ajustar el contenido a pesar de seguir achicando la pantalla? Este es mi CSS con las media queryes que utilizo
@media (max-width : 1024px){
.header{
    height: 60px; /*achicamos el largo del header*/
}
.header .nav .logo{
    font-size: 1.563em; /*25px tamaño letra*/
    padding: 0 1.250em; /*20px de ancho*/
    line-height: 60px; /*alto de linea, logo centrado en el header*/
}
.header .nav .nav-menu{
    flex-direction: column; /*elementos del nav uno arriba de otro*/
    align-items: center; /*centramos los elementos*/
    background-color: #2c3e50; /*color del nav-menu*/
    position: fixed;
    left: 0;
    top: 60px; /*posicion de 60px para que se vea el header*/
    width: 100%; /*ancho del nav-menu*/
    height: calc(100vh - 60px); /*100% - altura del nav-menu*/
    overflow-y: auto; /*cada vez que se necesite el scroll/ruedita lo añadirá*/
    padding: 1.250em 0; /*relleno arriba y abajo 20px 0 a los lados*/
    left: 100%; /*importante para mover el menu de izquierda a derecha*/
    transition: left 0.3s; /*transición */
}
.header .nav .nav-menu .nav-menu-item{
    line-height: 70px; /*alto de linea elementos nav en menu*/
}
.header .nav .nav-menu .nav-menu-item a:hover{
    background: none;
    color: #ff9800; /*color al pasar el mouse por elementos nav*/
}
.header .nav .nav-toggle{
    display: block; /*ocultamos boton menu en laptops/pc*/
}
.header .nav .nav-menu_visible{
    left: 0; /*hacemos que el menu sea invisible*/
}
.banner{
    background-position:center; /*posición de imagen de fondo*/
}
.banner .banner-text{
    font-size: 200%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 170%; /*tamaño texto del banner*/
}
}

@media only screen and (min-device-width : 540px) and (max-device-width : 768px) {
.banner .banner-text{
    font-size: 150%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 130%; /*tamaño texto del banner*/
}
}

/*Iphone 6 7 8 VERTICAL*/
@media only screen and (min-device-width : 414px) and (max-device-width : 540px) {
.banner .banner-text{
    font-size: 110%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 100%; /*tamaño texto del banner*/
}
}

/*Pixel 2 XL - Pixel 2*/
@media only screen and (min-device-width : 411px) and (max-device-width : 414px) {
.banner .banner-text{
    font-size: 110%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 100%; /*tamaño texto del banner*/
}
}
/*iPhone X*/
@media only screen and (min-device-width : 375px) and (max-device-width : 411px) {
.banner .banner-text{
    font-size: 100%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 90%; /*tamaño texto del banner*/
}
}
/*Galaxy S5 - Moto G4*/
@media only screen and (min-device-width : 360px) and (max-device-width : 375px) {
.banner .banner-text{
    font-size: 100%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 90%; /*tamaño texto del banner*/
}
}
/*Galaxy Fold*/
@media only screen and (min-device-width : 280px) and (max-device-width : 360px) {
.banner .banner-text{
    font-size: 80%; /*tamaño texto del banner*/
}
.banner .banner-description{
    font-size: 70%; /*tamaño texto del banner*/
}
}

No entiendo porque no se respetan las media query, ayuda por favor.

A: Soy nuevo en el tema pero creo que es porque usas min-device-width y max-device-width, cuando deberias usar min-width y max-width ya que estos ultimos funcionan de acuerdo al tamaño en si del browser, o sea google.


text:
Q: Log4j programmatically add appender for package I'd like to output logging for a specific amount of time and for a selection of classes to a second file. Right now I use this code:
FileAppender appender = new FileAppender(new PatternLayout(PATTERN), filePath);
Logger.getRootLogger().addAppender(appender);
log.info("test");
appender.close();

This does work for logging for a limited time, but instead of specific classes, all my logging is output to the second logfile.
An alternative is using class specific logging:
FileAppender appender = new FileAppender(new PatternLayout(PATTERN), filePath);
Logger.getLogger(A.class).addAppender(appender);
Logger.getLogger(B.class).addAppender(appender);
Logger.getLogger(C.class).addAppender(appender);
log.info("test");
appender.close();

Which is closer to what I want, but it's hard to make an exhaustive list of the classes in use.
Is it possible to programmatically add an appender based on thread or based on package name?


text:
Q: MVC return a value from a jqueryui dialog modal I have a very simple dialog box that opens up on page ready, here is the code
this code is on my view
$(document).ready(
        //Dialog
        $("#dialog").dialog({
            title: "Dialog box",
            height: 300,
            modal: true,
            open: function(event, ui) {
                $(this).load("@Url.Action("TestDialogView", "Card")");
            }
        })
    );

now this opens up a dialog modal fine with the view contents of TestDialogView. Now what I would like to do is draw a table in the dialog (I can do this with the view), but what I want to try and do is, when the user clicks one of the items in the table, the ID of that item is then posted back to the view we are on, and the id is now passed into my model.
Example with steps

*

*step 1: Users loads up the CardTypes page

*step 2: The dialog box shows up with a list of items

*step 3: when clicking the "view" link in the table row

*step 4: the id of that item will be posted back from the dialog

*step 5: the dialog closes

*step 6: the variable SelectedId on the CardTypes view model is now populated with the id   posted back from the dialog.

Cheers
---update---
Here is a screen shot of my dialog,

and here is the view that renders it
@model CardSite.Models.FileSearchModel

@{
    ViewBag.Title = "Attacks";
}

        @Html.DisplayNameFor(x => x.Name)

        Select

@foreach (var item in Model.PokemonFiles)
{

            @Html.DisplayFor(m => item.Name)

        View

}

What do I need to change in my view? What should the "view" a link be?

A: You need to have a event delegation with .on():
var selectedId = '';
$("#dialog").on('click', '.table a', function(){
    selectedId = this.id;
});

or if you explain a bit more about your step 4.

As per your updated question i don't see any ID in your table or any tr, td or anchor is also not having any ID.
So now here i have changed my answer little bit:
$("#dialog").on('click', '.table a', function(){
    alert($(this).closest('tr').find('td:first').text());
});

The above code would give you the first td's text in alert relative to the link clicked.


text:
Q: JQuery | Add anchor and add / remove class on click Here is my jquery:
// Show all instances
    var link = $('Show all instances');

    $('tr.main').hide().first().find('.product').parent().remove('a').append(link);
    $('tr.main').first().show();

    $(function () {
        $(".show-instances").click(function (e) {
            e.preventDefault();
            $(".show-instances").addClass('selected').not(this).removeClass('selected');
            var selectedClass = $(this).closest('tr.main').attr('class').split(' ');
            $('.' + selectedClass[1]).not(':has("a.show-instances")').toggle();
            return false;
        })
    });

Adding the anchor works and on click adding the class works - I just don't understand why on click the class added "selected" won't remove when a user clicks the anchor the 2nd time?
So when a user clicks the anchor "show-instances" class "selected" will add to the anchor - I need the class to be removed when it's clicked again.
Am I missing another function?
Any suggestions?
/******RESOLVED*******/
Using the Toggle class - here is the jquery:
// Show all instances
    var link = $('Show all instances');

    $('tr.main').hide().first().find('.product').parent().remove('a').append(link);
    $('tr.main').first().show();

    $(function () {
        $(".show-instances").click(function (e) {
            e.preventDefault();
            $(this).toggleClass("selected");
            var selectedClass = $(this).closest('tr.main').attr('class').split(' ');
            $('.' + selectedClass[1]).not(':has("a.show-instances")').toggle();
            return false;
        })
    });

Also here is a Jsfiddle link to see

A: Based on what you're describing perhaps the toggleClass function would work better for you.
From the API documentation:

.toggleClass( function(index, class, switch) [, switch] )
  function(index, class, switch)A function that returns class names to
  be toggled in the class attribute of each element in the matched set.
  Receives the index position of the element in the set, the old class
  value, and the switch as arguments. switchA boolean value to determine
  whether the class should be added or removed.

Although this one seems pretty straightforward, it can also help if you post these type of questions up on jsfiddle so people can see what you're trying to achieve.

A: have you tried toggleClass() instead of removing and adding classes ?


text:
Q: Circular issue: Attempt to send form-url-encoded data causes TypeError: can't concat bytes to str, and the fix to latter breaks the former When I try to follow the answer to this question Python requests module sends JSON string instead of x-www-form-urlencoded param string and pass a dict to the urlopen, I get the error described in this question: Python 3.6 urllib TypeError: can't concat bytes to str
Code based on recommendation in answers from 1st question:
req = Request(url, method='POST', data={"ID": theId})
r = urlopen(req)

When I try to apply the accepted answer from the 2nd question and use this (similar to my original code) ...
urllib.request.urlopen({api_url}, data=bytes(json.dumps({"ID": theId}), encoding="utf-8"))

... I am right back where I started with the 1st question, as the passing of a json string in the data parameter forces application/json to be sent instead of  the x-www-form-urlencoded that I'm looking for:
Is there a way out of this circular trap?

A: Fixed by calling urllib.parse.urlencode to convert the dict to a string, and then explicitly setting the content-type:
    postparam = urllib.parse.urlencode({"ID": theId}).encode('utf-8')
    req = Request(url, method='POST', data=postparam)
    req.add_header("content-type", "application/x-www-form-urlencoded")
    r = urlopen(req)


text:
Q: Rails best practice: use before_filter or application_controller helper method? So I'm working on a big rails project. There are a bunch of classes that use the before_filter to set the @current_user variable (there are actually a ton of these before_filter methods for other variables, but I'm using this one for an example):
before_filter :current_user

Which calls the application controller's current_user method:
class ApplicationController < ActionController::Base

    def current_user
        @current_user ||= session[:user_id].present? ? User.includes(:memberships).find(session[:user_id]) : nil
    end

The other option is to use an application_controller helper method:
class ApplicationController < ActionController::Base
    helper_method :get_current_user

    def get_current_user
        @current_user ||= session[:user_id].present? ? User.includes(:memberships).find(session[:user_id]) : nil
    end

Then I replace all the @current_user references in the app with a call to the helper method:
get_current_user

This ensures that the method only gets called in the methods or views where it's needed, right? Is there a performance benefit to using the before_filter?

A: In your case both behave in the same way and are equal in the result you get - cached instance variable @current_user.
helper_method:

Declare a controller method as a helper. For example, the following
  makes the current_user and logged_in? controller methods available to
  the view

before_action (because before_filter is deprecated):

Append a callback before actions

Because of memoization being used the result is same in both cases.
The difference is that with before_action you are actually calling the method each time any action is called, whereas helper_method just provides you with a helper. If the logic performed in both was more complicated, indeed there would be a performance difference - before_action would be more resource consuming.
P.S. Two things are different, its uses are different and you can't really compare them.


text:
Q: DropDownList not showing SelectedValue in MVC Razor .net I attempt to create the dropdown list in the View. The dropdown list for "CD_STATE_CLASS" "IN_DIVIDED" is working but for "TOLL_ROAD", it can return option values in the dropdown list, but the selected value defined in the function is not presented.When I log the TOLL_ROAD in the console, i can see the value but not in the dropdown list. I have no idea where the problem is because code looks identical. And also, when i save the form, it seems like selected TOLL_ROAD value in the dropdown list is not passing to the Road object.
private void GetEditRoadSelectLists(Road road)
{
    var roadLookup = objMgr.GetRoadLookupDataBAL();

    ViewBag.RoadTypes = roadLookup.RoadTypeLookup;
    ViewData["CD_STATE_CLASS"] = new SelectList(roadLookup.StateClassLookup, "StateClassCode", "StateClassDescription", road.CD_STATE_CLASS);
    ViewData["IN_DIVIDED"] = new SelectList(roadLookup.YesNoLookup, "YesNoShort", "YesNoLong", road.IN_DIVIDED);
    ViewData["TOLL_ROAD"] = new SelectList(roadLookup.TollLookup, "Id","TOLL_ROAD", road.RoadsRamps.TOLL_ROAD);

    //ViewData["TOLL_ROAD"] = new SelectList(roadLookup.TollLookup, "TOLL_ROAD", "TOLL_ROAD", road.RoadsRamps.TOLL_ROAD);
    System.Diagnostics.Debug.WriteLine("toll"+road.RoadsRamps.TOLL_ROAD);
    System.Diagnostics.Debug.WriteLine("YES" + road.IN_DIVIDED);
}

    @Html.LabelFor(model => model.CD_STATE_CLASS, htmlAttributes: new { @class = "control-label col-md-2 required" })

        @Html.DropDownList("CD_STATE_CLASS", null, "-- Please select --", new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CD_STATE_CLASS, "", new { @class = "text-danger" })

    @Html.LabelFor(model => model.RoadsRamps.TOLL_ROAD, htmlAttributes: new { @class = "control-label col-md-2 required" })

        @Html.DropDownList("TOLL_ROAD", null, "-- Please select --", new { @class = "form-control" })

        @Html.ValidationMessageFor(model => model.RoadsRamps.TOLL_ROAD, "", new { @class = "text-danger" })


text:
Q: Is it useful to pass std::weak_ptr to functions? I was reading this article by Herb Sutter about passing smart pointers to functions. He doesn't mention std::weak_ptr and honestly I can't find a good scenario where passing such smart pointer is useful.
Does the function take ownership? Pass std::shared_ptr. Does the function just need to operate on the underlying object? Pass a raw pointer or a reference.
So is passing std::weak_ptr to functions 100% useless?

A: If your clients have a weak_ptr, and your logic could lock it or not, and is valid regardless, then pass a weak_ptr.
As a concrete trivial example:
mutable std::mutex m_mutex;
mutable std::vector<std::weak_ptr<std::function<void(int)>>> m_callbacks;

void clean_callbacks(int x) {
  auto l = std::unique_lock<std::mutex>(m_mutex);
  auto it = std::remove_if( begin(m_callbacks), end(m_callbacks), [](auto w){ return !w.lock(); } );
  m_callbacks.erase( it, end(m_callbacks) );
}
void call_callbacks() {
  clean_callbacks();
  auto tmp = [&]{
    auto l = std::unique_lock<std::mutex>(m_mutex);
    return m_callbacks;
  }();
  for (auto&& wf:tmp) {
    if(auto sf = wf.lock()) {
      (*sf)(x);
    }
  }
}

clean_callbacks has a lambda that takes a weak_ptr.  It is used to remove any m_callbacks whose lifetime has ended.
This code is used in a simple broadcaster where broadcasts happen far more often than listeners are invalidated, so waiting for the next broadcast to eliminate a dead listener is a good strategy.

A:
So is passing std::weak_ptr to functions 100% useless?

No.
Consider this toy example.
struct PointerObserver
{
    std::weak_ptr<int> held_pointer;

    void observe( std::weak_ptr<int> p )
    {
        held_pointer = std::move(p);
    }

    void report() const
    {
        if ( auto sp = held_pointer.lock() )
        {
            std::cout << "Pointer points to " << *sp << "\n";
        }
        else
        {
            std::cout << "Pointer has expired.\n";
        }
    }
};

In this example, a member function observe keeps the weak_ptr passed to it.  This is often called a "sink parameter".
This weak_ptr parameter communicates that this passed pointer is not owning, but reserves the ability to own at a later time, safely detecting if the pointer has expired.
As a different example, a function that doesn't hold state for later could also usefully receive a weak_ptr parameter in a multithreaded context where the associated data might expire  while the function is doing work.

A: Weak pointers are useful for holding on to objects that might not be available later on (without extending their lifetime). This means that they are usually used for storing in containers (or variables). One would usually pass a shared pointer until the object is stored and then converted to weak pointers. Then when used they must first be converted to shared pointers in order to check if they are still valid. Thus it's unlikely you will pass a weak pointer except as part of the storage and retrieval process, perhaps in helper functions.

A: The only benefit I can come up with having a std::weak_ptr instead of a std::shared_ptr as an argument in a function, is that the function becomes responsible for checking if the pointer is valid or not, reducing any checks outside the function.
bool function(std::weak_ptr _obj)
{
    if(std::shared_ptr obj = _obj.lock())
    {
        obj->doSomething();
        return true;
    }
    return false
 }

With a std::shared_ptr as an argument instead, the check is not needed, but a conversion to std::shared_ptr from std:weak_ptr is required before calling the function. Though if there is a risk a nullptr is passed, that needs to be checked aswell.
void function(std::shared_ptr _obj)
{
    _obj->doSomething();
}

So, if passing a std::weak_ptr to the function many times, from many different places in the application, I think I would prefer to have std::weak_ptr as argument, making the check in that function, instead of checking everytime outside the function. Naturally you will then get lesser lines of code.
Else though, if normally passing a std::shared_ptr, the check is naturally not needed inside the function, and the check if std:weak_ptr is valid inside the function, will be overhead.


text:
Q: Why does this command crash cmd? I came across a mind-blowing weird script that crashes the console:
set "h=/?" & call [if | for | rem] %%h%%

*

*IF, FOR and REM aren't normal internal commands.
They use an own special parser, which possibly caused some interception errors so it crashed.

@jeb pointed out CALL doesn't execute the following special characters, but instead convert them into a "token" (version dependent):

*

*& returns /

*&& returns 1

*| returns 2

*|| returns 0

*/? returns <

*@ returns +

*@() returns ;

*

*@if a==a : returns ,

*@for %a in () do : returns +

*@rem : returns -
However, even though they have unique parsers, it still doesn't explain why they all crash. So I did some testing:

*

*Remove call

    C:\>set "h=/?" & for %h%
    %%h%% was unexpected at this time.

*

*Change the command to something else. (I tried all other internal commands, none works)

*Seperate two commands:

    C:\>set "h=/?"
    C:\>call for %%h%%
    --FOR help message--

*

*Add @

    C:\>set "h=/?" & call for @%%h%%
    CRASH!!!

*

*Surround the scriptblock by ()

    C:\>set "h=/?" & call for (%%h%%)
    CRASH!!!

Summary of question:

*

*What role does call play?

*What caused the parser to crash?

A: The CALL is necessary to start a second round of the parser.
But there is a small bug (or more), in that phase it's not possible to execute any of the special commands or using &, |, &&, ||, redirection or command blocks.
The cause seems to be, that the parser build internally a token graph, replacing the special things into some kind of token values.
But with CALL the executer doesn't know anymore how to handle them.
This code tries to execute a batch file, named 3.bat !!!
(The name can be different, depending on the windows version)
set "cmd=(a) & (b)"
call %%cmd%%

But in your sample, the help function is triggered on a non executable token.
That seems to be the final death trigger for the executer to be completely out of sanity.

A: Summary of Research:
Calling linefeeds \n or FOR, IF & REM's help function crashes cmd, exiting with ERRORLEVEL -1073741819 aka 0xC0000005, which indicates an access violation error.
First, the cmd parser tries to start werfault to terminate the process.

If you prematurely terminate werfault, an error message will appear!

Access violation error:
  The instruction at 0x00007FF7F18E937B referenced memory at 0x0000000000000070. The memory could not be read.

It is conjectured that if, for and rem uses special parsers, but when the help function is triggered by call, a non-command token is returned, which crashes the cmd parser.

Sources:

*

*Why I can't CALL "IF" and "FOR" neither in batch nor in the cmd?

*CALL me, or better avoid call

*Limit CMD processing to internal commands, safer and faster?


text:
Q: How to code an if(condition) loop that keeps generating a random matrix until it gets a close enough match in R I am working with data simulation techniques that generate a random data set based off of a correlation matrix entered by the user. What I noticed after a while was that some randomly generated datasets were much closer to the actually correlation matrix than others. I wanted to create a function that 1) generates data sets, 2) compares correlation matrices with the original, and 3) repeats until there is a close enough match. Unfortunately, I was trained as a social scientist not a programmer and the "if/then" computer logic is harder for me to understand. Here is as far as I have gotten based on resources I found throughout the web:
    #Input Correlation Matrix
    sigma <- matrix(c(1.00, -0.03, 0.39, -0.05, -0.08,
                      -0.03, 1.00, 0.07, -0.23, -0.16,
                      0.39, 0.07, 1.00, -0.13, -0.29,
                      -0.05, -0.23, -0.13, 1.00, 0.34,
                      -0.08, -0.16 ,-0.29, 0.34, 1.00), nr=5, byrow=TRUE)
    rownames(sigma) <-c("Exercise", "Hardiness", "Fitness", "Stress", "Illness")
    colnames(sigma) <-c("Exercise", "Hardiness", "Fitness", "Stress", "Illness")

    #The Choleski Decomposition Random Data Generator
    N <- 373
    generate <-function(sigma) {
        L = chol(sigma)
        nvars = dim(L)[1]
        r = t(L) %*% matrix(rnorm(nvars*N), nrow=nvars, ncol=N)
        r = t(r)
        sample <- as.data.frame(r)}

    sample <- generate(sigma)

    # check if the empirical correlation is close to the theoretical sigma:
    correction <- function(sample) {
        zigma <- cor(sample)
        check <- all.equal(zigma, sigma, tolerance = .0025)
        if(check != "TRUE") {
        sample <- generate(sigma)
        correction(sample)
        }
        else
            return(check)
    }

And the error message I get upon running "correction(sample)" is:
    Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

What do you think is wrong with the if/else loop? Should I be trying to look at this problem from another perspective than loop logic?
Thank you all for your willingness to share your knowledge and expertise!

A: The approach of using a loop is fine, the problem is that you haven't got a loop -- you have a recursive call. You also don't need to write your own multivariate normal generator; mvrnorm in the MASS package does this already.
Try this.
library(MASS) # for mvrnorm
m <- rep(0, nrow(sigma))
repeat {
    samp <- mvrnorm(N, m, sigma)
    z <- cor(samp)
    close_enough <- isTRUE(all.equal(z, sigma, tolerance=.0025))
    if (close_enough) break
}


text:
Q: Building and Testing with MySQL Workbench for SSMS People I am great with Microsoft's SQL Server and SQL Server Management Studio (SSMS).
I'm trying to get things I used to do there to work in MySQL Workbench, but it is giving me very unhelpful errors.
Currently, I am trying to write an INSERT statement. I want to declare my variables and test it with a few values, then turn the end result into a stored procedure.
Right now, I have a syntax error that is not allowing me to continue, and the error message is not helpful either:

syntax error, unexpected DECLARE_SYM

There is no error list at the bottom and no way to copy the text of that error to the clipboard, so it all has to be studied on one screen, then flip to this screen so I can write it down.
Irritating!
The MySQL documentation surely has what I'm looking for, but I can learn much faster by doing than spending weeks reading their online manual.
DELIMITER $$

declare cGroupID char(6) DEFAULT = 'ABC123';
declare subGroupRecords int;
declare nDocTypeID int(11);
declare bDocActive tinyint(1) DEFAULT '1';
declare cDocID varchar(256) DEFAULT NULL;

  insert into dbo_connection.documents
  (group_id, subgroup_id, type_id, active, title, doc_id, priority, ahref, description, last_modified)
  values
  (cGroupID,cSubGroupID,nDocTypeID,bDocActive,cTitle,cDocID,0,ahref1, docDesc,NOW());

select * from dbo_connection.documents where group_id='ABC123';

END

So, for right now, I'm looking for why MySQL does not like my declare statement.
For the long term, I'm interested in finding a short article that shows a cookbook approach to doing some of the basic tasks that SQL developers would need (i.e. skips the Hello World program and discussion on data types).

A: DECLARE is only valid within stored programs.  In other words, unlike T-SQL, you can't build up your query and then wrap CREATE PROCEDURE around it to turn the end result into a stored procedure, you have to build it up as a stored procedure from the get-go.


text:
Q: Can't install any package due to error with library I am trying to install libv4l-dev on my system, but I get the following error:
Reading package lists... Done
Building dependency tree
Reading state information... Done
libv4l-dev is already the newest version (1.10.0-1).
The following packages were automatically installed and are no longer required:
  cabextract chromium-codecs-ffmpeg-extra gir1.2-gtk-2.0 gstreamer0.10-ffmpeg gstreamer1.0-plugins-bad-faad gstreamer1.0-plugins-bad-videoparsers libass5 libatk1.0-dev libavcodec-dev libavcodec-extra libavcodec-ffmpeg-extra56 libavformat-dev libavformat-ffmpeg56 libavresample-ffmpeg2 libavutil-dev libavutil-ffmpeg54 libbasicusageenvironment1 libbluray1
  libbs2b0 libcairo-script-interpreter2 libcairo2-dev libcddb2 libchromaprint0 libcrystalhd3 libdc1394-22 libdc1394-22-dev libdca0 libde265-0 libdirectfb-1.2-9 libdvbpsi10 libebml4v5 libfaad2 libflite1 libfluidsynth1 libgdk-pixbuf2.0-dev libglib2.0-dev libgme0 libgroupsock8 libgstreamer-plugins-bad1.0-0 libgtk2.0-dev libgtkglext1 libhal1-flash libharfbuzz-dev
  libharfbuzz-gobject0 libilmbase-dev libiso9660-8 libjpeg8-dev libkate1 liblivemedia50 libmatroska6v5 libmimic0 libmjpegutils-2.1-0 libmms0 libmodplug1 libmpcdec6 libmpeg2encpp-2.1-0 libmplex2-2.1-0 libmspack0 libofa0 libopenal-data libopenal1 libopenexr-dev libopenjpeg5 libpango1.0-dev libpcre3-dev libpcre32-3 libpcrecpp0v5 libpostproc-ffmpeg53
  libproxy-tools libqt5x11extras5 libraw1394-dev libresid-builder0c2a libschroedinger-1.0-0 libsdl-image1.2 libshine3 libsidplay2v5 libsnappy1v5 libsoundtouch1 libsoxr0 libspandsp2 libsrtp0 libssh-gcrypt-4 libssh2-1 libswresample-dev libswresample-ffmpeg1 libswscale-dev libswscale-ffmpeg3 libtbb2 libunshield0 libupnp6 libusageenvironment3 libva-drm1
  libva-x11-1 libva1 libvcdinfo0 libvlc5 libvlccore8 libvncclient1 libvo-aacenc0 libvo-amrwbenc0 libwildmidi-config libwildmidi1 libx265-79 libxcb-composite0 libxcb-shm0-dev libxcb-xv0 libxvidcore4 libzbar0 libzvbi-common libzvbi0 oxideqt-codecs-extra unshield vlc vlc-data vlc-nox vlc-plugin-notify
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 317 not upgraded.
1 not fully installed or removed.
Need to get 78,9 kB of archives.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://archive.ubuntu.com/ubuntu xenial/universe amd64 libjpeg62 amd64 1:6b2-2 [78,9 kB]
Fetched 78,9 kB in 0s (114 kB/s)
dpkg: error processing package libjpeg62:amd64 (--configure):
 package is in a very bad inconsistent state; you should
 reinstall it before attempting configuration
Errors were encountered while processing:
 libjpeg62:amd64
E: Sub-process /usr/bin/dpkg returned an error code (1)

I can't remove or reinstall libjpeg62 because every time it throws the very same error.
What can I do and how did this happen?


text:
Q: Distinguish between list of of tables and table How can I make the caption of the table different from that what shows up in the "List of Tables"
For figures I used the non-float option with: \figcaption[short title for the index]{description for your figures}
I would like exactly the same for a table.


text:
Q: Ajax Adobe AIR and Facebook Connect Is anyone aware of any Facebook Connect implementation for Adobe AIR Ajax. I know there is an Action Script (written by Facebook guys) but it seems that Facebook has forgotten about AJAX version for Adobe AIR.
Since Adobe AIR can't make calls via xd_receiver.htm would be quite usefull to have version written for Adobe AIR AJAX (not Flex)


text:
Q: Shiny/Datatable: leave row on fixed position while sorting I have a simple datatable table in Shiny report, say
renderDataTable(mtcars)

is it possible to make one of the rows (e.g. the Volvo 142E) have fixed position (always stay on the bottom), i.e. not to move while sorting the table using the up/down arrows, no matter by what column we sort? I assume that the row is uniquely identifiable, so there is no problem with pointing the row that should stay fixed.

A:     # this pgm will hopefully download time-series data from yahoo.finance
   # from a table listing the sp500 you will select 3 rows
   # one row designated by the setResponse button is the response variable to be predicted
   # in a regression
   # the next two rows will determine the explanatory vars  and is set by
   # the user pressing the selEVars button

                                  #   server.R
   library(shiny)
   library(googlesheets)
   library(DT)
   # the google sheet is a great way to store data
   sheet <- gs_title( 'tickerSymbols' )
   sp500 = gs_read_csv(sheet)   # it's a google sheet

   shinyServer(   function(input, output, session ) {

   # define sp500 symbol table for stock history lookup
   output$sp500Table = DT::renderDataTable( sp500 , escape=T )

    rsIndex = eventReactive( input$setResponse, {
    if( length( input$sp500Table_cell_clicked$row ) > 0 ) {
         setResponse = input$sp500Table_cell_clicked$row
         return( setResponse )
        } # end if
    }  # end code chunk
   )   # end obs evt fun
    # this sets the expl. vars  set in ui.R
   eVarIndex= eventReactive( input$selEVars, {
   if( length( input$sp500Table_rows_selected ) >= 2 ) {
   selEVars = input$sp500Table_rows_selected
   return( selEVars[2:3] )
   }  # end if
   }  # end code chunk for obs evt
   )   # obs evt fun
  # here is the probable location of problem
  # this data.frame does not show up unless i select 4 rows!
  observeEvent( input$sp500Table_rows_selected ,  {
   if( length(eVarIndex() ) >= 2  && length( rsIndex())>=1 ) {
        rs=c( rsIndex(), eVarIndex() )
    cc = c( 'response', 'expl. var. 1', 'expl. var. 2' )
    sel.df =  data.frame( description=cc, sp500[ rs ,  ] )
    output$tabO = renderTable( sel.df  )
    } # endif
    }  # end chunk

      }  # end server chunk fun
    )   # end shinyserver fun

      # the ui follows
      #  ui.R

   library(shiny)
   library(shinyBS)

   shinyUI(

   fluidPage(
   tags$style(type='text/css', ".shiny-table { color: blue; font-weight:
   bold;  font-size: 10px; line-height: 12px;}")
   ,  # ,

    bsCollapsePanel(
         h5("Select a response and 2 explanatory variables")
  , # ,
     # i hope the labels are self explanatory as to the objective
     actionButton( inputId = 'setResponse', label = 'set response variable'
      )
   ,  # ,
     actionButton( inputId = 'selEVars', label = 'select 2 explantory
                    variables' )
      ,  # ,
         actionButton( input='bldModel', label='build predictive model' )
        ,  # ,
    h6( 'selected variables for model construction' )
  ,  # ,    # and the problem table appears here!
    tableOutput( outputId='tabO' )
    ,  # ,
    br()
    , # ,
         DT::dataTableOutput( "sp500Table" )

      )  # end panel
     )    # end page

   )  # end UI


text:
Q: What's the meaning of "cross any of our desks"? So I saw this line from a TV drama (again) and couldn't understand it. Here is the line:

But Michaela Stone remains a person of interest in the most perplexing investigation ever to cross any of our desks.

What's the meaning of "cross any of our desks"? I was guessing "according to our records" or something like that.

A: The phrase to "cross my desk" or "come across my desk" is an idiom meaning to be introduced to/to see (usually in a working context).
In this context then, the sentence means "Michaela Stone remains a person of interest in the most perplexing investigation we have ever seen at work." (Emphasis mine).

A: Basically it's a variation on the idiom
"To cross one's path"
Which means "to encounter". The author substituted the word "desks" for "path" to emphasise the idea that the encounter happened at work.


text:
Q: Clear Array, before re-creating array to stop duplicate drop down options in Angular HTML SELECT when data refresh or reload I have an issue where my Angular array items are duplicated when I refresh data (basically on re-calling the method that creates the array), as it adds the same items to the pre-existing array.
This happens when I switch between accounts, by selecting one of the drop down account IDs in my <select>.
This is my HTML code from where I change the account/profile:

            Select Twitter Profile:
            <select ng-change="changeTwitterProfile()" ng-model="selectedTwitterProfileID" id="ViewTwitterProfile" ng-options="channelID for channelID in twitterChannels"></select>

This is the method in my Controller that creates the array of profile IDs:
function getChannelProfiles() {

    $scope.showSelectTwitterAccounts = true;

    GetUserAccessService.returnBrandProfileID().then(function (brandProfileID) {

        SocialMediaUserService.channelProfiles().then(function (channelProfiles) {

            channelProfiles.forEach(function (channel) {

                if (channel.brand_profile_id === brandProfileID && channel.channel_type === 'twitter') {

                    $scope.twitterChannels.push(channel.id);
                }
            });
            console.log($scope.twitterChannels);
        });
    });
}

This is the method that gets called when I switch accounts:
$scope.changeTwitterProfile = function () {

    $scope.dataModel = DataModelService.showDataLoadingAnimation();

    $scope.twitterPageMetrics = {};

    $scope.dataContent = false;

    $scope.showSelectTwitterAccounts = true;

    var twitterID = $scope.selectedTwitterProfileID;

    GetFusionDataService.getItems(getRequestURL(twitterID))

      .success(function (data) {
          handleDataRetrievalSuccess(data);
          getChannelProfiles();

      })

      .error(function (error, status) {
          handleDataRetrievalError(error, status);
      });

};

I understand why the duplication is happening. The array is not cleared, and I keep pushing the same IDs into the array.
I have tried a couple options to stop this, like adding
$scope.twitterChannels = [];

In the begging of my method that creates the view. This sets the array as an empty array as expected, and the array is recreated without duplicates.
HOWEVER, when I call my $scope.changeTwitterProfile method, everything works as planned, until it is time to create the array again. The array is cleared, and the data call is made to retrieve the data to filter for the array, but before the data is returned, the system steps into my $scope.changeTwitterProfile method, and by this time the array is still empty, and no profile is found. After this, the array gets created as it should.
Apologies for the long explanation - I just wanted to make it clear what i have tried and what happens.
I would appreciate your help.

A: As per my understanding ,
You are clearing an array of ids which represents options of select box.
Here are the steps that you took

*

*Clear an array  Made an $http call .

*There are two $http service calls

*fill the array with new elements

The reason you are seeing  no  drop-downs momentarily , is because angular runs digest cycle after $http promise are fulfilled. In your case , it runs  when  your first promise  GetUserAccessService.returnBrandProfileID() is fulfilled and your second promise  SocialMediaUserService.channelProfiles() is yet to be fulfilled.
There are two ways you can tackle this.

*

*Do not push identical elements in   $scope.twitterChannels.push(channel.id)

*Clearing  $scope.twitterChannels when second promise
SocialMediaUserService.channelProfiles() is fulfilled [in its resolve function].


text:
Q: Windows Phone 8.1 system logs I am having a rely hard time with my BackgroundTask, it seems to be terminated by the OS.
I cannot trust the Log, cause sometimes the BackgroundTask terminated in the middle of the line...
Is there any way to take a look at Windows Phone 8.1 system logs, or any other equivalent options?
Any help will be appriciated

A: No there are no system logs for windows phone 8.1.  You can use something like application insights, hockey app, xamarin insights, splunk mint, little watson to get better error messages for troubleshooting.
http://hockeyapp.net/features/
https://blogs.msdn.microsoft.com/andypennell/2010/11/01/error-reporting-on-windows-phone-7/
https://azure.microsoft.com/en-us/services/application-insights/
http://insights.xamarin.com/
https://splunkbase.splunk.com/app/1885/


text:
Q: Is there a way that I can have a file download within the success function of an ajax call? I have a site, and users can select data that they want to view. What I want is to dynamically create a file on the server side, and then have it download for the user in the success function of the ajax call.
What I currently have is a button
<div class='col-md-12 text-center'>
    <button class='btn btn-link' id='download-data-file'>Download Data File</button>
</div>

which when clicked should trigger the ajax call to create the file.
something like
$.ajax({
url: '/createDataFile/',
method: 'POST',
data: data,
datatype: 'json',
success: function(data, status, xhr){
    //Here Is where I am uncertain as to how to download the file for the user
    },
error: function(xhr, status, err) {
    //Some error code
});

For the purpose of this just assume that data is already a json.
There are a few things that I am uncertain of. 1. within my server side code (which is python) Should I return the file object that I create, or should I save the file to my local disk and then return the filename of the local file. 2. Within the ajax success function, how could I download the file that I just created for the user?
For clarity, I do not need any assistance with the creation of the file, just with actually downloading it for the user
Thanks!!

A: Create anchor tag with download attribute
Remove dataType:'JSON'
Use responce from ajax call in anchor tag to download. Add anchor tag to body and click on it.
success: function(data, status, xhr){
    var a = document.createElement("a");
    a.setAttribute("download","filename.json");
    a.setAttribute("href","data:application/json,"+data);
    document.body.appendChild(a);
    a.click();
    //document.body.removeChild(a);
}

var a = document.createElement("a");
a.setAttribute("download","fname.json");
a.setAttribute("href","data:application/json,{ 'num' : 5 }");
document.body.appendChild(a);
a.click();
console.log('Downloaded successfully!');


text:
Q: Why is my references section of my LaTeX document empty, and how can I change its name? In my document I have to specify the references I'm using. I used this code in the preamble:
\bibliographystyle{abbrv}
\bibliography{main}

Where main is the .bib file from the same folder, and contains, for example:
@string{jgr = "J.~Geophys.~Res."}

@MISC{primes,
   author = "Charles Louis Xavier Joseph de la Vall{\'e}e Poussin",
   note = "A strong form of the prime number theorem, 19th century",
   year = 1879
   }

@INBOOK{chicago,
   title = "The Chicago Manual of Style",
   publisher = "University of Chicago Press",
   edition = "Thirteenth",
   year = 1982,
   pages = "400--401",
   key = "Chicago"
   }

But at the References section nothing is displayed, when generating the .pdf. I have rebuild the .bib and the .tex file, without any changes.
And how can I change that default text, from References to Bibliografie or something else?

A: I think that you need to put \nocite{*} somewhere within your document -- putting it inside the preamble should cause LaTeX to throw a "cannot be used in preamble" error.  If they're still not appearing within your document, is LaTeX giving you any errors and, if so, can you tell us what they are?
To change the default text from "References" to whatever you would like, use the following command:
\renewcommand{\bibsection}{\section*{insert_title_here}}

Note that the asterisk after \section means that it won't be associated with a number.  If you want it to be associated with a number, just remove the asterisk.

A: You have to actually \cite references for them to be included in the bibliography. If instead you want everything in the bib file in the bibliography put \nocite{*} somewhere in the preamble. Read here what this actually does.

A: You have to either \cite or \nocite a reference for it to appear in your References section.  I'm not sure how to change the name of the bibliography.  I would start by looking at the LaTeX WikiBook.  It looks like there is a tool make makebst that produces a custom bibliography style - take a look at the custom-bib package and this document for more details.


text:
Q: how to save the command prompt output to an Microsoft 365 Excel or google spreadsheets (online) hello everyone i used a .bat file get all devise information and start to data entry it manually in google spreadsheet
https://github.com/hegazytarek/Device-information
but now i want this .bat file to import this data to Microsoft 365 Excel sheet or google spreadsheet
every new run recoded in new Row in same sheet
but i don't want just a code i want to learn how to achieve this thing but really i don't know from where should i start or how could i achieve my target
any help please and thanks for your time
my .bat file now can extartct the data in .txt file in the same dir. like this

my target to save this data in Microsoft 365 Excel sheet or google spreadsheet with the same format


text:
Q: Unable to open the db file in the real device Here is my code.  I have created a .db file using "sqlite browser" and placed into "assets"folder of my work space. But the '.db ' file is not copied into application path (when I checked in DDMS(data/data/com.example.trans/)  databases folder is not created). Also .db file is not copied from assets folder.
Here is my code:
public class ConnectionFactory  extends SQLiteOpenHelper{
    private static String DB_Path = "/data/data/com.example.translationapp/databases/";
    public static  String DB_Name = "Translator.db";
    public SQLiteDatabase myDb;
    File dbFile;
    public Context con;

    public ConnectionFactory(Context context) {
        super(context, DB_Name, null,1);

        // TODO Auto-generated constructor stub
        this.con= context;
    }

    public void OpenDb() throws IOException
    {
        boolean dbCheck = checkDb();
        if(dbCheck)
        {

        }
        else
        {
            this.getWritableDatabase();
            try
            {
                copyDatabase();
            }
            catch(IOException e)
            {
                throw new Error("Sorry");
            }
        }
    }
    public boolean checkDb() throws IOException
    {
        SQLiteDatabase checkDb =null;
        try
        {
        String myPath = DB_Path+DB_Name;
        checkDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }
        catch(SQLiteException e)
        {

        }
        if(checkDb!= null)
        {
          checkDb.close();
        }
        return checkDb !=null ? true:false;
    }
   public void copyDatabase()throws IOException
   {
       try
       {
       File filetext = con.getFileStreamPath(DB_Name);
       boolean exists = filetext.exists();
       if(!exists)
       {
       String outFileName = DB_Path+ DB_Name;

       myDb=con.openOrCreateDatabase(outFileName, Context.MODE_PRIVATE, null );
       OutputStream myOut  = new FileOutputStream(filetext.getAbsolutePath());
       InputStream myin = con.getAssets().open(DB_Name);
       byte[] buffer = new byte[1024];
          int length;
          while((length = myin.read(buffer))>0)
          {
              myOut.write(buffer,0,length);
          }
          myOut.flush();
          myOut.close();
          myin.close();
       }
       }
       catch(IOException e)
       {
           e.printStackTrace();
       }

   }
   public void openDatabase() throws SQLException
   {
      String myPath = DB_Path+DB_Name;
     myDb = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

   }
   public synchronized void close()
   {
      if(myDb != null)
      {
         myDb.close();
          super.close();
      }
   }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

A: Instead of hardcoding db path in assets folder, just use this   -
private static String DB_Path = "/data/data/"+getPackageName()+"/databases";


text:
Q: Use stripe in Nuxtjs I am a newbie in the programming world. Recently I am encountering difficulty in setting up stripe payment in my nuxt web app. I tried to follow the stripe official document, but it didn't redirect me to the stripe checkout page as expected. Instead, it redirected me to my localhost checkout page while it doesn't exist. I am really appreciated that if you could tell me what I did wrong. Many thanks in advance. Below is my code.
Frontend
    <template>

Stubborn Attachments

$20.00

      <form action="/create-checkout-session" method="POST">
        <button type="submit" id="checkout-button">Checkout</button>
      </form>

</template>

Backend
const express = require('express')
const app = express()
const cors = require('cors')
app.use(express.json())
app.use(cors())

const stripe = require('stripe')(process.env.STRIPE_PRIVATE_KEY)

const YOUR_DOMAIN = 'http://localhost:8000';

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    line_items: [
      {
        // Provide the exact Price ID (for example, pr_1234) of the product you want to sell
        price: 'price_1XXhOEFTCdQ1tcSK1ALR8CXQ',
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: `${YOUR_DOMAIN}/success`,
    cancel_url: `${YOUR_DOMAIN}/cancel`,
  });

  res.redirect(303, session.url);
});

const port = process.env.PORT || 4002

app.listen(port, ()=>{
    console.log(`App listening on port ${port}!`)
})


text:
Q: Error: file does not start with RIFF id This line of code is throwing an error:
import wave
...
wave.open('/path/to/wavfile/1a.wav', "rb")

The 1a.wav is in the NIST SPHERE format. I don't have much experience with the wav formats, but is there anyway I could transform it into RIFF format so that I can open it with the "wave" library?
Thank you in advance!

A: Use ffmpeg to convert. e.g.
ffmpeg -i test.wav -acodec pcm_s16le -ac 1 -ar 16000 out.wav


text:
Q: Grails 2.3+ looking for jar in local maven repo for **plugin** Okay, after a solid day I've solved my problem but think this MUST be a bug.  I started in grails 2.3.2 and upgraded to 2.3.4, all the same
My grails app is divided up into plugin: a base plugin that has core domain objects and some interfaces, N "factory" plugins that require the base plugin and one app, that can include any number of the "factory" plugins.  All of these plugins, for now, are local (not in any external maven repo)
So this is what people are calling the 'transitive' plugin issue.  What I'm seeing is that I write the base plugin and use 'maven install' to put it into my local repo (the ~/.m2/repository...).  Fine.  Then I write one of the "factory" plugins where in the BuildConfig under the 'plugins' section I put the 'base' plugin.  It compiles and packages fine, but when I run 'maven-install' it says:

| Error Could not find artifact pkg-blah:name-blah:jar:ver-blah in
  grailsCentral (http://repo.grails.org/grails/plugins) (scope: compile)
  (Use --stacktrace to see the full trace)

Now, beyond the s there's something I didn't see for about 6 hours.  The 'jar'. See it there?  I didn't for a LONG time.  A very LONG, frustrating time. Why is it looking for 'jar' when it's been put into the 'plugins' section of the BuildConfig?  That, to my understanding, is only when it's in the 'dependencies' section.
I think that's the bug.  Let me know how wrong I may or may not be.  Dunno.  I'm no Grails God, just an everyday user.
Oh, the fix:  use grails create-pom, put 'pom true' into the BuildConfig, then edit the pom and under the dependencies section of the pom for the plugins, add in <type>zip</type>. Oh, default packaging at the top of the pom is 'grails-plugin' or something.  Change it to 'zip'.  Then all is fine.
Just dunno why it's defaulting to 'jar' for a plugin.  Edify me!


text:
Q: NHibernate Criteria query on in-memory collection of entities I would like to apply a Criteria query to an in-memory collection
of entities, instead of on the database. Is this possible?
To have Criteria API work like LINQ? Or alternatively, convert
Criteria query to LINQ query.
Thanks!

A: I don't believe you can use Criteria to query against an in-memory collection and come to think about it it doesn't seem to make much sense. If I'm understanding everything correctly you've already queried against your database. I'd suggest to either tune your original query (whichever method you choose) to include all of your filters. Or you could use LINQ (as you suggested) to refine your results.
Also, what's your reasoning for wanting to query from memory?

A: It sounds like you're rolling your own caching mechanism. I would highly recommend checking out NHibernate's 2nd level cache. It handles many complex scenarios gracefully such as invalidating query results on updates to the underlying tables.
http://ayende.com/Blog/archive/2009/04/24/nhibernate-2nd-level-cache.aspx


text:
Q: Attribute values are missing while adding new node to xml payload using mule 4 I'm trying to add the new child node(ValidationError) to the existing xml payload using the below dataweave code:
%dw 2.0
var errormessage = "Rating Service Exception Error. Please contact support."
output application/xml writeDeclaration=false
---
DTOApplication : payload.DTOApplication ++ { ValidationError @(TypeCd: "Validation", Name: "Rate Service Exception Error", Msg: errormessage, SubTypeCd: "ERROR") :null}

The ValidationError child node appends perfectly, but the attribute values of the root node DTOApplication are missing.
Input payload: https://github.com/Manikandan99/Map_request/blob/main/request_payload.xml
Expected response: https://github.com/Manikandan99/Map_request/blob/main/Expected_response.xml
The new child node is ValidationError :
<ValidationError TypeCd="Validation" Name="Rate Service Exception Error" Msg="Rating Service Exception Error. Please contact support." SubTypeCd="ERROR"/>

Any ideas please on how to append ValidationError child node to existing payload without missing the attribute values of DTOApplication using dataweave 2.0?

A: Could you Please try below code, its giving expected output
%dw 2.0
var errormessage = "Rating Service Exception Error. Please contact support."
output application/xml  writeDeclaration=true
---
payload mapObject ((value, key, index) ->
  (key): value ++ {
    ValidationError @(TypeCd: "Validation", Name: "Rate Service Exception Error", Msg: errormessage, SubTypeCd: "ERROR"): null
  }
)

A: The problem your script has is that it uses the value of the node DTOApplication but ignores that it has attributes. I'm providing a simple fix but @Anurag Sharma solution seems better because it is generic.
%dw 2.0
var errormessage = "Rating Service Exception Error. Please contact support."
output application/xml writeDeclaration=false
---
{
    DTOApplication @((payload.DTOApplication.@)) : payload.DTOApplication ++ { ValidationError @(TypeCd: "Validation", Name: "Rate Service Exception Error", Msg: errormessage, SubTypeCd: "ERROR") :null}
}


text:
Q: Film - a book is the villain's weak spot I remember when I was a kid ('90) my older siblings and cousins were watching a movie and I saw some parts of it. I wonder what the movie is called.
It was some kind of horror. There were a group of people and these people were running from a man (like in no other horror movie ;)), but what was significant in this movie was that there was a magic book. It seemed like the bad guy was vulnerable only by that magic book and when these people were stabbed the book, the man was bled and his blood was black.
Is there any movie like this or was it just my imagination?


text:
Q: What happened to "allow application to interact with desktop" checkbox in cluster manager for server 2008? The cluster managing software for managing clusters on a windows server 2005 cluster had a checkbox for "allow application to interact with desktop" when creating a generic application resource.  This appears to be gone in the management software for server 2008 clusters.  Does anyone know where this option, if it still exists, is?

A: From MattB on ServerFault, got this response.

This option was removed in Server 2008 as a security enhancement. This is because the application runs as the cluster service account which has elevated privileges.
Even in 2003 clusters, the security best practice was to not have this checked.


text:
Q: Trying to learn WSDL and getting this "simple" SOAP JavaScript client to work I was looking an old thread over 5 years ago asking for the most simplest SOAP code using Javascript.
This was the most highest rated comment and marked as answered:
<html>
<head>
    <title>SOAP JavaScript Client Test</title>
    <script type="text/javascript">
        function soap() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open('POST', 'https://somesoapurl.com/', true);

            // build SOAP request
            var sr =
                '<?xml version="1.0" encoding="utf-8"?>' +
                '<soapenv:Envelope ' +
                    'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
                    'xmlns:api="http://127.0.0.1/Integrics/Enswitch/API" ' +
                    'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
                    'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' +
                    '<soapenv:Body>' +
                        '<api:some_api_call soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
                            '<username xsi:type="xsd:string">login_username</username>' +
                            '<password xsi:type="xsd:string">password</password>' +
                        '</api:some_api_call>' +
                    '</soapenv:Body>' +
                '</soapenv:Envelope>';

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    if (xmlhttp.status == 200) {
                        alert('done. use firebug/console to see network response');
                    }
                }
            }
            // Send the POST request
            xmlhttp.setRequestHeader('Content-Type', 'text/xml');
            xmlhttp.send(sr);
            // send request
            // ...
        }
    </script>
</head>
<body>
    <form name="Demo" action="" method="post">
        <div>
            <input type="button" value="Soap" onclick="soap();" />
        </div>
    </form>
</body>
<html>

I've tried to copy and paste it into a .html to get it running so I can see how it works, but it still doesn't work. In line-7 of the code, I replaced
https://somesoapurl.com/

with an actual free WSDL URL I found from searching on Google:
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

When I click on the "Soap" button and look at the console to see the code run, I get the following error:

XMLHttpRequest cannot load
  http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL. Response to
  preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access. The response
  had HTTP status code 405.

Can someone assist? I want to get this SOAP client call using JavaScript working so I can understand WSDL and SOAP better.


text:
Q: using model forms to save data in different databases Ok the problem is that I have a model in which a field is unique. I am inputting that field value from user in post body and wanted to save that via model form in a database that is also specified in post body.
# models.py
class Type(models.Model):
    name = models.CharField(max_length=100, unique=True)
    created_at = models.DateTimeField(auto_now_add=True, editable=True)

    def __str__(self):
        return self.name

#forms.py
class TypeCreateForm(forms.ModelForm):
    class Meta:
        model = Type
        fields = "__all__"

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "default",
        'USER': 'root',
        'PASSWORD': 'abcd1234',
        'HOST': '0.0.0.0',
        "PORT": "3306"
    },
    'database1': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "database1",
        'USER': 'root',
        'PASSWORD': 'abcd1234',
        'HOST': '0.0.0.0',
        "PORT": "3306"
    },
}

#views.py
def index(request):
    db_name=request.POST["db_name"]
    ob = TypeCreateForm(request.POST)
    for a in ob:
        if a.errors:
            print(a.errors.as_text())

    ob=ob.save(commit=False)
    ob.save(using=db_name)

I searched several similar question of saving into another database other than default.Some suggested commit=False will work along with save with using keyword argument.
In some answer they suggested to do modification in queryset of the field.
But I dont think that worked for me because in my model there is a unique constraint as well so when I will print the errors before saving it will show unique constraint failed if that type is stored in default db even if I might want to save in the second database.
Isn't there any way that I can make such that while initiating a form object I also specify the db name and it will save into that db and errors will also come corresponding to that selected db
Also I cant use Type.objects.using(db_name).create()
because I may add validations as well later that can only be checked via forms.


text:
Q: Splitting tasks in gulp Right now I have multiple gulpfiles. Everytime I get to work I need to run mulptiple "gulp --gulpfile path/to/another-gulpfile.js". Can I run it with one command? I tried "gulp --gulpfile gulpfile1.js gulpfile2.js gulpfile3.js", but it didn't work.
EDIT:
  "scripts": {
    "gulp": "gulp --gulpfile bin/gulp-tasks/config.js && gulp --gulpfile bin/gulp-tasks/deploy.js"
  }

I tried running multiple gulp instances using npm scripts, but it looks like only watchers from first specified gulpfile are working. Simple console.logging showed, that second gulpfile was not even started. They do work perfectly when launched separately.

A: one way you can try put your gulp command in npm package.json
scripts: {
  gulp: gulp --gulpfile path/to/gulpfile1.js && gulp --gulpfile path/to/gulpfile2.js
}

then you can run one command npm run gulp;
the other way you can refer to this post for more details
http://macr.ae/article/splitting-gulpfile-multiple-files.html


text:
Q: Auto close popup message "open method of workbooks class failed" I am trying to convert a batch of excel files into PDF using Doc2PDF software. Sometimes a corrupt excel comes in a batch and throws an error message "_open method of workbooks class failed". Is there any way to disable windows popup in batch file or using .vbs ? As i don't want my automation job to halt until i click close to the error popup

My current batch script :

echo "Starting Dev Filewatcher 2 ....."
@echo off
set PATH=%PATH%;C:\Program Files\docPrint Pro v5.0
perl C:\Script\Test\xyz.pl -DbgMsgLevel 9 ^
-IncomingDir C:\Script\incoming ^
-ProcessDir C:\Script\process ^
-SuccessDir C:\Script\success ^
-FailDir C:\Script\fail ^
-ExceptionsDir C:\Script\exception ^
-OutgoingDir C:\Script\outgoing ^
-SleepInt 1 ^
-ConvertCmd "doc2pdf.exe -s SilentPrintOffice=1 -b 1 -i"


text:
Q: Partial-screen WebView with  cut in half I have a tablet application with a split layout - a list on the left, and a detail pane on the right.  The right-hand pane is a WebView, and it contains a <video> tag.  That's all working fine, except the entire right-hand side of the WebView is cut off and renders plain white.
Why is it rendering this way, and how can I avoid it without inserting a huge hack?
I have boiled it down to a simple test project, which I've posted on github.
Here is a screenshot: http://d.pr/i/dfEh.
The grey area along the left is where the list view belongs. I have changed it to an empty FrameLayout for simplicity.  The cut off portion along the right side of the WebView IS the same width as the list view.  It's also worth noting that any content below the video is also cut off--the white area extends the full height of the WebView.
Some things I've tried:

*

*replace the list view with something else

*enable and disable WebSettings: javascript, use wide viewport, load with overview mode

*set a WebViewClient and a WebChromeClient

*turn hardware acceleration on and off

*various settings in View.setScrollBarStyle, WebView.setVerticalScrollBarOverlay, and similar

*tweak the <video>'s height/width attributes and styles

*various video formats, including mp4 with h264 and aac, m3u8, and a youtube rtsp stream

*various devices, including the Fire HD shown, a Nexus 7, a Galaxy 10.1, and a Xoom

*Android versions 3.1, 3.2, 4.0, 4.1

Current workaround:
I ended up working around this by using a full-screen WebView, overlaying my list view on top of it, and setting a left margin on the outermost container element in the html.  This is rather hacky, and getting the size of the list view on various densities and resolutions is error-prone, so I would really like to solve this the right way.
Snippets:
As I mentioned, a (non-) working test bed is posted on github, but here are the important bits:
Html loaded into the WebView (this is ALL of it):
<html>
<head><title>Title</title></head>
<body style="margin:0">
    <video x-webkit-airplay="allow" controls="controls" style="width:100%">
        <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"></source>
    </video>
</body>
</html>

The main layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <fragment android:name="com.concentricsky.android.webviewvideotest.ListFragment"
        android:id="@+id/item_list"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

    <!-- The WebView is attached here -->
    <FrameLayout android:id="@+id/detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

</LinearLayout>

In onCreateView:
    View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
    webView = (WebView) rootView.findViewById(R.id.webview);
    webView.setWebChromeClient(new WebChromeClient());
    webView.loadUrl("file:///android_asset/test.html");
    return rootView;

I am really scratching my head over this one, and I'm surprised I haven't been able to find any mention of it. Any input is appreciated, however far-fetched.

A: The problem seems to be with the hardware/opengl layer. Since the VideoView uses an hardware layer to render the video I believe that the same happens with the webView with a video.
So if you set the layers right, they shouldn't interfere with each other, so like I said on the coments, you should set the ListView to layer none or software, to disable the hardware acceleration and enable it on the webView or the window.
More info about the hardware acceleration at http://developer.android.com/guide/topics/graphics/hardware-accel.html#controlling

A: I had the same problem, it had to with me using a relative layout. The layer it renders the video to, does not move with the webview. So it will render the video as if the webview was positioned at 0,0.
You can work around this by actually position the webview at 0 0, behind any components that may already be there. Then in css give the content a margin to position it on the correct spot.
It may not be clean, but I haven't found another solution.
EDIT: After taking a better look at your question I think it doesn't have anything to do with the relative layout as you're not using one. Nevertheless this workaround worked for me. So I guess the 'Video layer' stays at 0,0 no matter what layout you're using. I only came across this problem on a Galaxy Tab 2(android 4.0.3) by the way.

A: I had the same issue in a master/detail flow layout. By setting the layer type to software my video being cut in half issues were gone. This turns off hardware acceleration for the webview.
webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

FYI I only experienced this issue on Amazon Tablets.