text:
Q: Is this an implementation of a fixpoint combinator? I presumed this couldn't be called "fixed point recursion" because it was too straightforward.  However, I recently realized it actually might be.
Have I effectively implemented fixed point recursion?
Here's the function in question:
/* recursive kleisli fold */
var until = function(f) {
    return function(a) {
        return kleisli(f, until(f))(a);
    };
};

Here's some additional context:
// The error monad's bind
var bind_ = function(f, m) { return m.m === Success ? f(m.a) : m; };

var bind = function(f, m) {
    return m !== undefined && m.m !== undefined && m.a !== undefined ? bind_(f, m) : m;
};

var kleisli = function(f1, f2) {
    return function(a) {
        return bind(f2, f1(a));
    };
};

The rest of the code is here, but the snippet above should be enough to follow.

A: The definition of a fixed-point combinator is a function F which takes a function f and returns a function p such that
Given F(f) = p then p = f(p)
There are many possible fixed point combinators that could be written. Don't let the straightforwardness make you think that something isn't a fixed-point combinator; here is a standard definition in JavaScript, which is very simple:
  var fix = function(f) {
       return function(x) {
        return f(fix(f))(x)
      }
  };

A usage might be then to compute the fixed-point for factorial, with:
var fact = function(f) {
              return function(n) { return (n == 0) ? 1 : (n * f(n - 1)) }
           };

alert(fix(fact)(7)); // alerts us with 5040.

For an example of a different fixed point combinator (the Y combinator) see this helpful blog post.
Let's see if your until combinator computes fixed-points. Since you are working with monadic functions the fixed-point definition changes slightly to handle the monadic structure, where F is a (monadic) fixed-point combinator when
Given F(f) = p then p = f*  . p
where f* . p means the Kleisli composition of the function p with the function f (in your code you would write this kleisli(p, f), you can think of * as bind). I'll use this notation as it is shorter than writing JavaScript.
Let's unroll the definition of until then and see what we get:
until(f) = (until(f))* . f
         = (until(f)* . f)* . f
         = ((... . f)* . f)* . f
         = ... . f* . f* . f     (associativity of bind for a monad: (g* . f)* = g* . f*)
         = p

Does p = f* . p?
... . f* . f* . f  =?=  f* . ... . f* . f* . f

Yes- I believe so. Although I don't think this is a useful fixed point. (I'm afraid I don't have a good argument for this yet- but I think this is basically a greatest-fixed point which will just diverge).
To me, it looks like the arguments to kleisli in until should have been swapped. That is, we wish to do the Kleisli equivalent of application in the fix example, so we need to pass the monadic result of the recursive call until(f) to f:
  var until = function(f) {
      return function(a) {
          return kleisli(until(f), f)(a);
      };
  };

Let's unroll this new definition of until:
until(f) = f* . until(f)
         = f* . (f* . until(f))
         = f* . f* . ...
         = p

Does p = f* . p? Yes it does:
f* . f* ... = f* . (f* . f* . ...)

since adding one more composition of f* onto an infinite chain of f* composition is the same function.
Using your kleisli function I had some problems with divergence (some evaluation is happening too soon so the computation runs until I run out of stack space). Instead, the following seems to work for me:
 var until = function(f) {
     return function(a) {
        return bind(f,until(f)(a));
    };
 };

For more on fixed-points for monadic code you might like to check out the work of Erkök and Launchbury.


text:
Q: Psychopy TextStim Bounding Box Is it possible to control the width of a bounding box for a text stim? I know the parameter is read only but it adjusts to changes in the size of the text or the length of a word. I'd like to display some text across one line at a large size but it always spreads it out over two lines. If I add the underscore it fits on the screen but I replace the _ with a space and it goes back to two lines.
>>> from psychopy import visual
>>> win=visual.Window([1920,1080])
>>> ts=visual.TextStim(win,'some text')
>>> ts.height=.6
>>> ts.autoDraw=True
>>> win.flip()           ###Shows 'Some text' over two lines in .6 height
45.916739664040506
>>> ts.boundingBox
(794, 724)
>>> ts.height=.4
>>> win.flip()          ###shows 'some text' over one line in .4 height
81.28536250023171
>>> ts.boundingBox
(942, 241)
>>> ts.height=.6
>>> ts.text='some_text'
>>> win.flip()         ###shows 'some_text' in one line in .6 height
113.71247935923748
>>> ts.boundingBox
(1500, 362)
>>> ts.text='some text'
>>> win.flip()        ###shows 'some text' in two lines in .6 height
139.62244182173163
>>> ts.boundingBox
(794, 724)
>>>

----> How do I expand the width of the bounding box so that text stays on one line?
THANKS!

A: Found the answer: Use wrapWidth.
ts.wrapWidth=2

resolved the issue

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copying data after deleting empty rows in Google Sheets using Apps Script? The following code is working fine. It is sorting, removing duplicates and deleting empty rows. Then I just want to copy the rows of data to after the last data row. But the code is copying the rows of data with empty rows. Need to avoid empty rows while copying

var column = 3;
range.sort({column: column, ascending:true});
range.removeDuplicates([column]);

//now delete empty rows if any
for (var i = range.getHeight(); i >= 1; i--){
    if(range.getCell(i, 1).isBlank()){
            sheet.deleteRow(range.getCell(i, 1).getRow());
    }
}
//For Double periods in a class
var dataToCopy = range.getValues(); //Gets the values of the source range in a 2 dimensional array
var copyData = sheet.getRange(range.getLastRow()+1,1,dataToCopy.length,dataToCopy[0].length).setValues(dataToCopy);

A: I believe your goal as follows.

*

*After the for loop in your script was finished, you want to retrieve the values without the empty rows.

For this, how about this answer?
Modification points:

*

*In this answer, the number of delete rows is counted and the number is reduced from range of range.getValues();. By this, dataToCopy doesn't include the empty rows.

When above points are reflected to your script, it becomes as follows.
Modified script:
var column = 3;
range.sort({column: column, ascending:true});
range.removeDuplicates([column]);

//now delete empty rows if any

var deleteRows = 0;  // <--- Added

for (var i = range.getHeight(); i >= 1; i--){
    if(range.getCell(i, 1).isBlank()){
      sheet.deleteRow(range.getCell(i, 1).getRow());
      deleteRows++; // <--- Added
    }
}
//For Double periods in a class
var dataToCopy = range.offset(0, 0, range.getNumRows() - deleteRows).getValues();  // <--- Modified
var copyData = sheet.getRange(sheet.getLastRow()+1,1,dataToCopy.length,dataToCopy[0].length).setValues(dataToCopy); // <--- Modified

*

*If you want to put the values to the last row of range, please modify the last line to the last line of your script.

References:

*

*offset(rowOffset, columnOffset, numRows)

*getLastRow() of Class Sheet


text:
Q: TCL - find a regular pattern in a file and return the occurrence and number of occurrences I am writing a code to grep a regular expression pattern from a file, and output that regular expression and the number of times it has occured.
Here is the code: I am trying to find the pattern "grep" in my file hello.txt:
set file1 [open "hello.txt" r]
set file2 [read $file1]
regexp {grep} $file2 matched
puts $matched
while {[eof $file2] != 1} {
set number 0
if {[regexp {grep} $file2 matched] >= 0} {
 incr number
}

puts $number
}

Output that I got:
grep

--------
can not find channel named "qwerty
iiiiiii
wxseddtt
lsakdfhaiowehf'
jbsdcfiweg
kajsbndimm s
grep
afnQWFH
 ACV;SKDJNCV;
    qw  qde
 kI UQWG
grep
grep"
    while executing
"eof $file2"

A: It's usually a mistake to check for eof in a while loop -- check the return code from gets instead:
set filename "hello.txt"
set pattern {grep}
set count 0

set fid [open $filename r]
while {[gets $fid line] != -1} {
    incr count [regexp -all -- $pattern $line]
}
close $fid

puts "$count occurrances of $pattern in $filename"

Another thought: if you're just counting pattern matches, assuming your file is not too large:
set fid [open $filename r]
set count [regexp -all -- $pattern [read $fid [file size $filename]]]
close $fid

A: The error message is caused by the command eof $file2. The reason is that $file2 is not a file handle (resp. channel) but contains the content of the file hello.txt itself. You read this file content with set file2 [read $file1].
If you want to do it like that I would suggest to rename $file2 into something like $filecontent and loop over every contained line:
foreach line [split $filecontent "\n"] {
  ... do something ...
}

A: Glenn is spot on. Here is another solution: Tcl comes with the fileutil package, which has the grep command:
package require fileutil
set pattern {grep}
set filename hello.txt
puts "[llength [fileutil::grep $pattern $filename]] occurrences found"

If you care about performance, go with Glenn's solution.


text:
Q: How do I SSH into Ubuntu on VirtualBox? How do I SSH into Ubuntu from an outside network? It's running in VirtualBox and the network adapter has to remain NAT. I can't seem to figure out how to set it up. Are there any ways to directly SSH into the VirtualBox session?

A: When the VM networking is based on NAT, you need to use port forwarding to remotely access the VM (here named ubuntu).
VBoxManage modifyvm "ubuntu" --natpf1 "guestssh,tcp,,2222,,22"

Then you'll be able to access the VM by connecting to the host on port 2222, eg:
ssh -p 2222 user@host


text:
Q: simple jQuery function working in codepen but not on server: So I have this little function that takes the value or text input and gives it to an iframe's src attribute. It seems to work great on my codepen, but when I export it (with all of the files etc(codepen style) (jquery and everything is loaded properly) and put it on a server, it doesn't work. Does anyone have any ideas why this might be? or how I could be going about this in a better way? --
this is what shows in the url bar on submit with the live version in chrome if that means anything to you.
http://site.com/?url-input=http%3A%2F%2Fmy-site.com
A working codepen
HTML
<form class="visitor-input-form">
  <label for="url-input" >
    Type in your current URL and see what your website looks like to almost everyone else.
  </label>
  <input type="text" name="url-input"
         class="currentUrl"
         placeholder="http://nouveau.io" id="txtSRC" />

  <input type="submit" class="submit-button" value="View site" />
</form>

jQuery
$(".submit-button").click( function() {
  $(".i-frame").attr("src", $("#txtSRC").val());
});

Thanks for your time.
Update:
So to further test I'm using this. Page loads, tells me the dom is ready. So everything is loading in order. Then I input the url, it tells me the button was pushed, THEN - it tells me the dom is ready AGAIN. So, when I'm pressing enter, it is reloading the page. I do not want the page to reload. I just want the iframe to get switched out. So that is at least a little window to what might be the problem.
jQuery( document ).ready(function($) {

    alert("dom is ready");

    $(".submit-button").click( function() {

    alert("button was pushed");

        $(".i-frame").attr("src", $("#txtSRC").val());

    });
}); // end dom ready

A: Make sure you either execute your jQuery at the end of the document, after the elements already exist in the page, or in the head within a document ready call:
$(document).ready(function () {
    $(".submit-button").click(function () {
        $(".i-frame").attr("src", $("#txtSRC").val());
    });
});

Codepen does the former.

A: We found this:
Prevent reloading page after submiting form. ( no ajax )
<form onsubmit="return false">
Does the trick, but I have the feeling there is a better answer. I feel like on submit, it should run the scrip maybe instead of on click. I'm going to look into that. <form onsubmit="script"> etc... I'll wait a while before I mark this as answered in the hopes I get something more appropriate, but it is currently working as intended.

A: The page is reloading, try updating your jQuery to this:
jQuery( document ).ready(function($) {

    $(".submit-button").click( function(e) {
        e.preventDefault();

        $(".i-frame").attr("src", $("#txtSRC").val());

    });
});


text:
Q: Comparing byte arrays and vectors I'm trying to compare a Vec of bytes read to the very bytes that were read in to the Vec, but I'm having trouble getting the types of the two sides to line up. Here is my code (http://is.gd/goOnYf):
use std::io::{Cursor, Read};
// use std::borrow::Borrow;

fn main() {
    let byte_str = b"This is a byte string";
    let mut byte_vec = Vec::new();

    let mut reader = Cursor::new(byte_str.as_ref());
    reader.read_to_end(&mut byte_vec).unwrap();

    // assert_eq!(byte_str, byte_vec);
    // assert_eq!(byte_str, &byte_vec);
    // assert_eq!(byte_str, byte_vec.as_ref());
    // assert_eq!(byte_str, byte_vec.borrow());

    let bv: &[u8] = &byte_vec;
    assert_eq!(byte_str, bv);
}

You can see each of my failed attempts to compare them, before I had to force the Vec's type with a let binding and compare those.
The first one, assert_eq!(byte_str, byte_vec), failed with:
`<std macros>:5:8: 5:33 error: the trait `core::cmp::PartialEq<collections::vec::Vec<u8>>` is not implemented for the type `&[u8; 21]`

So it looks like I need to turn the Vec on the RHS in to a &[u8]. So I try a shared reference, and get the same error. Then I tried as_ref(), but that (and borrow()) need type annotations that I don't seem to be able to provide inline:
<anon>:13:35: 13:43 error: type annotations required: cannot resolve `collections::vec::Vec<u8> : core::convert::AsRef<_>` [E0283]

Is there a simpler way to do this that I'm missing?
Update: In writing the question, I did find an answer, but it's still kind of clunky:
assert_eq!(byte_str, AsRef::<[u8]>::as_ref(&byte_vec));

Is there a better way?
Update 2: The answer below only worked with some byte arrays I tried it with, but not all. It turns out that all of the handy traits like Debug, PartialEq, etc. are only implemented for arrays with <= 32 elements, so this works:
assert_eq!(b"01234567890123456789012345678901", &*byte_vec);

but this won't:
assert_eq!(b"012345678901234567890123456789012", &*byte_vec);

so you have to call as_ref() on it to make it a slice, for which those traits are implemented:
assert_eq!(b"012345678901234567890123456789012".as_ref(), &*byte_vec);

A: You can write the following:
assert_eq!(byte_str, &*byte_vec);

&* may look like a no-op, but in fact, Deref comes into play here and changes the meaning of the unary * operator. &*byte_vec is therefore equivalent to &*(byte_vec.deref()), or just to byte_vec.deref().


text:
Q: bin/magento setup:upgrade not running I am facing a long lasting issue on this command

*

*bin/magento setup:upgrade

I have made an extension hello world on magento2 stable version, which will simply print hello world on screen.
The thing is when I ran that....it gave me setup version, not specified error (though I have specified)...then I searched & ran this command -

bin/magento setup:upgrade

When I ran above command then I met with another error....pdo_mysql is not installed....
Then I solved that error with the following commands:
sudo apt-get install php5-mysql
sudo apt-get install pdo-mysql
then by doing php -m I could see the pdo_mysql in extensions list :)
But then as ran that command (bin/magento setup:upgrade) again....I got another error (very frustrated). Please check the attachment.
For solving that error I referred this one.... https://stackoverflow.com/questions/11990708/error-cant-connect-to-local-mysql-server-through-socket-var-run-mysqld-mysq
I typed this: sudo find / -type s
so I got the list in that one of the line is like this......
/opt/lampp/var/mysql/mysql.sock
now in that article, it says......"Once you find where the socket is being opened, add or edit the line to your /etc/my.cnf file with the path to the socket file".........so I opened /etc/my.cnf but....I found that the line is already there.....socket = /opt/lampp/var/mysql/mysql.sock
Then it says to run this : kill -9 4969 or pkill -9 mysqld but I did not run...I am afraid it can cause damage to xampp...
Then it says....."After you do this you might want to look for a pid file in /var/run/mysqld/ and delete it" but the thing is I can not find mysqld folder inside var/run/ so I am confused what to do now....
Many times I restarted xampp by first stopping apache like this:
sudo /etc/init.d/apache2 stop
But could not resolve the issue...
Can anyone please give the correct solution?
Magento 2 becomes a big problem running in Ubuntu for me :)

A: search mysqld.sock
you can search it using command : find -name "mysqld.sock"
then right click on it and copy link
then paste it under /var/run/mysqld/ and rename it to mysqld.sock
if there is no directory name "mysqld" in /var/run/ then create it

A: The answer given by Santosh Kumar & Denish Vachhani is absolutely right so I again say thank you to both of them :)
Now the thing is Santosh Kumar said search for mysqld.sock file using this command : find -name "mysqld.sock" I did it but no result found so it was unclear that how & from where can I have mysqld.sock file.
So finally what I did is :-
Before doing the following procedure please give your entire magento directory & sub directories & files the permission - 777 (in case of local or development phase)
Me gone to opt/lampp/var/mysql & looked for mysql.sock (remember that there wasn't available mysqld.sock file in my case) then I right clicked on it & selected "Make Link" so another file created from mysql.sock file so just renamed it to mysqld.sock & moved it (cut paste) to (outside opt folder)var/run/mysqld/ folder. If you don't find mysqld folder then simply create it. Remember that file should be having 777 permission.
Then go to your magento folder in terminal & hit this command :-
sudo php bin/magento setup:upgrade & you will get success :)
Then visit your module from url & it will work :)
One note :- If you don't have mysqld directory in (outside opt folder)var/run then if you are not interested in making manually then here are the commands:
sudo mkdir /var/run/mysqld (this will make directory)
sudo mv /opt/lampp/var/mysql/mysqld.sock /var/run/mysqld (this will move your created mysqld.sock file to var/run/mysqld)
this command from your magento folder in terminal - sudo php bin/magento setup:upgrade
Few more tips :-
1) If you want to see how many commands you can hit then do this :-
Go to your magento folder in terminal then,

cd bin
  ./magento
  You will have a list of commands :)

2) If you want to reindex then, go to your magento folder in terminal then hit these commands :-

cd bin
  ./magento indexer:reindex

3) If you want to compile then, go to your magento folder in terminal then hit these commands :-

cd bin
  ./magento setup:di:compile

Thank you & Good Luck

A: please clear page_cache, view_process and di folder.

please give sudo chmod -R 777 to root folder magento.

re-run compiler. using php -f bin/magento setup:di:compile

and also give chmod 777 '/var/run/mysqld/mysqld.sock
Note:- give full permission to magento root folder as well as mysqld.

A: In my case, the reason is I run the script "bin/magento setup:upgrade" under "root" account.
Need to switch to this account, and everything works fine:

A: give chmod -R 777 /var/pub/app
This is due to the permission issue


text:
Q: How to scroll to a specific div when the mouse is scrolled with jQuery? I have this code right now which scrolls to the correct place when a button is clicked:
$("#skills").click(function() {
    $('html, body').animate({scrollTop: $("#skills_page").offset().top}, 500);
    $(this).addClass("toggled_alt");
    $("#skills_id").css("background-color", "#646464");
    $("#contact_id, #home_id, #about_id").css("background-color", "transparent");
    $("#home, #contact, #about").removeClass("toggled");
    $("#home, #contact, #about").removeClass("toggled_alt");
});

What I want to do now is I want the page to scroll to the next div when the scroll wheel is moved down/up. I've been searching google for a while now and all that comes up is stuff about smooth scrolling which is not what I want. Any help would be great, thanks.

A: Checkout this answer and it's comments, and the MDN page on the wheel event.
Looks like you can bind to the event like this:
$(window).on('wheel', function(event){

But that might be overwhelming as it's each "click" of the mousewheel.
See this fiddle. Only tested in Chrome.


text:
Q: Size of Session Memory used by Entire website I want to know the size of memory used by session state variables including all the sessions present in AppDomain. I got the size of session variable that present in that session. But i want for entire AppDomain.
Thanks,
Pravin

A: with the help of Application Domain Resource Monitoring you can find the memory usage by application domain. follow this link
http://msdn.microsoft.com/en-us/library/dd997285.aspx

A: One thing you could try is to loop through the session objects and get the total as mentioned in this SO link.


text:
Q: not understanding why this code is not working im new to sessions but from what i see it complicated to apply <input> with them.  can you please look at this code and tell me why its not working. i had it working earlier then it died on me. the function of the program is to fill out a form and have it verified for legit information using regular expressions, i just need help with getting the sessions to save the data.
<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>regex</title>

</head>

<body>

<?php

$fname = $_REQUEST['fname'];

$fname = $_SESSION['fname'];

print<<<form

<form method="post"  action="">

  <input type ="text"
             name="fname"
             value="">

    <input type ="submit">

</form>

form;

$_SESSION['fname'] = $fname;

 print $_SESSION['fname'];

?>

</body>
</html>

A: You are reading $fname from $_REQUEST, then overwriting it with the value from $_SESSION, then putting it back to $_SESSION. So far, it should work as designed :) What are you trying to do? If you want to set the $_SESSION variable with the value received through $_REQUEST, leave out the second "$fname=" line.

A: Timothy,
Change your code so that it checks if the session/request is empty or not
Something like:
if(isset($_REQUEST['fname'])){
  $fname = $_REQUEST['fname'];
}else if(isset($_SESSION['fname'])){
  $fname = $_SESSION['fname'];
}

A: Try this:
if (!isset($_SESSION['fname'])) {
    $_SESSION['fname'] = '';  // default value
}
if (isset($_POST['fname'])) {
    $_SESSION['fname'] = $_POST['fname'];
}

print<<<form

…

form;

print $_SESSION['fname'];


text:
Q: PyQt5 QPixmap is Null with valid file I am trying to load an icon into a tool button. I need to first create a pixmap so I can add it to the QIcon, which then is added to the tool button. However, the pixmap is always null and nothing gets displayed on the tool button except for the default text of "..."
Take a look at this
file = ":/icons/refresh.jpg"
if QtCore.QFile.exists(file):
    print("File exists")
else:
    print("Does not exist")
pixmap = QtGui.QPixmap(file)
print(pixmap.isNull())

>>>File exists
>>>True

Why is the pixmap not being created when a valid file is given?
I am running Python 3.4 in a virtualenv with PyQt5 v5.5 on Windows 10

A: ekhumoro pushed me in the right direction with QImageReader, where I checked the file formats with supportedImageFormats(). This led me to this post https://github.com/ContinuumIO/anaconda-issues/issues/131
I discovered that since I am using a virtualenvironment, the Python interpreter was in a location that was unknown to the qt.conf file, which had the wrong prefix for the interpreter path. By changing my prefix to my PyQt5 folder relative to the venv folder, I was able to get Qt to load the .jpg image format .dll which now displays the image.


text:
Q: PHP: Find spreadsheet (e.g. Excel / LibreOffice Calc) column number from column title I need to write a PHP function to get a spreadsheet column number from its column name (e.g. 'A' = 1, 'B' = 2, 'Z' = 26, 'AA' = 27, 'BE' = 57, 'CW' = 101, 'ZZ' = 702, 'CDA' = 2133, ...)
function get_col_number_from_name($col_name)
{
    // do something to determine $col_number from $col_name...

    return $col_number;
}

e.g. get_col_number_from_name('BE') must return 57
Unfortunately I cannot manage to write a suitable algorithm.
Could you please help me?
Thank you in advance.

A: Sample code below,
function get_col_number_from_name($col_name)
{
    $l = strlen($col_name);
    $col_number = 0;

    for ($i = 0; $i < $l; $i++) {
        $col_number = $col_number * 26 + ord($col_name[$i]) - 0x40;
    }

    return $col_number;
}


text:
Q: How do I find the averge value of the function g(x) on the interval [1, + infinity]? I know how to find the average value of functions on an interval, but I am having trouble finding the average value of this function with the interval going to positive infinity. I tried doing what the hint says, but I'm not sure if I am on the right track. Can anyone suggest anything? Thank You!

A: Given the amount of your homework you have posted in the past four hours...
Hint: $u = \frac{\pi}{x}$.


text:
Q: koa2 template string can not display properly I am installing coat 2.0 and node 8.0, but when I test following code, it shows
Hello World ${date}, not Hello World 6/7/2017.
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
const date = new Date();

ctx.body = 'Hello World ${date}';

});
app.listen(3000);

A: You need to use backticks ` in a template string:
const Koa = require('koa'); const app = new Koa();

app.use(ctx => {
    const date = new Date();
    ctx.body = `Hello World ${date}`;
});

app.listen(3000);


text:
Q: $R$ is Noetherian semilocal. $J:=\operatorname{Jac}(R)$. If $R/\operatorname{nil}(R)$ is $J$-adically complete, then $R$ is $J$-adically complete Let $R$ be a Noetherian ring with finitely many maximal ideals. Let $I$ be its nilradical, i.e. the intersection of all prime ideals, and $J$ be the Jacobson radical i.e. the intersection, hence product (since there are finitely many), of maximal ideals. If $R/I$ is $J$-adically complete ( with the topology  induced by the nbd base $\{(J^n+I)/I\}_{n\ge 0}$ ); then how to show that $R$ is $J$-adically complete ?
Since $R/I$ is Noetherian and $J$-adic complete, so for any Noetherian $R/I$-mod $M$, $M$ is $J$-adic complete , so in particular $\cap_{n\ge 1} J^n M=(0)$.
I don't know how to proceed further. Please help.


text:
Q: C++ vector issues My application keeps crashing on me for whatever reason. I am new to vectors so there is more than likely something silly on my part.
#include <iostream>
#include <vector>

using namespace std;

class Projectile
{
private:
    SDL_Surface *projectile;
    void load();

public:
    int count;

    vector< int > c;
    vector< vector< int > > p;

    int positionX;
    int positionY;

    Projectile();
    void newProjectile( int, int );
    void drawCurrentState( SDL_Surface* );
};

...
...

void Projectile::newProjectile( int x, int y )
{
    positionX = x;
    positionY = y;

    c.push_back( 10 );
    c.push_back( 10 );

    //p.push_back( c ); //trying to start off simple before i do multidimensional.
}

void Projectile::drawCurrentState( SDL_Surface* destination )
{
    SDL_Rect offset;
    offset.x = c[0]; //will eventually me the multidimensional p vector
    offset.y = c[1]; //

    SDL_BlitSurface( projectile, NULL, destination, &offset );
}

what exactly am I doing wrong here? I push back two values ( will be the x and y ints after done testing ) however it seems to crash when it gets to the offset.x = c[0]; part of the script.
I thought for certain both c[0] and c[1] should be equal to 10. Any suggestions?

A: You're right, both [0] and [1] should be 10.
Just make sure you really call newProjectile() first, and make sure there are no other problems such as invalid destination pointer and so on.

A: The code seems to be okay, but the order of the calls is important. Make sure that you call newProjectile() before you call drawCurrentState(), for example like this:
Projectile * projectile = new Projectile();
projectile->newProjectile(1,1);
projectile->drawCurrentState( ... );

A: Maybe vector c is empty at line where c[0] is read. Check the result of c.size().


text:
Q: React SPA - GTM Analytics React-Helmet Previous Page Title I am using Google Tag Manager to push pageview events to the datalayer for Analytics tracking. This is happening in componentDidMount() (and sometimes componentWillReceiveProps() if I am listening for query string parameter changes with the location prop using withRouter).
I am using react-helmet to dynamically update my title and other tags as components change.
I have noticed an issue that I am getting the improper page title in Analytics. It's frequently showing the page title of the previous page, instead of the one I am currently on. It appears that react-helmet is not updating the  tag until after componentDidMount().
Page View Event Function Example
My analytics tag in GTM is called every time this event is pushed to the data layer

const firePageViewEvent = () => {
      console.log("Pageview event fired (from tracking script)");

      if (window && window.dataLayer) {
          console.log("window and dataLayer exist, pushing pageview event.");
          let dataLayer = window.dataLayer || [];
          dataLayer.push({
              'event': 'reactPageViewEvent'
          });
      } else {
          console.log("window or dataLater does not exist, cannot push pageview event.");
      }
};

A: I can confirm that wrapping the function in a setTimeOut() function with a 0ms delay does indeed work to ensure that the event is only pushed after react-helmet has a chance to do its thing.
This allows me to consistently get the current page title in Analytics.
See github issue comment
Updated Function

const firePageViewEvent = () => {
    setTimeout(() => {
        console.log("Pageview event fired (from tracking script)");

        if (window && window.dataLayer) {
            console.log("window and dataLayer exist, pushing pageview event.");
            let dataLayer = window.dataLayer || [];
            dataLayer.push({
                'event': 'reactPageViewEvent'
            });
        } else {
            console.log("window or dataLater does not exist, cannot push pageview event.");
        }
    }, 0);
};


text:
Q: React | Add className to a dynamically created component I am trying to add a className property to a newly created component like this:
const component = <Icons.RightArrowIcon /> // I want to add a className to this component

// Then...

// ...

return (
    <>{component}</>
)

I wrote the following code:
type IconButtonProps = {
  icon: 'RightArrowIcon' | 'WordIcon';
  className?: string;
};
// eslint-disable-next-line react/display-name
const IconButton = React.forwardRef<any, IconButtonProps>((props, ref) => {
  const getIcon = () => {
    let icon: React.ReactNode | null = null

    if (props.icon === 'RightArrowIcon') {
      icon = <Icons.RightArrowIcon />
    } else if (props.icon === 'WordIcon') {
      icon = <Icons.WordIcon />
    }

    // This is what I thought it would be
    if (icon !== null) { icon.props.className = styles.icon_button__icon }

    return icon
  }

  return (
    <div
      ref={ref}
      className={`${props.className} ${styles.icon_button__wrapper}`}
    >
      <button className={styles.icon_button}>
        {getIcon()}
      </button>
    </div>
  )
})

export default IconButton

But I got this error:

TypeError: Cannot add property className, object is not extensible

A: Not sure if it needs to be that complicated. Why not just render the icon conditionally?
  return (
    <div
      ref={ref}
      className={`${props.className} ${styles.icon_button__wrapper}`}
    >
      <button className={styles.icon_button}>
        {
         props.icon === 'RightArrowIcon'?//or any condition here
         (
         <Icons.RightArrowIcon className={style.anyClassHere}/>
         ):
        (
         <Icons.WordIcon className={style.anyClassHere}/>
        )
        }
      </button>

    </div>
  )


text:
Q: PHP Curl: Set -J and -O options to download file by remote file name I'd like to download a file from a php script using curl.
I want to write the file with the same name as the remote file (which is not included in the url).
I can achieve this in the bash by using the options -O and -J.
Example:
curl -XGET -O -J http://AAA.com/asdasd/Default.aspx?pid=somethingsomethignsomething
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                               Dload  Upload   Total   Spent    Left  Speed
100 2388k  100 2388k    0     0   304k      0  0:00:07  0:00:07 --:--:--  248k

curl: Saved to filename 'file_20151206.txt'

As you can see, the name of the file is file_20151206.txt, and it's the remote name of the file, which is NOT contained in the url.
How can I do this in php?, I couldn't find any help in the documentation.


text:
Q: Get dates between 2 dates with equal intervals I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.
Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017

Please help!!

A: One method would be to use a Calendar table. Then return the results from there using the modulus to get the 7th rows:
WITH Dates AS(
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY [date]) AS RN
    FROM DateTable
    WHERE [Date] BETWEEN '20170401' AND '20170430')
SELECT *
FROM Dates
WHERE (RN - 1) % 7 = 0;

I've used this solution, as from your post you imply that you might supply any date range, and that the 1st day may not necessarily be a Monday (or other specific day).

A: Try this
DECLARE @STRT DATETIME='04/01/2017',@END DATETIME ='04/30/2017'
;WITH CTE
AS
(
    SELECT
        MyDate = CAST(@STRT AS DATETIME)

    UNION ALL

    SELECT
        MyDate = CAST(MyDate AS DATETIME)+7
        FROM CTE
            WHERE CAST(MyDate AS DATETIME)+7 < CAST(@END AS DATETIME)
)
SELECT
    *
    FROM CTE

result

A: DECLARE @StartDate  DATETIME,
    @EndDate        DATETIME

SELECT @StartDate = '2017-04-01',
    @EndDate = '2017-04-30'

SELECT DATEADD(DAY, number*7, @StartDate)
FROM master.dbo.spt_values
WHERE type='P'
    AND  @EndDate >= DATEADD(DAY, number*7, @StartDate)

A: Declare @StartDate DATE=CONVERT(DATE,'01/04/2017',104),@EndDate DATE=CONVERT(DATE,'01/12/2017',104)
Declare @String NVARCHAR(MAX)=''

WHILE (@StartDate<=@EndDate AND DATEDIFF(wk,@StartDate,@EndDate)>=0)
BEGIN

SET @String=@String+CONVERT(NVARCHAR(100),@StartDate)+CHAR(10)+CHAR(13)

SET @StartDate=DATEADD(d,7,@StartDate)

END
PRINT  @String
GO


text:
Q: When module Enabled in Content left & right panel so I want to hide javascript code in OpenCart I have add small javascript code in featured.tpl module OpenCart. So, when, featured module Enabled in Content top & bottom part. so, I want to show(run) it javascript code. but, when featured module Enabled in Content left & right panel. so, I want to hide(not run) it javascript code.
Please guide me :)

A: I have found solution.
in .tpl file
<?php if ($module['position'] == 'content_bottom' || $module['position'] == 'content_top') { ?>
//add your code Here
<?php } ?>

add in .php file
$this->data['module'] = $setting;


text:
Q: Subclass NSDate, no changing behaviour, just add a tag? I need to sort I need to subclass NSDate to add a tag, I don't need to change its behaviour, do I still need to implement my own:

*

*(NSTimeInterval)timeIntervalSinceReferenceDate

*(id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds;
as stated in apple's documentation? If so, how do I do it?
currently I just created a class extends NSDate with a tag attribute, but how do I initialise it?
Thanks!

A: NSDate is a class cluster, not a simple class. It is not wise to subclass a class cluster unless you know exactly what you are doing; see How do I subclass NSDate?
I would recommend that you create your own class containing an NSDate and a tag, and extend as needed:
@interface MyClass : NSObject {
  NSDate *_date;
  NSUInteger _tag;
}
@end

Add the appropriate properties, etc for easy dot-notation access.


text:
Q: Process substitution in BSD hangs (sometimes) While porting a Linux bash script to BSD, I've stumbled on an interesting question.
How can this phenomenon be explained and what workaround would you suggest in this case:
it is a minimal reproducible example, that's why it makes no sense per se)
# this works in Linux, but hangs in BSD:
$(a=<(echo 1))

It is so called process substitution (inside a command substitution) here, and it works like this:

*

*Name of a file descriptor (linux), or temporary FIFO file (BSD) is stored in the $a variable;

*after that the subshell of the command substitution $() is closed.

Ok. That is how it should work (and it works in Linux), but it hangs in FreeBSD, waiting for something to happen with the FIFO created for the command substitution (/tmp//sh-np.muuX1P).
Question:
How you can explain this, and what workaround would you propose?


text:
Q: importing files from android source code I'm looking into duplicating the Always-On VPN (introduced in Android 4.2) functionality in my VPN android app. I could of course direct the users to the settings page and have them click the checkbox, but I'd really like to just bake this into my application. I went through the android source code for this dialog (since there is no corresponding setting exposed in the SDK) and it seems simple enough:
 public void onClick(DialogInterface dialog, int which) {
      final int newIndex = listView.getCheckedItemPosition();
      if (mCurrentIndex == newIndex) return;
      if (newIndex == 0) {
            keyStore.delete(Credentials.LOCKDOWN_VPN);

      } else {
            final VpnProfile profile = mProfiles.get(newIndex - 1);
            if (!profile.isValidLockdownProfile()) {
                Toast.makeText(context, R.string.vpn_lockdown_config_error,
                        Toast.LENGTH_LONG).show();
                return;
             }
            keyStore.put(Credentials.LOCKDOWN_VPN, profile.key.getBytes());
      }

      // kick profiles since we changed them
      ConnectivityManager.from(getActivity()).updateLockdownVpn();
   }

Unfortunately the keystore here is the android.security.KeyStore file instead of the usual java.security.KeyStore. As such, my question is, whats the best way to implement this block of code in my app? Is it even possible for me to change this setting in my app without root access? Is there a way for me to include the android.security.KeyStore file? Any thoughts would be very helpful!!


text:
Q: How to run a function that gets data from inside eventReactive and plot in table? I'm very new to shiny and am having some trouble and have been searching all day, so hopefully someone can help me.  Once an action button (actionButton, on UI) is selected by a user, I would like the server script to call a function (evenReactive in server) I wrote (myfunction, see below) that uses the input items from the UI and gets the right parameters I need to run myfunction and produce a n X2 data matrix that will be plotted as a table (renderTable in server, below). The data is a n X 2 matrix.
I have some sample code below. It's not the entre code, so you will not see the UI with the inputs I am putting in my function, or the server parts associated. But, it is the part I am trying to fix. I hope that's ok. I don't need the renderText, but when I take it out I get an error.  Sorry for the formatting. Copy and pasting changed it a bit.
library(shiny)

ui <- shinyUI(fluidPage
     (column(4,actionButton("gobutton", "Run"),verbatimTextOutput("ntext1")),
      column(4, DT::dataTableOutput("table",width = "75%"))))

library(shiny)

shinyServer(function(input, output, session)

  ntext1 <- eventReactive(input$gobutton, {
            if (input$gobutton==1){
              data=myfunction(input$checkbox,input$dateRange)}
   })

  output$ntext1 <- renderText({ntext1()})

  output$table <- DT::renderDataTable(DT::datatable({
    data
  })
))

myfunction <-function(All,date1,date2,source_cd,tran_cd,airline_list,mag_level) {
 print(All); print(date1); print(date2); print(source_cd);print(tran_cd);print(airline_list);print(mag_level)

    setwd("C:/Users/TRomano/Documents/Projects/TrendAnalysis/Data")
    data = read.csv("Airlines.csv",header = TRUE)
    return(data)
  }

A: For this type of problem I like to make use of reactiveValues()that are designed to store data in a reactive way.
Here is a simple app (single app, not split into server & ui) that demonstrates what I think you are trying to do
library(shiny)
library(DT)

ui <- shinyUI(
    fluidPage(
        column(width = 4,
                     actionButton("gobutton", "Run")
        column(width = 4,
                     DT::dataTableOutput("table",
                                         width = "75%"))))

server <- shinyServer(function(input, output, session){

    rv <- reactiveValues()
    rv$data <- NULL

    observe({    ## will 'observe' the button press

        if(input$gobutton){
            print("here")  ## for debugging
            rv$data <- myfunction()   ## store the data in the reactive value
            rv$data
            }
        })

    output$table <- DT::renderDataTable({
        ## The data has been stored in our rv, so can just return it here
        rv$data
    })
})

myfunction <- function(){
    data <- data.frame(id = c(1,2,3),
                       val = letters[1:3])
    return(data)
}

shinyApp(ui, server)

A: library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(title = "Company Name"),
dashboardSidebar(sidebarMenu(
menuItem("Results Table", tabName = "ResultsTable", icon = icon
("ResultsTable")),
dashboardBody(
tabItems(

  tabItem(tabName tabItem(tabName = "ResultsTable",
          fluidPage(
            headerPanel(
            fluidRow(
              column(4,
                     selectInput("sour",
                                 "Source Type:",
                                 c("All",
                                   unique(as.character(data_source_cd)))), offset=2
              ),
              column(4,
                     selectInput("tran",
                                 "Transaction Type:",
                                 c("All",
                                   unique(as.character(tran_cd)))))),
            # Create a new row for the table.
            fluidRow(column(8, DT::dataTableOutput("table",width = "75%"),offset = 2))))))

library(shiny)
shinyServer(function(input, output, session) {
       ntext1 <- eventReactive(input$gobutton, {
if (input$dateRange[2]<input$dateRange[1]){print("You selected the date range option;however, the end date entered occurs before the starting date")}else{
  output$ntext1 <- renderText({print("Analysis complete...")});
  observe({
    if(input$gobutton){
      rv$data <- myfunction()          }
  })
  output$table <- DT::renderDataTable(DT::datatable({
    data <- rv$data
    if (input$sour != "All") {
      data <- data[data[,5] == input$sour,]
    }else{data}
    if (input$tran != "All") {
      data <-data[data[,6] == input$tran,]
    }else{data}
  }))
}})

Once an action button is selected on the main page of my dashboard(not shown), myfunction runs analysis with the inputs from the main dashboard page. On another tab, a table will show once the analysis is complete. There are drop down menus (input$tran, input$sour) that will reduce what is in the table depending on what the user selects. If there are any errors in the input, a warning of text comes up on the main dashboard page and the tab with the table will not be created until the correct inputs are selected.
The observe function allowed me to run my function and the output data of the function set to a variable I could later use to create the table (shown).
THis is my first time posting. Any questions feel free to ask.


text:
Q: How Can I Add A sleep or delay to this code? I use this to add friends on facebook. How can i slow this code down so that it will only run once per set time period?
var inputs = document.getElementsByClassName('_3-8_ img sp_zYKR9BP4QJasx_27b6db');
for(var i=0; i<inputs.length;i++) {
    sleep(2000);
    inputs[i].click();
}

A: This may not work because the class names look like they are dynamically generated.
window.setInterval(function(){
    var inputs = document.getElementsByClassName('3-8 img sp_zYKR9BP4QJa sx_27b6db');
    for(var i=0; i<inputs.length;i++) { inputs[i].click(); }
}, 15000 );


text:
Q: Cannot return to shell session after script I cannot get a script to return to bash.
The script is kicked off via the following Docker directives:
ENTRYPOINT ["/bin/bash", "-c"]
CMD ["set -e && /config/startup/init.sh"]

The init script looks like this:
#!/bin/bash

if [ -d /etc/postfix/init.d ]; then
    for f in /etc/postfix/init.d/*.sh; do
        [ -f "$f" ] && . "$f"
    done
fi

echo "[x] Starting supervisord ..."
/usr/bin/supervisord -c /etc/supervisord.conf

bash

And this is the command I use to kick off the image into a container:
docker run -it --env-file ENV_LOCAL mailrelay

The init script runs as expected (and I see output from the scripts within the /etc/postfix/init.d/ directory and supervisord kicks off Postfix.
The problem is getting the script to return to the parent process (bash) instead of needing to start a new one. After it hits the supervisord the session sits there, requiring a Ctrl+C to get it to get back into a bash prompt.
If I leave off the call to bash at the end of the init.sh script, Ctrl+D exits the script AND the container, returning me to the host OS (osx). If I replace the bash call with exit, it returns to the host OS as well.
Is supervisord behaving the way it's supposed to, by running in the foreground this way? I'd like to be able to easily get back into the container shell session to check to see if things are running. Am I left with needing to Ctrl+D (into the secondary bash session) in order to do this?
UPDATE
Marc B

take out the bash line, so you don't start a new shell. and if
  supervisord doesn't go into the background automatically, you could
  try running it with & to force it into the background, or maybe
  there's an extra cli option to force it to go into daemon mode

I've tried removing the last call to bash, but as I've mentioned it just sits there still, and Ctrl+D takes me to the host OS (exits the container).
I just tried /usr/bin/supervisord -c /etc/supervisord.conf & (and left off the call to bash at the end) and it just immediately returns to host OS, exiting the container. I assume because the container had nothing left to "do", and so stopped.

A: #!/bin/bash

if [ -d /etc/postfix/init.d ]; then
    for f in /etc/postfix/init.d/*.sh; do
        [ -f "$f" ] && . "$f"
    done
fi

echo "[x] Starting supervisord ..."
/usr/bin/supervisord -c /etc/supervisord.conf
one
bash # You are spawning a new bash shell here. Remove this statement

At the end your're stuck in a child bash shell :(
Now if you're not returning to the parent shell, the last command that you have run is the culprit.
/usr/bin/supervisord -c /etc/supervisord.conf

You can either force the command to run in the background by
/usr/bin/supervisord -c /etc/supervisord.conf & #the & tells to run in background

A workaround for keeping the container open is mentioned here


text:
Q: Trying to understand recursive definitions in discrete math
Consider the recursive definition of the natural numbers:

*

*Basis: $0 \in \mathbb{N}$

*Recursive step: if $n \in \mathbb{N}$  , then $s(n) \in \mathbb{N} $
Give recursive definitions of:

*

*$T_0$ the set of natural numbers that are divisible by 3

*$T_1$ the set of natural numbers with a remainder of 1 when divided by 3

I'm having trouble understanding the adaptation of the basis and recursion step for natural numbers. Should I approach it something like:

Basis: if $n = 0, {0\over 3}$ is divisible by 3
Recursive: if $n \in \mathbb{N} $, then $s(n+3)$ is divisible by 3 ( where $s$ is the successor function )

I will of course need some type of closure. I would appreciate any help trying to grasp the concept

A: For the basis step, you don't want to state that $0/3$ is divisible by $3$, you just state that $0$ is divisible by $3$.
For the recursive step: you assume that $n \in \mathbb{N}$ is divisible by 3, then say that this implies that some other number is divisible by 3. To get what that other number is, think about the numbers divisible by $3$, then think about the relationship between them in terms of the successor operation.

A: Recursive definition of the set $T_0$ of natural numbers divisible by $3$:

*

*Basis: $0\in T_0$

*Recursive step: if $n\in T_0$, $s(s(s(n)))\in T_0$.

Try to figure out how to modify it to get the set $T_1$ of natural numbers with a remainder of $1$ when divided by $3$.


text:
Q: Derivatives of radial functions can be bounded by derivatives in terms of radial distance? Suppose $f$ is a radial function, i.e., $f(x)=f(|x|)$,
and $f \in C^\infty(\bar{B})$, where $\bar{B}$ is the closure of the unit ball in $\mathbb{R}^n$.
Prove or disprove the following.
Given any positive integer $k$, $$\sup_{|\alpha|=k,x\in B} |D^\alpha f(x)| \leq \sup_{r < 1} \lvert f^{(k)}(r) \rvert,$$
where $\alpha$ is a multi-index and $D^\alpha f$ is the corresponding derivative of $f$.
By $f^{(k)}(r)$, we mean the $k^{th}$ derivative of $f$ as a function of $r=|x|.$
I try some functions, taking second order derivatives, and the inequality holds for all of them.
The case where $k=1$ is easy to prove but I can't prove for a general $k$.
Instead of a general smooth $f$,  can we prove the assertion for polynomials(or an uniformly and absolutely converging power series) with only even powers, namely,
$$f(r) = \sum_{j=0}^m c_j r^{2j} \quad(m\text{ can be}+\infty)\quad?$$
PS: I asked this question on Math.SE but no one answered so it is posted here.
This is a quite simple/straightforwad question (that a Freshman in math can fully understand) but it is surprising that till now, no one(me included) could answer it or at least give some idea.

A: To avoid confusion, I shall denote $f=f(r)$ and $F(x)=f(|x|)$ the corresponding radial function.
Because of Van der Corput-Schaake Inequality, it is enough to prove the following more general inequality: for every point $x\ne0$, integer $k\ge1$ and unit vector $e$,
$$|D^kF_xe^{\otimes k}|\le\sup_{0\le s\le r}|f^{(k)}(s)|\quad ?$$
This is obvious for $k=1$. Let me first prove that it is true for $k=2,3$. Then I'll give a general strategy for a proof. In the following, I denote
$$\nu:=\frac{x\cdot e}r\in[-1,1].$$
For $k=2$, one has
$$D^2F_xe^{\otimes 2}=(1-\nu^2)\frac1rf'+\nu^2f''.$$
Because $F$ is smooth, we know that the derivatives of $f$ of odd order vanish at $0$. Using $f'(0)=0$, we obtain
$$D^2F_xe^{\otimes 2}=(1-\nu^2)\frac1r\int_0^rf''(s)ds+\nu^2f''=\langle\mu_2,f''\rangle.$$
There remains to check that the measure $\mu_2$ has total mass $1$ (i.e. is a probability). This is obvious.
If $k=3$, we have
$$D^3F_xe^{\otimes 3}=3(\nu-\nu^3)\left(\frac1rf''-\frac1{r^2}f'\right)+\nu^3f'''.$$
Using again $f'(0)=0$, we obtain
$$D^3F_xe^{\otimes 3}=\langle\mu_3,f'''\rangle$$
where
$$\mu_3:=\nu^3\delta_{s=r}+3(\nu-\nu^3)\frac{s}{r^2}\chi_{[0,r]}(s).$$
Again, one checks that
$$|\mu_3|=|\nu^3+\frac32(\nu-\nu^3)|\le1.$$
The general strategy is to prove that if $r=|x|$, then
$$D^kF_xe^{\otimes k}=\langle\mu_k,f^{(k)}\rangle$$
for some measure $\mu_k$ over $[0,r]$. Mind that the coefficients of $\mu_k$ involve only $\nu$ and $r$. The measure $\mu_k$ can be calculated from the Faa di Bruno Formula (I suspect that $\mu_k$ has a constant sign). To conclude, one has to check that its total mass is less than $1$. This total mass involves only $\nu$ ; it is likely to be the absolute value of a polynomial $P_k(\nu)$.
More precisely, $\mu_k$ is the sum of the Dirac mass $\nu^k\delta_{x=r}$ and a continuous density over $s\in(0,r)$ :
$$\frac1rN_k(\nu,t),\qquad t:=\frac sr.$$
The density is determined by induction with the following rules
$$\partial_t(N_{k+1}-\nu tN_k) = -(1-\nu^2)\partial_\nu N_k, $$
$$N_{k+1}(\nu,1) = \nu N_k(\nu,1)+k\nu^{k-1}(1-\nu^2),$$
and we have $N_k(\nu,0)$ if $k$ is odd. The second line gives explicitly
$$N_k(\nu,1)=\frac{k(k-1}2\nu^{k-2}(1-\nu^2).$$ The first few $N_k$'s are
$$N_1\equiv0,\quad N_2=1-\nu^2,\quad N_3=3\nu(1-\nu^2)t,$$
$$N_4=\frac32(1-\nu^2)(5\nu^2-1)(t^2-1)+6\nu^2(1-\nu^2),$$
$$N_5=\frac32\nu(1-\nu^2)(5\nu^2-1)t(t^2-1)+6\nu^3(1-\nu^2)(t-1)-2(3\nu-5\nu^3)(1-\nu^2)(t^3-3t+2)-12\nu(1-\nu^2)(1-2\nu^2)(t-1)+10\nu^3(1-\nu^2).$$
One verifies easily that $\mu_4$ is a probability (Question : is $\mu_{2\ell}$ always a probability ?).
I checked that for every value of the angle $\nu$,
$$0\le\langle\mu_5,{\bf1}\rangle\le1.$$
However, I gave up about the sign of $N_5$, and therefore I cannot claim that the total mass $|\mu_5|\le1$.

A: Here is an argument to show that $\nabla^k F_x\cdot e^{\otimes^k}=f^{(k)}(r)$ if $x=re$. This shows that the inequality Denis is seeking to prove is sharp, if true; I can verify this inequality in the particular case $f(r)=e^{-r^2}$. Here is the argument:
Let $g$ be a function such that $g(r^2)=f(r)$, so that in Denis' notation, $F(x)=g(|x|^2)$. The derivatives of $f$ and the expressions $\nabla^k F_x\cdot e^{\otimes^k}$ can be expressed in terms of the derivatives of $g$ as follows:
For every $k$, there exist polynomials $P_{i,k}(t)$ such that
$$
f^{(k)}(r)=\sum_{i=1}^k P_{i,k}(r)g^{(i)}(r^2)
$$
and
$$
\nabla^k F_x\cdot e^{\otimes^k}=\sum_{i=1}^k P_{i,k}(x\cdot e)g^{(i)}(|x|^2).
$$
Taking $x=re$, we see that the RHS of both equations are equal.
To prove these equations, use induction and the following formulas, valid for any $h, P$:
$$
\nabla(h(|x|^2))\cdot e = 2(x\cdot e)h'(|x|^2)\qquad \nabla(P(x\cdot e))\cdot e = P'(x\cdot e)
$$
and
$$
\frac{d}{dr}h(r^2)=2r h'(r^2)\qquad \frac{d}{dr}P(r)=P'(r).
$$
In addition, these polynomials satisfy the recurrence $P_{i,k+1}(t)=P_{i,k}'(t)+2tP_{i-1,k}(t)$, so that, for $k$ even, the $P_{i,k}$ are even, and for $k$ odd, the $P_{i,k}$ are odd. Thus if $x=-re$, we have equality up to $\pm1$.
If $g(t)=e^{-t}$ (i.e. $f(r)=e^{-r^2}$), then
$$
\nabla^k F_x\cdot e^{\otimes^k}=H_k(x\cdot e)g(r^2),
$$
where $H_n(t)$ is the $n$th Hermite polynomial (which satisfy a similar recurrence to the $P_{i,k}$). Since $H_k(t)g(r^2)$ is decreasing in $r$, the sup of $\nabla^k F_x\cdot e^{\otimes^k}$ over $|x|\leq r$ (i.e. $|t|\leq r$) is attained when $x=re$.

A: There are many estimates of Sobolev type of the form
$$
||D^{\alpha}f||_1 \le ||\Delta f||_2
$$
for different pairs of norms. For your case the r.h.s. will be one-dimensional in r
$||(D^2-\frac{n-1}{r}-\frac{1}{r^2})f||_2$. Now the question is reduced to one-dimensional estimates of this norm, say from the embedding theorem bounding derivatives uniformly.
Of course it is just a plan to attack the problem, no pretence for being an answer complete, bounty cake and so on.
E.g. in case of the Lebesgue  norms with powers of Bessel operators instead standard derivatives-we have Kipriyanov spaces, like Sobolev ones. I proved some years ago that these norms are equivalent to Sobolev with power weights. For such spaces there are embedding in $C$---spaces. So estimates with Bessel powers lead to uniform estimates.


text:
Q: HPA is unable to fetch custom metrics from prometheus adapter I have configured Prometheus-adapter to fetch custom metrics from Prometheus.
When I execute the command:
kubectl get --raw /apis/custom.metrics.k8s.io/v1beta1
Following is the result.
 {
      "name": "namespaces/envoy_http_ingress_http_downstream_cx_http1",
      "singularName": "",
      "namespaced": false,
      "kind": "MetricValueList",
      "verbs": [
        "get"
      ]
    },
    {
      "name": "namespaces/envoy_cluster_xds_cluster_upstream_cx_rx_bytes",
      "singularName": "",
      "namespaced": false,
      "kind": "MetricValueList",
      "verbs": [
        "get"
      ]
    },
    {
      "name": "jobs.batch/statsd_exporter_lines",
      "singularName": "",
      "namespaced": true,
      "kind": "MetricValueList",
      "verbs": [
        "get"
      ]
    },
    {
      "name": "pods/fs_writes_merged",
      "singularName": "",
      "namespaced": true,
      "kind": "MetricValueList",
      "verbs": [
        "get"
      ]
    },

My HPA configuration is as follows:
apiVersion: autoscaling/v2beta1
kind: HorizontalPodAutoscaler
metadata:
  name: scale
  namespace: default
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: billing-app
  minReplicas: 1
  maxReplicas: 10
  # targetCPUUtilizationPercentage: 50
  metrics:
    - type: External
      external:
        metricName: fs_writes_merged
        targetValue: 100

Hpa results in unknown. Not sure why it is not able to fetch metrics.
Hpa must be able to read the custom metrics.

A: Answer
Since your HPA configuration declares the metric as type: External, the HPA tries to fetch it from the External Metrics API (/apis/custom.metrics.k8s.io), but the Prometheus Adapter exposes it on the Custom metrics API (/apis/custom.metrics.k8s.io).
Since your metric comes from the Pods of the Deployment that you're trying to autoscale, you should use the Pods metric type. So, change your HPA configuration to:
  # ...
  metrics:
    - type: Pods
      pods:
        metricName: fs_writes_merged
        targetValue: 100

Background
You can see all the available HPA metric types and their usages here:
kubectl explain --api-version=autoscaling/v2beta1 hpa.spec.metrics

There are four metric types, and they map to the various metric APIs as follows:

*

*Resource: Resource Metrics API (/apis/metrics.k8s.io/v1beta1)

*Pods: Custom Metrics API (/apis/custom.metrics.k8s.io/v1beta1)

*Object: Custom Metrics API (/apis/custom.metrics.k8s.io/v1beta1)

*External: External Metrics API (/apis/external.metrics.k8s.io/v1beta1)

See HPA docs, and design documents for Resource Metrics API, Custom Metrics API, and External Metrics API.


text:
Q: Advanced USE >= AND <= in SQL Don't know how to call the question title.
I need to shows result base on WHERE DOCDATE >= (From my DateADD function ) and DOCDATE <= (From my DateADD function )
My Dateadd fuction pulling a list  of last 52 week's date from today's date.
Error message is sub-query returned more than 1 Value
`DECLARE @NOW Date
SET @NOW =GetDate()
SELECT        TOP (1) ItemCode, Dscription, Price, DocDate
FROM            dbo.PCH1
WHERE       ItemCode = '3255' AND (DocDate In  ( SELECT DATEADD(Week,  - WEEKS.n, @NOW) as Date
FROM            (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12), (13), (14), (15), (16), (17), (18), (19), (20), (21), (22), (23), (24), (25), (26), (27), (28), (29), (30), (31), (32), (33), (34), (35), (36), (37), (38), (39), (40), (41), (42),
                         (43), (44), (45), (46), (47), (48), (49), (50), (51)) WEEKS(n)))
`

Hard coded version is bit messy and i don't want to do union all 20 time
    SELECT        TOP (4) ItemCode, Price, DocDate
FROM            dbo.PCH1
WHERE        (ItemCode = N'3255') AND (DocDate <= DATEADD(Week, - 48, GETDATE())) AND (DocDate >= DATEADD(Week, - 52, GETDATE()))


text:
Q: Facebook graph api is slow i am doing this :
<?php echo json_decode(file_get_contents("http://graph.facebook.com/?id=8083675473"))->likes; ?>

Sometimes, it takes .2 seconds, sometimes it takes 30 seconds. The problem is the load time of this page: http://graph.facebook.com/?id=8083675473.
Now i wonder why sometimes it is slow. Maybe facebook has limitations on the number of request i can make ?
I just want to show the number of like somewhere, what is the best way to retrieve it without slowing down the whole page?
I tried to load the content by ajax, but it does not work since it is a cross site request.

A:
Now i wonder why sometimes it is slow. Maybe facebook has limitations on the number of request i can make ?

Yes, but if you reach the quota, you can not even getting any data

I just want to show the number of like somewhere, what is the best way to retrieve it without slowing down the whole page?

Cache locally, that's mean get the results from facebook,
and write it to disk-file/database/memcache,
subsequently, you will be no longer require to fetch the data from facebook
in order to keep the data freshness, you should periodically (schedule) to update the cache


text:
Q: sed multiple repacement in a line It may be a very basic question but I am not able to form the sed on liner for this.
Consider this line
foo@some_text/48183 bar@another-test/22787 xyz@some_another_text/2291

I want to replace everything from "@" to space separated by comma.
So my expected output should look like
foo,bar,xyz

I was trying  sed -e 's/@.*[^ ]/,/g' to replace till space however it is replacing whole whole line(not so good in writing regular exp).
Any help will be appreciated.

A: You may find and capture any 1+ chars other than @ before a @ char, then match @ and any 0+ chars other than whitespace followed with 0+ whitespace chars, and replace all that with a placeholder to Group 1 and a comma. Then, you will have to remove the trailing comma.
See a sed demo:
s='foo@some_text/48183 bar@another-test/22787 xyz@some_another_text/2291'
echo "$s" | sed -E 's/([^@]+)@[^[:space:]]*[[:space:]]*/\1,/g' | sed 's/,$//'

Note that you may also use sed 's/\([^@][^@]*\)@[^[:space:]]*[[:space:]]*/\1,/g' insead of the POSIX ERE version. In BRE POSIX, you should escape ( and ) to form a capturing group, and + quantifier should be escaped, or replaced with a aa* construction.
Details

*

*([^@]+) - Capturing group 1: 1+ chars other than @

*@ - a @ char

*[^[:space:]]* - 0+ chars other than whitespace

*[[:space:]]* - 0+ whitespace chars

The \1 is a placeholder for the text captured with the capturing group #1.
The second sed 's/,$//' is used to remove the trailing , at the end of the string.

A: Following awk may help you here.
awk 'BEGIN{OFS=","}{for(i=1;i<=NF;i++){sub(/@.*/,"",$i)}} 1'  Input_file

Solution 2nd: Taking code from Wiktor Stribizew's post and modifying it a bit to convert it to a single sed now.
sed -E 's/([^@]+)@[^[:space:]]*[[:space:]]*/\1,/g;s/,$//'  Input_file

A: The basic problem with the match part of your regex (@.*[^ ]) is that .*
matches almost the whole rest of the source string after the first @
(a quite common error) and [^ ] matches the last non-space char.
If you use @\S+\s* as the match part, then \S+ matches "non-space" part
(e.g. some_text/48183) and \s* matches optional spaces thereafter.
This replacement gives foo,bar,xyz,, so you should somehow delete the last comma.

A: You can also do it the other way around even if it might be a bit more pipy.
$ echo "foo@some_text/48183 bar@another-test/22787 xyz@some_another_text/2291" | (tr ' ' ',' | grep -oP '(?=,|^)[^@]+' | tr -d '\n'; echo "")
foo,bar,xyz

Instead of replacing, part of the string you can directly extract the relevant parts.
Explanations:

*

*tr ' ' ',' in order to replace all spaces by commas.

*grep -oP '(?=,|^)[^@]+' to fetch everything before the @. It uses perl regex with lookaround (imposing the constraint that the preceding character is either a comma or the beginning of the string and accept all the characters except @.

*tr -d '\n' is used to remove the EOL inserted by grep

*the echo "" may be omitted if you do not need to have an ending \n. You can then simplify the command in tr ' ' ',' | grep -oP '(?=,|^)[^@]+' | tr -d '\n'


text:
Q: SQL String, TypeError: not enough arguments for format string I tried to write a SQL in python, I always get the erorr
v1 = 'abc'
v2 = 'def'

name =  """
   fulfillment_week BETWEEN STRFTIME_USEC(DATE_ADD(%(v1)s, -34, "DAY"), '%Y-%m-%d')
      AND STRFTIME_USEC(DATE_ADD(%(v2)s, -6, "DAY"), '%Y-%m-%d')
""" % {'v1': v1, 'v2':v2}

when I run it, I always get


text:
Q: Ubuntu server: Cannot setup dummy driver alsa (LXC container) // modprobe issue I'm trying to setup alsa on my ubuntu server, but it seems that the drivers are not installed & I don't know how to solve this problem. I just wanna setup a dummy soundcard. But I really don't know how to do it.

*

*aplay -l :

aplay: device_list:272: no soundcards found...

*

*lspci :

00:00.0 Host bridge: Intel Corporation Xeon E3-1200 v6/7th Gen Core Processor Host Bridge/DRAM Registers (rev 05)
00:01.0 PCI bridge: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor PCIe Controller (x16) (rev 05)
00:01.1 PCI bridge: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor PCIe Controller (x8) (rev 05)
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 630 (rev 04)
00:14.0 USB controller: Intel Corporation 200 Series/Z370 Chipset Family USB 3.0 xHCI Controller
00:16.0 Communication controller: Intel Corporation 200 Series PCH CSME HECI #1
00:17.0 SATA controller: Intel Corporation 200 Series PCH SATA controller [AHCI mode]
00:1b.0 PCI bridge: Intel Corporation 200 Series PCH PCI Express Root Port #17 (rev f0)
00:1b.4 PCI bridge: Intel Corporation 200 Series PCH PCI Express Root Port #21 (rev f0)
00:1c.0 PCI bridge: Intel Corporation 200 Series PCH PCI Express Root Port #1 (rev f0)
00:1c.4 PCI bridge: Intel Corporation 200 Series PCH PCI Express Root Port #5 (rev f0)
00:1d.0 PCI bridge: Intel Corporation 200 Series PCH PCI Express Root Port #9 (rev f0)
00:1f.0 ISA bridge: Intel Corporation 200 Series PCH LPC Controller (Z270)
00:1f.2 Memory controller: Intel Corporation 200 Series/Z370 Chipset Family Power Management Controller
00:1f.3 Audio device: Intel Corporation 200 Series PCH HD Audio
00:1f.4 SMBus: Intel Corporation 200 Series/Z370 Chipset Family SMBus Controller
01:00.0 Ethernet controller: Intel Corporation I210 Gigabit Network Connection (rev 03)
02:00.0 Non-Volatile memory controller: Intel Corporation PCIe Data Center SSD (rev 02)
04:00.0 Non-Volatile memory controller: Intel Corporation PCIe Data Center SSD (rev 02)
06:00.0 USB controller: ASMedia Technology Inc. ASM2142 USB 3.1 Host Controller

*

*alsa force-reload:

alsa force-reload
Unloading ALSA sound driver modules: snd-hda-codec-hdmi snd-hda-codec-realtek snd-hda-codec-generic snd-hda-intel snd-hda-codec snd-hda-core snd-hwdep snd-pcm snd-timer (failed: modules still loaded: snd-hda-codec-hdmi snd-hda-codec-realtek snd-hda-codec-generic snd-hda-intel snd-hda-codec snd-hda-core snd-hwdep snd-pcm snd-timer).
Loading ALSA sound driver modules: snd-hda-codec-hdmi snd-hda-codec-realtek snd-hda-codec-generic snd-hda-intel snd-hda-codec snd-hda-core snd-hwdep snd-pcm snd-timermodprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hda-codec-hdmi not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hda-codec-realtek not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hda-codec-generic not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hda-intel not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hda-codec not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hda-core not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-hwdep not found in directory /lib/modules/4.15.18-25-pve
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: ERROR: ../libkmod/libkmod.c:514 lookup_builtin_file() could not open builtin file '/lib/modules/4.15.18-25-pve/modules.builtin.bin'
modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-timer not found in directory /lib/modules/4.15.18-25-pve
 (failed).

*

*modprobe snd-dummy:

modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.15.18-25-pve/modules.dep.bin'
modprobe: FATAL: Module snd-seq-dummy not found in directory /lib/modules/4.15.18-25-pve

*

*alsamixer :

Cannot open mixer: No such file or directory

It seems that no drivers are installed. I cannot figure out what happened. I have no directory /lib/modules btw. It seems that all of them are in /sys/modules.
Also, my uname -r is 4.15.18-25-pve which does not correspond to any linux-generic-uname -r etc... Well, I really don't know what's happening.
My os : ubuntu server 19.10

A: I've found a solution.
I needed an independent of host kernel, so now I use a KVM VPS instead of an LXC container. It is better in my case.


text:
Q: access mdb date/time issue I am trying to fetch the record of 3rd june of 2013 from my database which is made in ms access. Dates are stored in the format of dd/MM/yyyy, below is my query
AND (a.Date = #" + date + "#) ) order by e.E_ID asc

But the amazing thing is i have inserted a record on date of 03/06/2013 which is todays date, while it takes it as 6th march 2013, i have corrected my regional settings, still the same issue. Also in my query i am query for matching date i am using dd/MM/yyyy. Is this a bug from microsoft? please help

A:
Dates are stored in the format of dd/MM/yyyy

I suspect they're not. I suspect they're stored in some native date/time format which is doubtless much more efficient than a 10 character string. (I'm assuming you're using an appropriate field type rather than varchar, for example.) It's important to differentiate between the inherent nature of the data and "how it gets displayed when converted to text".

But the amazing thing

I don't see this as amazing. I see it as a perfectly natural result of using string conversions unnecessarily. They almost always bite you in the end. You're not trying to represent a string - you're trying to represent a date. So use that type as far as you possibly can.
You should:

*

*Use parameterized SQL for queries for many reasons - most importantly to avoid SQL injection attacks, but also to avoid unneccessary string conversions of this kind

*Specify the parameter value as a DateTime, thus avoiding the string conversion

You haven't specified which provider type you're using - my guess is OleDbConnection etc. Generally if you look at the documentation for the Parameters property of the relevant command class, you'll find an appropriate example. For example, OleDbCommand.Parameters shows a parameterized query on an OleDbConnection. One thing worth noting from the docs:

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. [...]
  Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.


text:
Q: Set input group min and max value dynamically I'm looking for a way to update or validate the min and max value of my dynamic input-group inputs with plus and minus button.
Here's what I've done so far:
HTML

      <button type="button" class="btn btn-danger btn-number" data-type="minus" data-field="numbergroup'+thisgroupid+'id'+buttonid+'max&'+row.max+'"">

      </button>

    <input type="text" name="numbergroup'+thisgroupid+'id'+buttonid+'max&'+row.max+'"" value="0" class="form-control input-number" min="'+row2.min+'"  max="'+row2.max+'">

      <button type="button" class="btn btn-success btn-number" data-type="plus" data-field="numbergroup'+thisgroupid+'id'+buttonid+'max&'+row.max+'"">

      </button>

JS
 $('.btn-number').click(function(e){
e.preventDefault();
fieldName = $(this).attr('data-field');
console.log(fieldName)
 var grpmax = fieldName.split('&')[1];
 console.log(grpmax)
type      = $(this).attr('data-type');
 console.log(type)
var input = $("input[name='"+fieldName+"']");
var currentVal = parseInt(input.val());
if (!isNaN(currentVal)) {
    if(type == 'minus') {
        if(currentVal > input.attr('min')) {
            input.val(currentVal - 1).change();
        }
        if(parseInt(input.val()) == input.attr('min')) {
            $(this).attr('disabled', true);
        }

    } else if(type == 'plus') {

        if(currentVal < input.attr('max')) {
            input.val(currentVal + 1).change();
        }
        if(parseInt(input.val()) == input.attr('max')) {
            $(this).attr('disabled', true);
        }
    }
} else {
    input.val(0);
}
});
$('.input-number').focusin(function(){
   $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function() {

minValue =  parseInt($(this).attr('min'));
maxValue =  parseInt($(this).attr('max'));
valueCurrent = parseInt($(this).val());

name = $(this).attr('name');
if(valueCurrent >= minValue) {
    $(".btn-number[data-type='minus'][data-field='"+name+"']").removeAttr('disabled')
} else {
    alert('Sorry, the minimum value was reached');
    $(this).val($(this).data('oldValue'));
}
if(valueCurrent <= maxValue) {
    $(".btn-number[data-type='plus'][data-field='"+name+"']").removeAttr('disabled')
} else {
    alert('Sorry, the maximum value was reached');
    $(this).val($(this).data('oldValue'));
 }

 });
 $(".input-number").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

I'm setting the min and max values for each input field, but I'm not setting the min and max values for each input groups that will be created. I need to set the group max value or add validation to check if the group's total value is less than or equal to grpmax

A: Try

function add(groupId,val) {
  let inp = document.querySelector(`[name=numbergroup_${groupId}]`);
  inp.value= +inp.value + val;
  if(inp.value<+inp.min) inp.value=inp.min;
  if(inp.value>+inp.max) inp.value=inp.max;
}
Min:-2, Max:5

      <button type="button" onclick="add(123,-1)" >
        -
      </button>

    <input type="text" name="numbergroup_123" value="0"  min="-2"  max="5">

      <button type="button" onclick="add(123,1)" >
        +
      </button>


text:
Q: StopWords() not working after using RegexTokenizer() in Spark/Scala ML I need to use StopWordsRemover after I use RegexTokenizer. However, I noticed that no stop words are being removed. I noticed when using Tokenizer (as opposed to RegexTokenizer) stop words are removed because Tokenizer converts the output into an array of terms. RegexTokenizer outputs only an array of strings with (not comma separated). Is there a fix for this?
Here is what my data looks like where "body" is the initial data. You can see "removedStopWords" is the same thing as "removeTags" column. This should not be the case:

Code:
val regexTokenizer = new RegexTokenizer() // first remove tags from string
  .setInputCol("body")
  .setOutputCol("removeTags")
  .setPattern("<[^>]+>")
val stopWordsRemover = new StopWordsRemover()
  .setInputCol(regexTokenizer.getOutputCol)
  .setOutputCol("removedStopWords")

A: A tokenizer should take a stream of characters (e.g. a sentence) and break it up into smaller chunks (e.g. words).
For example, a Tokenizer in Spark will split a sentence on whitespaces.
Here, you use the RegexTokenizer to remove HTML tags (more accuratly, split the sentence into tokens based on tags). While this works, you need to make sure that the output is split into individual words as well.
To do that, you can add a condition to the regex to, in addition to tags, split on any whitespaces by adding \\s+ to the regex pattern:
val regexTokenizer = new RegexTokenizer() // removes tags from string and split into words
  .setInputCol("body")
  .setOutputCol("removeTags")
  .setPattern("<[^>]+>|\\s+")

Now using StopWordsRemover should work as expected.


text:
Q: Recursively intercepting $http In order to better consume a hateoas enabled rest api I got the idea to intercept http calls and add some methods to my resource objects before returning them.
The idea is that if the resource has an array of links I'll add methods to easy further http requests.
The below code is push to the interceptors array of a $httpProvider and does pretty much what I want.
define(['angular'], function (angular) {

    var $http = angular.injector(['ng']).get('$http');

    function flattenLinks(links) {
        for (var key in links) {
            var rel = links[key].rel;
            var href = links[key].href;
            links[rel] = href;
        }
    }

    return {
        'response': function responseHandler(response) {
            var data = response.data ? response.data : response;
            if(typeof data === 'string' || !data.hasOwnProperty('links')) {
                return response;
            }

            if(data.links instanceof Array) {
                flattenLinks(data.links);
            }

            if(data instanceof Array) {
                for(var key in data) {
                    responseHandler(data[key]);
                }
            }

            data.hasLink = function(link) {
                return link in data.links;
            };

            data.get = function(rel) {
                return $http.get(data.links[rel]);
            };

            data.delete = function(rel) {
                return $http.delete(data.links[rel]);
            };

            data.post = function(rel) {
                return $http.post(data.links[rel], data);
            };

            data.put = function(rel) {
                return $http.put(data.links[rel], data);
            };

            return response;
        }
    };
});

The problem is that when I use, as seen below, my added methods to do requests the response isn't handled by my interceptor. The $http.get, $http.delete, etc. done from within my interceptor isn't intercepted (naturally!).
    vm.someResourceObj.get('self').then(function(response) {
        console.log(response);
    });

So the question is. How do I get the internal calls to $http handled?

A: First of all - this is not an answer to you question =)
But it's a kind of advice: man, you are really try to develop a bicycle.
According to developers guide you should use $resource instead of $http to interact with REST api. Especially with RESTful.
$resource service will provide you functionality to make exactly what you want - to make requests like User.get() and after this User.save(), User.update(), etc.
My suggest is to create a factory for each entity(like "user", "account", etc), or for each workflow(like "sign up").
'use strict';

angular.module('app.factories.user', ['ngResource'])

    .factory('UserFactory', function ($resource) {

      var _userApi = {
        user: $resource('/user', {}, {})
      };

      return {
        getCurrentUser: function () {
          return _userApi.user.get(function (data) {
            // here we got data.user;
          }, function (response) {
            console.error(response.status);
          }).$promise;
        }
      };

    })
;

And use it in a controller:
.controller('UserPageCtrl', function ($scope, UserFactory) {

      var currentUser;

      $scope.getCurrentUser = function () {
        return UserFactory.getCurrentUser().success(function (user) {
          //here we got user
          currentUser = user;

          //now we able do stuf like
          //currentUser.save()
          //etc.
        }).error(function (err) {
          console.error(err);
        });
      };

    });

So, don't mind if examples above little bit... you know... let's say if you don't like it ))
Just take a look at $resource documentation (and this)
If you don't like resource, you can use third-party restanguar (or perhaps something else). But restangular is much more strict, so choose it only if you know for sure that your backend developers aren't idiots.
UPD1: About interceptors (I'll put here my working code for error intercepting, the idea of this code is to logout user when any request return 403 error status):
You are able to add all facctory to global $httpProvider(at module config section).
Like this:
app.config(function  ($urlRouterProvider, $httpProvider) {
      //Process backend errors
      $httpProvider.interceptors.push('errorsFactory');
})

And here is errorsFactory:
'use strict';

angular.module('app.factories.errors', [])

    .factory('errorsFactory', function ($q) {

      var HTTP_STATUS = {
        FORBIDDEN: 403
      };

      return {
        response: function (response) {
          if (response.status === HTTP_STATUS.FORBIDDEN) {
            //logout here
          }
          return response || $q.when(response);
        },
        responseError: function (rejection) {
          if (rejection.status === HTTP_STATUS.FORBIDDEN) {
            //logout here
          }
          return $q.reject(rejection);
        }
      };
    })
;

A: Use $injector to get $http instead of accessing it via angular..
Detailed Answer:
The problem is how you inject $http. It seems that you get some $http that is outside of your app (I can't exactly say why, though). var $http = angular.injector(['ng']).get('$http'); doesn't do what you want (or what you think it does).
You could do var $http = angular.element(document).injector().get('$http'); (or probably better use $document there), but imo you should use the $injector-service normally: you can just add $injector to your dependencies/inject statement and inside your interceptor use that to retrieve the service you want like: var $http = $injector.get("$http");
With that your interceptor will intercept the $http-calls it makes.


text:
Q: How to list all configuration files for an already installed package? I am running Ubuntu 12.10 and, if possible, I would like to get the list of configuration files available for a given package that is already installed.
I would prefer to do this using dpkg or apt if possible, but no problem if other tools such as aptitude or dselect are needed/recommended.

A: Let's for example test the package apt to get the config file(s).
It can be tricky to understand what .conffiles you should check to see the info so I suggest using grep to find the clue.
locate *.conffiles | grep apt

/var/lib/dpkg/info/apt-config-icons.conffiles
/var/lib/dpkg/info/apt.conffiles
/var/lib/dpkg/info/aptdaemon.conffiles
/var/lib/dpkg/info/apturl-common.conffiles
/var/lib/dpkg/info/libatk-adaptor:amd64.conffiles

And to cat any of these in particular if you are interested according to Marcin's Kaminski answer.
Another trick is to read the manual, for instance man apt will lead you to SEE ALSO section from where you can call man apt.conf where you will see the location of the config file for apt in this case: /etc/apt/apt.conf.
However, config file /etc/apt/apt.conf may not even exist. Be aware of that when searching for the config files.
In Linux config files should be inside the /etc/ directory. You may use dpkg-query -L your_package | grep etc to list all package files and directories inside the /etc/ directory.

A: There's no need to use anything other than cat, if I understood your intention correctly:
cat /var/lib/dpkg/info/<package>.conffiles

should give you what you're after. For instance for package zsh:
% cat /var/lib/dpkg/info/zsh.conffiles
/etc/zsh/zlogin
/etc/zsh/zlogout
/etc/zsh/zprofile
/etc/zsh/zshenv
/etc/zsh/zshrc
/etc/zsh/newuser.zshrc.recommended

Regarding a case where there's no such file for a given package - it's up to the package maintainer to designate certain files as configuration. If this hasn't been done properly, you should file a bug where appropriate.
In such cases you have a couple of options.

*

*List files belonging to the package that are in /etc/:
dpkg -L package | grep '/etc'

*Fetch and inspect the source package to find out how it was compiled (which should also show you where it expects its configuration files to be located).
apt-get source package
less package-x.y.z/debian/rules

*Look up the upstream project page to find documentation.

A: How about dpkg -S [package-name]? Cant see it being mentioned here.
root@homehub:/# dpkg -S nginx

nginx-common: /usr/share/nginx/html
nginx-full: /usr/share/man/man8/nginx.8.gz
libnginx-mod-http-xslt-filter: /usr/share/doc/libnginx-mod-http-xslt-filter/copyright
nginx-common: /etc/logrotate.d/nginx
libnginx-mod-mail: /usr/share/doc/libnginx-mod-mail/changelog.gz
libnginx-mod-http-upstream-fair: /usr/share/doc/libnginx-mod-http-upstream-fair
libnginx-mod-http-auth-pam: /usr/share/doc/libnginx-mod-http-auth-pam/changelog.Debian.gz
libnginx-mod-http-image-filter: /usr/lib/nginx/modules/ngx_http_image_filter_module.so
nginx-common: /etc/nginx/snippets
libnginx-mod-mail: /usr/share/doc/libnginx-mod-mail/copyright
nginx-common: /etc/nginx/snippets/fastcgi-php.conf
libnginx-mod-http-xslt-filter: /usr/share/doc/libnginx-mod-http-xslt-filter/changelog.Debian.gz
nginx-full: /usr/share/doc/nginx-full/copyright
nginx-common: /usr/share/doc/nginx-common
nginx-common: /etc/ufw/applications.d/nginx
libnginx-mod-http-upstream-fair: /usr/share/doc/libnginx-mod-http-upstream-fair/changelog.gz
libnginx-mod-stream: /usr/share/nginx/modules-available/mod-stream.conf
nginx-common: /etc/nginx/sites-enabled
libnginx-mod-http-upstream-fair: /usr/share/doc/libnginx-mod-http-upstream-fair/copyright
libnginx-mod-http-subs-filter: /usr/share/doc/libnginx-mod-http-subs-filter/changelog.gz
libnginx-mod-http-dav-ext: /usr/share/nginx/modules-available/mod-http-dav-ext.conf
nginx-common: /etc/nginx/koi-utf
nginx-common: /etc/nginx/mime.types
nginx-common: /usr/share/vim/addons/syntax/nginx.vim
nginx-common: /usr/share/doc/nginx-common/NEWS.Debian.gz
nginx-common: /usr/share/doc/nginx-common/README.Debian
nginx-full: /usr/share/doc/nginx-full
libnginx-mod-mail: /usr/share/nginx/modules-available/mod-mail.conf
libnginx-mod-http-auth-pam: /usr/share/doc/libnginx-mod-http-auth-pam/changelog.gz
nginx: /usr/share/doc/nginx
nginx-common: /etc/nginx/win-utf
libnginx-mod-http-dav-ext: /usr/share/doc/libnginx-mod-http-dav-ext
....

And sometimes depending on filename structure it might be good if piped out to grep names containing ".conf":
root@homehub:/# dpkg -S nginx |grep ".conf"

nginx-common: /etc/nginx/snippets/fastcgi-php.conf
libnginx-mod-stream: /usr/share/nginx/modules-available/mod-stream.conf
libnginx-mod-http-dav-ext: /usr/share/nginx/modules-available/mod-http-dav-ext.conf
libnginx-mod-mail: /usr/share/nginx/modules-available/mod-mail.conf
libnginx-mod-http-auth-pam: /usr/share/nginx/modules-available/mod-http-auth-pam.conf
nginx-common: /etc/nginx/fastcgi.conf
nginx-common: /etc/init/nginx.conf
nginx-common: /etc/nginx/conf.d
libnginx-mod-http-subs-filter: /usr/share/nginx/modules-available/mod-http-subs-filter.conf
libnginx-mod-http-geoip: /usr/share/nginx/modules-available/mod-http-geoip.conf
libnginx-mod-http-echo: /usr/share/nginx/modules-available/mod-http-echo.conf
libnginx-mod-http-upstream-fair: /usr/share/nginx/modules-available/mod-http-upstream-fair.conf
nginx-common: /etc/init/nginx.conf
libnginx-mod-http-xslt-filter: /usr/share/nginx/modules-available/mod-http-xslt-filter.conf
nginx-common: /etc/nginx/snippets/snakeoil.conf
nginx-common: /etc/nginx/nginx.conf
libnginx-mod-http-image-filter: /usr/share/nginx/modules-available/mod-http-image-filter.conf


text:
Q: What is lock-free multithreaded programming? I have seen people/articles/SO posts who say they have designed their own "lock-free" container for multithreaded usage. Assuming they haven't used a performance-hitting modulus trick (i.e. each thread can only insert based upon some modulo) how can data structures be multi-threaded but also lock-free???
This question is intended towards C and C++.

A: The idea of "lock free" is not really not having any lock, the idea is to minimize the number of locks and/or critical sections, by using some techniques that allow us not to use locks for most operations.
It can be achieved using optimistic design or transactional memory, where you do not lock the data for all operations, but only on some certain points (when doing the transaction in transactional memory, or when you need to roll-back in optimistic design).
Other alternatives are based on atomic implementations of some commands, such as CAS (Compare And Swap), that even allows us to solve the consensus problem given an implementation of it. By doing swap on references (and no thread is working on the common data), the CAS mechanism allows us to easily implement a lock-free optimistic design (swapping to the new data if and only if no one have changed it already, and this is done atomically).
However, to implement the underlying mechanism to one of these - some locking will most likely be used, but the amount of time the data will be locked is (supposed) to be kept to minimum, if these techniques are used correctly.

A: The new C and C++ standards (C11 and C++11) introduced threads, and thread shared atomic data types and operations. An atomic operation gives guarantees for operations that run into a race between two threads. Once a thread returns from such an operation, it can be sure that the operation has gone through in its entirety.
Typical processor support for such atomic operations exists on modern processors for compare and swap (CAS) or atomic increments.
Additionally to being atomic, data type can have the "lock-free" property. This should perhaps have been coined "stateless", since this property implies that an operation on such a type will never leave the object in an intermediate state, even when it is interrupted by an interrupt handler or a read of another thread falls in the middle of an update.
Several atomic types may (or may not) be lock-free, there are macros to test for that property. There is always one type that is guaranteed to be lock free, namely atomic_flag.

A: The key in lock-free programming is to use hardware-intrinsic atomic operations.
As a matter of fact, even locks themselves must use those atomic operations!
But the difference between locked and lock-free programming is that a lock-free program can never be stalled entirely by any single thread. By contrast, if in a locking program one thread acquires a lock and then gets suspended indefinitely, the entire program is blocked and cannot make progress. By contrast, a lock-free program can make progress even if individual threads are suspended indefinitely.
Here's a simple example: A concurrent counter increment. We present two versions which are both "thread-safe", i.e. which can be called multiple times concurrently. First the locked version:
int counter = 0;
std::mutex counter_mutex;

void increment_with_lock()
{
    std::lock_guard<std::mutex> _(counter_mutex);
    ++counter;
}

Now the lock-free version:
std::atomic<int> counter(0);

void increment_lockfree()
{
    ++counter;
}

Now imagine hundreds of thread all call the increment_* function concurrently. In the locked version, no thread can make progress until the lock-holding thread unlocks the mutex. By contrast, in the lock-free version, all threads can make progress. If a thread is held up, it just won't do its share of the work, but everyone else gets to get on with their work.
It is worth noting that in general lock-free programming trades throughput and mean latency throughput for predictable latency. That is, a lock-free program will usually get less done than a corresponding locking program if there is not too much contention (since atomic operations are slow and affect a lot of the rest of the system), but it guarantees to never produce unpredictably large latencies.

A: For locks, the idea is that you acquire a lock and then do your work knowing that nobody else can interfere, then release the lock.
For "lock-free", the idea is that you do your work somewhere else and then attempt to atomically commit this work to "visible state", and retry if you fail.
The problems with "lock-free" are that:

*

*it's hard to design a lock-free algorithm for something that isn't trivial. This is because there's only so many ways to do the "atomically commit" part (often relying on an atomic "compare and swap" that replaces a pointer with a different pointer).

*if there's contention, it performs worse than locks because you're repeatedly doing work that gets discarded/retried

*it's virtually impossible to design a lock-free algorithm that is both correct and "fair". This means that (under contention) some tasks can be lucky (and repeatedly commit their work and make progress) and some can be very unlucky (and repeatedly fail and retry).

The combination of these things mean that it's only good for relatively simple things under low contention.
Researchers have designed things like lock-free linked lists (and FIFO/FILO queues) and some lock-free trees. I don't think there's anything more complex than those. For how these things work, because it's hard it's complicated. The most sane approach would be to determine what type of data structure you're interested in, then search the web for relevant research into lock-free algorithms for that data structure.
Also note that there is something called "block free", which is like lock-free except that you know you can always commit the work and never need to retry. It's even harder to design a block-free algorithm, but contention doesn't matter so the other 2 problems with lock-free disappear. Note: the "concurrent counter" example in Kerrek SB's answer is not lock free at all, but is actually block free.


text:
Q: What's the difference between management.server.port and management.port properties? To run Actuator on a separate port we write management.server.port: 9001 in the application.properties file.
But there is a confusing line in Actuator Guide code:
@TestPropertySource(properties = {"management.port=0"})

And then
...
@Value("${local.management.port}")
private int mgt;

Here is the source class https://github.com/spring-guides/gs-actuator-service/blob/master/complete/src/test/java/hello/HelloWorldApplicationTests.java
What's the difference between
 management.server.port,
management.port and
 local.management.port?

A: The management.server.port is used to expose management/actuator endpoints to a different HTTP port other than the one used for running the application.
And the management.port=0 is used to provide random port for the actuator to run while integration testing.
Whereas local.management.port is used to inject the random port.
Reference Spring Boot Actuator: Production-ready features and Random Port for Actuator


text:
Q: How do I link a container in docker only if it exists when starting the container? In a server, I currently have many HTTP-applications running which would share port 80, so I have one main nginx container that routes to the specific apps on a hostname basis (reverse proxy).
However, when I docker start nginx, all those containers must be running, because I linked all of them when I run the nginx container for the first time. This creates a single bottleneck, so if one of my applications goes down, I cannot start the main nginx:
Error response from daemon: Cannot start container nginx: Cannot link to a non running container: /myapp AS /nginx/myapp
and then all of my applications are down instead of just one.
Is there a "Best Practice" for some setup ike this? Should I run the nginx container every time instead of stopping and starting it and then add the links of the apps that are currently running? Should I put nginx on the host level instead of running it in a container?

A: Frankly, links as they stand aren't good enough to solve this problem, at least not beyond a development set-up. I suggest you use a key-value store or something similar to store the mapping.