Openvpn problems with route-nopull

Question: here is the situation,I have:

vps with public ip
vpn service
own router with public ip

if i connect vpn (interface name tunVPN) without route-nopull vps drops all connections (like ssh) sice it has new default gateway through vpn provider. if i use route-nopull on connection it connects but just sits there, i cannot use it (for example if i try to  ping -I tunVPN xxx.xxx or bind some service to it).
So my question is what route should i add to make this vpn work.
i've even tried to use openvpn 2.4 with pool-filter but its no good.
here is route wihit route-nopull:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         gateway         0.0.0.0         UG    100    0        0 eth0
10.114.0.0      0.0.0.0         255.255.0.0     U     0      0        0 tunvpn
62.x.x.0        0.0.0.0         255.255.255.0   U     100    0        0 eth0
62.x.x.254      gateway         255.255.255.255 UGH   100    0        0 eth0

same without route-nopull
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.114.0.1      220.127.116.11       UG    0      0        0 tunvpn
default         gateway         0.0.0.0         UG    100    0        0 eth0
10.114.0.0      0.0.0.0         255.255.0.0     U     0      0        0 tunvpn
62.x.x.0        0.0.0.0         255.255.255.0   U     100    0        0 eth0
62.x.x.254      gateway         255.255.255.255 UGH   100    0        0 eth0
18.104.22.168       10.114.0.1      188.8.131.52       UG    0      0        0 tunvpn
185.x.x.68      gateway         255.255.255.255 UGH   0      0        0 eth0

Any sugestions? I dont want to use vpn for all the traffic just for some :)
Answer: After some time i managed to work it out: two routing tables
add to /etc/iproute2/rt_tables
# reserved values
#
255 local
254 main
253 default
0   unspec
#
# local
#
#1  inr.ruhep
1 rt2

then configure rt2 (routing table 2) through up.sh script invoked by openvpn on connection
/usr/sbin/ip route add 0.0.0.0/0  dev tunvpn src $VPNADDR table rt2
/usr/sbin/ip rule add from $VPNADDR table rt2
/usr/sbin/ip rule add to $VPNADDR table rt2

where $VPNADDR is ip from vpn server usually $4 is enough.
Hope this will help.

Openvpn problems with route-nopull


When is a real function orthogonal to its derivative?

Question: I saw this proof that a function $f$ is orthogonal to its derivative $f'$:
$$
\int_{-\infty}^\infty f(t)f'(t)dt
= \frac{1}{2\pi} \int_{-\infty}^\infty F(\Omega) (-j\Omega) F^*(\Omega) d\Omega
= -\frac{1}{2\pi} \int_{-\infty}^\infty j\Omega |F(\Omega)|^2 d\Omega
= 0
$$
where $F(\Omega)$ denotes the Fourier transform of $f(t)$.
This clearly isn't true for all functions, e.g. $f(t) = \max(0,t)$. Could anyone help me figure out which assumptions were made? The original text was
not more specific than this.
Comment: Probably both $f$ and $f'$ ought to lie in $L^2$.
Comment: @Mark Are you considering only the case for $\omega(x) =1$?
Comment: @PeterT.off I don't follow, what's $\omega(x)$?
Comment: @Mark The weighing function. Not all [orthogonal functions](http://mathworld.wolfram.com/OrthogonalFunctions.html) have the same weighing function.
Comment: @PeterT.off: Aha. Yes, that's orthogonality in the room I'm considering.
Answer: In addition to the assumptions that the integral even makes sense, this particular result is based on the assumption is that $f(t)^2$ is defined at $t = \pm\infty$ and that the two limiting values (at $t = \infty$ and $t = -\infty$) are equal.
$$
\int_{-\infty}^\infty f(t)f^\prime(t)dt = \tfrac{1}{2}\int_{-\infty}^\infty \tfrac{d}{dt}f(t)^2 dt = \tfrac{1}{2}f(t)^2|_{-\infty}^\infty
$$
Comment: By "$f(t)^2$ is defined at $t=\pm\infty$", are you referring to the limits at $\pm\infty$? And by making sense, do you mean that it converges?
Comment: Yes for both of them.


Role of Dominant 7th chord in particular progressions

Question: Examining this progression in F:

 | F | A7 | Dm7 | Bb, Bbm |

 | F, E7 | Gm7, C7 | F, D7 | Gm7, C7 |

In the fifth measure I really don't understand what role has the E7 chord because I can't identify as:

primary dominant - it isn't on the fifth degree of the scale
secondary dominant - it doesn't resolve to his relative first degree (Am7)
tritone substitution - it does not resolve to Eb his relative IIb

So what is the role of the chord?
Answer: It's just a passing chord on the way to Gm7 from F.
From Gm7 to E7 the D is common and the other notes are moving chromatically to get to Gm7. If you look at the notes each contain you'll see:

F -> E  -> F
A -> G# -> G
C -> B  -> Bb
C -> D  -> D

You'll notice the chromatic descending line in A to G and C to Bb  and The F - E - F can be looked at as a neighboring tone.
Answer: In F major the subdominant chord is Bb7, and E7 is the tritone substitution of that chord.
The tritone interval G#-D appears in both chords.
In the E7 chord the G# functions as the 3rd and the D functions as the 7th.
And if you respell G# as Ab then the same interval Ab-D appears in the Bb7 chord, the Ab functions as the 7th and the D functions as the 3rd.


Determining the State of a User using their Hostname

Question: Not sure if this is the right SE site. I figured this question doesn't belong on SO, but if you think it doesn't belong here either, I apologize.
I've been looking into determining the location, specifically the state, of a user accessing my website. One of the options I've known about for a while is the GeoIP City Database, however this isn't the most cost effective solution and I'm cheap so I was looking for a less expensive way. Something that occurred to me was that my state was in the public hostname assigned to me by Comcast:
(Dash Separated IP).hsd1.ma.comcast.net

Could it be possible that other ISPs follow this same pattern of inserting the state abbreviation into their users' hostnames? I've been looking around for a list of hostnames for other ISPs, but I haven't found anything. Can anyone verify that this holds true for other major ISPs?
Edit: Is your state in your hostname? Is it abbreviated or written out? Is it in it's own subdomain?

After some more digging, I discovered that Verizon FiOS customers have location data in their hostnames. It seems that the general pattern that they follow is:
static-(Dash Separated IP).(City Abbreviation)(State Abbreviation).fios.verizon.net

So for example a FiOS customer in boston would have a hostname that looks like:
static-(Dash Separated IP).bstnma.fios.verizon.net

I can extract a state from this, leading me to believe that there must be other ISPs that follow this pattern. Can anyone else confirm by checking if their hostname has their state in it?
Answer: GeoIP also offers a free version with obviously drawbacks such as its not as accurate.  It can be found here:
http://www.maxmind.com/app/geolite
If you are interested in web analytics for your site.  I recommend using piwik.  This is a free solution and has GeoIP built in as a plugin. It will show you where your traffic is coming from plus you own all the data unlike with using google analytics.  This can be an issue with large corporations and smaller companies who do not wish for another company to own their data.
As far as MO is concerned, I do not have the state from my ISP.
Comment: Geolite was likely going to be my fallback...either that or the API (in which case I was looking for ways to reduce my number of calls, beyond simple caching). Just out of curiosity: who is your ISP?


Can we submit application to applestore by skipping some versions?

Question: My current application in apple store is with 3.0.1, now to have sync with other platform versions I just wanted to release new version of application with 18.104.22.168. Will it be problem from apple?
Comment: I'm voting to close this question as off-topic because it concerns the policies and procedures of app distribution services, rather than programming. Please refer to: [Are developer-centric questions about application stores on topic?](https://meta.stackoverflow.com/q/272165), [Why can't I ask customer service-related questions?(https://meta.stackoverflow.com/a/255746)
Answer: Yeah surely you can do this,Apple has no problem at all with this,They just check whether current version is above to the previous one or not.
More information on updating your app(s) can be found on this Apple Developer page.
Comment: Thanks @Ayan Khan, Can you please provide apple documentation link for the same?
Comment: I have provided the link for versions,but that not contains the statement to skip versions,I am telling you my personal experience as i did same 2 times.So no problem with that.......:)


java.lang.ClassNotFoundException: org.codehaus.jettison.mapped.MappedXMLOutputFactory

Question: I am getting java.lang.ClassNotFoundException: org.codehaus.jettison.mapped.MappedXMLOutputFactory error while running mule application. I checked jettison-1.1.jar jar is already there in my application folder lib directory but still I am getting this error.
I am getting this error while initialising Spring batch job repository.
java.lang.ClassNotFoundException: org.codehaus.jettison.mapped.MappedXMLOutputFactory
        at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
        at com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver.<init>(JettisonMappedXmlDriver.java:36)
        at org.springframework.batch.core.repository.dao.XStreamExecutionContextStringSerializer.init(XStreamExecutionContextStringSerializer.java:67)
        at org.springframework.batch.core.repository.dao.XStreamExecutionContextStringSerializer.afterPropertiesSet(XStreamExecutionContextStringSerializer.java:62)
        at org.springframework.batch.core.repository.support.JobRepositoryFactoryBean.afterPropertiesSet(JobRepositoryFactoryBean.java:182)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)

Comment: Do you add it to your classpath? How do you run your application?
Comment: We are deploying the application on mule server.
Answer: You need to add jettison.jar file to your project.
Download from here
Comment: I already have jettison-1.1.jar in my project lib directory that contains org.codehaus.jettison.mapped.MappedXMLOutputFactory class.
Comment: @sach Then check if it exists in class path or not.
Comment: My application lib folder contains all the required jar files. jettison-1.1.jar also there in the lib folder and lib folder is added into class path. I think somehow application is not looking into jettison-1.1.jar for the required class.
Comment: I found the issue. Mule server has xstream-1.2.2-osgi.jar that also contains MappedXMLOutputFactory class. If I removed this jar then application work fine. How do we force to use jettison-1.1.jar?


Smooth functions with linearly independent gradients extend to coordinate charts (reference request)

Question: This feels obvious, but I can't find a reference for it. Suppose I have a smooth $n$-dimensional manifold $M$, and I have $k$ smooth functions $f_1,\ldots,f_k \in C^\infty(M)$ such at some point $x \in M$, the gradients $\nabla f_1,\ldots,\nabla f_k$ are linearly independent at $x$ (and therefore in a neighbourhood of $x$). Can I find $n-k$ functions $f_{k+1},\ldots,f_n \in C^\infty(M)$ and a set $U \subset M$ containing $x$ such that $(U,(f_1,\ldots,f_n))$ forms a smooth coordinate chart for $M$ (i.e. is contained in the maximal atlas for $M$)?
Comment: In other words, you have a map $F: M \rightarrow \mathbb{R}^k$, whose Jacobian has maximal rank at $x$, i.e., the map is a submersion near $x$. Now look up the canonical submersion theorem.
Comment: Thank you - that's perfect.
Answer: As @Deane points out in the comments, this is an application of the canonical submersion theorem. It appears in e.g. Guillemin and Haine's Differential Forms, Theorem 4.2.14.


reactjs datepicker date format

Question: Beginner with ReactJS, I use now the wonderful ReactJS Datepicker. Questions about my custom date format :

i found no doc to explain all the possibilities like M is month, MM is month on 2 letters, etc. (shall I look to the github code? which source?)
How to add the name of the day... like Saturday. I tried dddd but it shows the number of the day with 2 leading 0 before !!
How to exclude the non office hour (like hours 0 to 8 and 20 to 23), I tried the excludesTimes below but no way.

Here is my code :
<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChange}
    locale={fr}
    showTimeSelect
    timeFormat="HH:mm"
    timeIntervals={60}
    dateFormat="dddd, DDD, ddd, d, dd MMMM yyyy à HH'h'mm"
    timeCaption="Heure"
    minDate={new Date()}
    showDisabledMonthNavigation
    placeholderText="Choisir ici ..."
    excludeTimes={[0, 1, 2, 3, 4]}
/>

Date shown in input field is then :

0023, 082, 023, 23, 23 mars 2019 à 20h00

Thanks
Comment: rezvani-datepicker
return actual new Date() so you can change the format to what ever you want.
https://github.com/Abolfazl2647/rn-datepicker/
Answer: React datepicker uses Moment.js for dates, I think you should review the docs at his website.
For example MMMM Do YYYY, h:mm:ss a should return a date formated as  March 21st 2019, 8:50:37 am.
EDIT
I went to the repo and it appears the author removed moment from package, so I gave a try to the formatting dates guide found here and it appears to be working now! Per example use "eeee" if you want day of the week.
I made a working example at codesandbox.
Comment: PERFECT, you solve it !It is a pity that one must look into the code to understand the use of the software .. but that is current life !
We can mark this ticket as solved (note the solution is in the previous comment, and not the beginning of te answer speaking about moment.js).
Comment: Link from @PabloHuetCarrasco is outdated. Author is using [format from date-fns package](https://date-fns.org/v2.28.0/docs/format)
Comment: Thank for your help, but it does not solve.. using dateFormat="MMMM Do YYYY, h:mm:ss a" , it displays "March 81st 2019, 8:43:14 PM" .. whereas I ran "npm install moment as you requested.. can you give more clue ?
Comment: I went to the repo and it appears the author removed moment, so I gave a try to the formatting dates guide found [here](http://userguide.icu-project.org/formatparse/datetime) and it appears to be working now! Per example, use "eeee" if you want day of the week. I made you a working example at [codesandbox](https://codesandbox.io/s/ov8z0zvl9).
Comment: Bad documented libraries are a plague...I edited the answer if you want to mark it as approved solution :)
Answer: You also can convert manually ...
  const convertDate = str => {
  str = str.toString();
  let parts = str.split(" ");
  let months = {
    Jan: "01",
    Feb: "02",
    Mar: "03",
    Apr: "04",
    May: "05",
    Jun: "06",
    Jul: "07",
    Aug: "08",
    Sep: "09",
    Oct: "10",
    Nov: "11",
    Dec: "12"
  };
  return parts[3] + "-" + months[parts[1]] + "-" + parts[2];
};

:) Reinventing the wheel
Comment: ugh. I was trying to get away from doing that but credit for you for just writing code instead of relying on someone having written it already!

reactjs datepicker date format


How to return an XLS file to download on form submit

Question: I am trying to create an XLS file and send it to the browser on a form submit but I cannot figure out how to do it. I am using XLS Serialization module but I'm open to all other suggestions. With this module I successfully created some views with XLS Export feature. But now I have a form and the excel file should be created on form submit depending on the submitted data.
I created the following code but if I send the form, I get no excel file to download:
class MyForm extends FormBase {
  private SerializerInterface $serializer;

  public static function create(ContainerInterface $container) {
    return new static($container->get('serializer'));
  }

  public function __construct(SerializerInterface $serializer) {
    $this->serializer = $serializer;
  }

  // Removed the buildForm() etc for simplicity

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = (new StreamedResponse(function () use ($selected_values) {
      $this->serializer->serialize([[1, 2, 3], [4, 5, 6]], 'xlsx');
    }))->send();

    $form_state->setResponse($response);
  }
}

Comment: "didn't work" ? Not sure what that means exactly ... The only weird thing I can see is the ->send(), but you left out some code and you don't say what the error or problem is.
Comment: it means when I send the form, I don't get an excel file to download
Answer: First off, you need a serializer for xls(x), I used https://www.drupal.org/project/xls_serialization
The following example code should deliver what you need:
public function submitForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $filename = "random_file_" . rand() . ".xlsx";

  $response = new StreamedResponse(function () use ($values) {
    echo $this->serializer->serialize([[1, 2, 3], [4, 5, 6]], 'xlsx');
  });
  $response->headers->set('Content-Type', 'application/vnd.ms-excel');
  $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');

  $form_state->setResponse($response);
}

I tried that with the XLS encoder provided https://www.drupal.org/project/xls_serialization and it worked.
Good luck!
References:

https://symfonycasts.com/screencast/symfony-uploads/file-streaming#codeblock-b856bd1a43
https://drupal.stackexchange.com/a/245460/57183
https://evertpot.com/222/
https://www.drupal.org/project/xls_serialization
Comment: Thank you, I worked out a working solution. But with a bit different and simpler callback function in StreamedResponse. Would you mind if I update your code?
Comment: If it's the same approach, yes, please do. Otherwise, this question needs a different answer than mine. Curious in any case! The callback code I wrote in there was based off of your question, perhaps you can update the question and then I can update my answer.
Comment: Updated the code with the one worked for me. Please check my changes: https://drupal.stackexchange.com/posts/308007/revisions If you want you can still rollback to your version. Thanks.
Comment: So, all you needed was the headers' part to get your code working, right?
Comment: Not only the headers. I also added `echo` to the StreamedResponse callback, and removed the `send()` method that I used at the beginning.


SVG stroke-dashoffset animation start (again) on click

Question: I made a simple svg-stroke-animation using css and jquery. The animations starts on click. But i can't find a way to start it again on a second click (or third etc). I think the solution is quite simple but still nothing worked (e.g. .addClass).
This is how it should work:
1. Stroke is visible
2. User clicks on image
3. Stroke animation starts
4. When done: stroke keeps visible
5. User clicks again
6. Stroke animation starts again....
This is my current code:

jQuery(document).ready(function () {

    $("#form").click(function () {

        var path1 = document.querySelector('#umriss');
        var length = path1.getTotalLength();

        $(path1).css("stroke-dasharray", length);

    });

});
body {
    width: 100%;
    font-size: 20px;
    background-color: #eee;
}

.wrapper {

    margin: 0 auto;
    text-align: center;
    max-width: 700px;
}

.bild{
    width: 100%;
    height: 0;
    padding-top: 100%;
    position: relative;
}

svg{
    position: absolute;
    height: 100%;
    width: 100%;
    left:0;
    top:0;

}

#umriss {
    stroke-dashoffset: 2600;
    animation: ani1 4s linear forwards;
}

@keyframes ani1 {
    to {
        stroke-dashoffset: 0;
    }
}

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Stroke</title>

            <svg id="form" x="0px" y="0px" width="812.959px" height="581.971px" viewBox="0 0 812.959 581.971" enable-background="new 0 0 812.959 581.971" xml:space="preserve">
                <path id="umriss" fill="#3CC243" stroke="#141412" stroke-width="10" stroke-miterlimit="10" d="M137.521,128.454        C139.812,9.278,220.056,16.972,313.194,20.365c136.466,4.97,179.837,72.616,205.304,200.859
 c21.428,107.905,195.473,45.773,260.65,56.229c39.317,6.308-28.293,212.529-53.685,245.178
 c-61.222,78.716-262.76,32.434-351.007,35.777c-102.917,3.899-125.172-88.539-81.979-175.921
 c71.457-144.56-162.979-48.431-225.951-44.29C-22.9,344.077,25.05,112.387,137.521,128.454z"/>
</svg>

Answer: I'm using JQuery only to start the animation. Everything else is done with CSS. I've added a checkbox in your HTML that controls the animation. The checkbox is visible but you may hide it (visibility:hidden or display:none).
I hope this is what you want to achieve.

$(label).click(function(){
    $(this).addClass("test");
});
body {
  width: 100%;
  font-size: 20px;
  background-color: #eee;
}

.wrapper {
  margin: 0 auto;
  text-align: center;
  max-width: 700px;
}

.bild {
  width: 100%;
  height: 0;
  padding-top: 100%;
  position: relative;
}

svg {
  position: absolute;
  left: 0;
  top: 0;
}

#umriss {
  stroke-dasharray: 2333.43;
  stroke-dashoffset: 2333.43;
}
.test #umriss {
  animation: ani1 4s linear forwards;}

[type="checkbox"] {
  position: absolute;
  top: 0;
  left: 0;
}

[type="checkbox"]:checked + label #umriss {
  animation: ani2 4s linear forwards;
}

@keyframes ani1 {
  from {
    stroke-dashoffset: 2333.43;
  }
  to {
    stroke-dashoffset: 0;
  }
}

@keyframes ani2 {
  from {
    stroke-dashoffset: 0;
  }
  to {
    stroke-dashoffset: 2333.43;
  }
}

        <input type="checkbox" id="anim"/>

            <svg id="form" x="0px" y="0px" width="200" viewBox="0 0 812.959 581.971">
                <path id="umriss" fill="#3CC243" stroke="#141412" stroke-width="10" stroke-miterlimit="10" d="M137.521,128.454        C139.812,9.278,220.056,16.972,313.194,20.365c136.466,4.97,179.837,72.616,205.304,200.859
 c21.428,107.905,195.473,45.773,260.65,56.229c39.317,6.308-28.293,212.529-53.685,245.178
 c-61.222,78.716-262.76,32.434-351.007,35.777c-102.917,3.899-125.172-88.539-81.979-175.921
 c71.457-144.56-162.979-48.431-225.951-44.29C-22.9,344.077,25.05,112.387,137.521,128.454z"/>
</svg>

UPDATE
In CSS I've used the selector :checked to start one animation or another.
Animation without using the checkbox:
In this case I'm using the click event to add the class .test to bild, and I'm using the event animationend to remove the .test class. I hope it helps.

bild.addEventListener("click",()=>{
  bild.classList.add("test")
})

//umriss.addEventListener("webkitAnimationEnd",..... );
umriss.addEventListener("animationend",()=>{
  console.log("end")
  bild.classList.remove("test");
} );
body {
  width: 100%;
  font-size: 20px;
  background-color: #eee;
}

.wrapper {
  margin: 0 auto;
  text-align: center;
  max-width: 700px;
}

.bild {
  width: 100%;
  height: 0;
  padding-top: 100%;
  position: relative;
}

svg {
  position: absolute;
  left: 0;
  top: 0;
}

#umriss {
  stroke-dasharray: 2333.43;
  stroke-dashoffset: 0;
}
.test #umriss {
  animation: ani1 4s linear forwards;
}

@keyframes ani1 {
  from {
    stroke-dashoffset: 2333.43;
  }
  to {
    stroke-dashoffset: 0;
  }
}

            <svg id="form" x="0px" y="0px" width="200" viewBox="0 0 812.959 581.971">
                <path id="umriss" fill="#3CC243" stroke="#141412" stroke-width="10" stroke-miterlimit="10" d="M137.521,128.454        C139.812,9.278,220.056,16.972,313.194,20.365c136.466,4.97,179.837,72.616,205.304,200.859
 c21.428,107.905,195.473,45.773,260.65,56.229c39.317,6.308-28.293,212.529-53.685,245.178
 c-61.222,78.716-262.76,32.434-351.007,35.777c-102.917,3.899-125.172-88.539-81.979-175.921
 c71.457-144.56-162.979-48.431-225.951-44.29C-22.9,344.077,25.05,112.387,137.521,128.454z"/>
</svg>

Comment: Thank you so much enxaneta! This is exactly I was looking for :D
Comment: First: Thank you for your quick answer! Can you explain to my why a checkbox is necessary? I tried to add a class to the path but the animation won't start. In your example it works pretty fine with a checkbox but i'd like to avoid this if possible. Also: is ist possible that the stroke is already visible at the beginning at that each click start the same animation (in your example the stroke changes the directions with every click (first: counterclockwise, then: clockwise))
Comment: @jessy20 : I've updated my answer. Please take a look


Regression for categorical independent variables and a continuous dependent one

Question: I just realized I have always worked regression problem where the independent variables were always numerical. Can I use linear regression in the case where all independent variables are categorical?
Answer: Just some semantics and to be clear:

dependent variable == outcome == "$y$" in regression formulas such as
$y = β_0 + β_1x_1 + β_2x_2 + ... + β_kx_k$
independent variable == predictor == one of "$x_k$" in regression
formulas such as $y = β_0 + β_1x_1 + β_2x_2 + ... + β_kx_k$

So in most situations the type of regression is dependend on the type of dependent, outcome or "$y$"  variable. For example, linear regression is used when the dependent variable is continuous, logistic regression when the dependent is categorical with 2 categories, and multinomi(n)al regression when the dependent is categorical with more than 2 categories. The predictors can be anything (nominal or ordinal categorical, or continuous, or a mix).
(The remark below might be redundant for you, but I add it anyway)
However, do note that most software requires you to recode categorical predictors to a binary numeric system. This just means coding sex to 0 for females and 1 for males or vice versa. For categorical variables with more than 2 levels you'll need to recode these into $L-1$ dummy variables where $L$ is the number of levels and these dummies contain a 0 or 1 when they are in the corresponding category. This way each individual (sample) should be represented by having a 1 for the dummy variable he/she is part of and a 0 for the others, or a 0 for all dummies when he/she is part of the reference group.
Comment: I see you have edited the question to add a second question, and posted a similar quesiton here: http://stats.stackexchange.com/questions/267137/achieve-continuous-predictions-in-linear-regression-with-all-categorical-indepen . Additionally, I'd ask you what you mean by smoothing your predictions, or what you mean by predicting discrete values. AFAIK a linear regression will give you the mean value of the continuous dependent based on your predictor variables (through the regression formula). Please elaborate
Comment: thanks. as I write in the question title, the dependent variable is continuous. So I take your answer as "you can use linear regression, provided you do dummy encoding". Please correct me if I am wrong.
Comment: I deleted the second question as you fully answered the original one. To answer your question, if I feed $n$ new "events" ($x_i$) to the model, I would get $n$ different $y$ values that would all take one of four regressed values. I guess I am saying that if the categorical variables were actually ordinal, I would like to introduce some (logit?) smoothing between values.
Comment: In the case of an ordinal variable one can always chose to assume it is "continuous enough" to use it as if it were a continuous predictor (by simply not using dummies, but entering the variable as a numerical version). However, **if you do this** and you have only few levels, you are fitting a straight line (thus assuming linearity) through only a few points (so note that the amount of levels is important here). A Likert scale is a good example of a variable used this way, which regrettably creates problems on various occasions.
Comment: yes that is what I was saying.
Comment: Thanks! This is brilliant. However, I am still puzzled that in this case the values I would predict are discrete, while my dependent variable is actually continuous. Is there any way to "smooth" my predictions?
Comment: What purpose is the 'smoothing' for? Just for visually trying to interpret the output as a (continuous) curve? If there are K input binary categoricals, there will only be 2^K discrete output points. Likewise if they were ordinals, you would multiply together the number of levels.
Comment: @IWS What happens if I have an independent variable that is categorical with which the dependent variable does not vary monotonically. For example,  to predict the price of a toy, one of the features is colour (which can take the values blue, red or yellow). If blue=0, red = 1 and yellow =2, but price of a blue toy is higher than that of an equivalent red toy and price of a yellow toy is higher than that of an equivalent blue (and red toy). Can I still use colour as a feature?


Format time algorithm

Question: I am really struggling to solve human readable duration format algorithm. I have solved the most of it, but there are some mistakes anyway which I cannot solve for a while. Some tests pass, while others don't. Please help me it solve it.
The code
function formatDuration (seconds) {
  // Complete this function
  var minutes = Math.round(seconds / 60);
  var thisSeconds = Math.round(seconds % 60);
  var hours = Math.round(seconds / 3600);
  var days = Math.round(seconds / 86400);
  var years = Math.round(seconds / 31536000);

  var stringYear = "year";
  var stringDay = "day";
  var stringHour = "hour";
  var stringMinute = "minute";
  var stringSecond = "second";

  if (years > 1) {
    stringYear = "years";
  } else if (days > 1) {
    stringDay = "days";
  } else if (hours > 1) {
    stringHour = "hours";
  } else if (thisSeconds > 1) {
    stringSecond = "seconds";
  } else if (minutes > 1) {
    stringMinute = "minutes";
  }

  if (minutes >= 60) {
    hours = Math.round(minutes/60);
    minutes = Math.abs(minutes - hours*60);

    if (minutes > 1) {
      stringMinute = "minutes";
    }
  }

  if (hours >= 24) {
    days = Math.round(hours/24);
    if (days > 1) {
      stringDay = "days";
    }
    hours = hours - days*24;
    stringHour = "hours";
  }

  if (days > 365) {
    days = Math.abs(days - years*365);
    stringDay = "days";
  }

  var obj = new Map();
  obj.set(stringYear, years);
  obj.set(stringDay, days);
  obj.set(stringHour, hours);
  obj.set(stringMinute, minutes);
  obj.set(stringSecond, thisSeconds);

  var empArr = [];

  obj.forEach(function (value, key, mapObj) {

    if (value == 0) {
      obj.delete(key);
    }

    var res = value + " " + key;

    if (value > 0) {

      empArr.push(res);

      formatStrings(empArr);

    }

  });

  return formatStrings(empArr);

}

function formatStrings(arr) {
    return arr.length == 1 ? arr[0] : arr.slice(0, arr.length - 1).join(", ") + " and " + arr[arr.length - 1];
    //console.log(str);
}

formatDuration(3600);

Test results
Comment: What are the inputs you're getting that are failing? What are the inputs that are working?
Comment: You should use Math.floor instead of Math.round, because otherwise "118" will become 2 mins 58 seconds instead of 1 min 58 seconds
Comment: I do not know they do not provide that.
Comment: Thank you, James you are so helpful. It works now. However, I do not know why second does not change to seconds when there are more than one seconds.
Comment: You have a big if/else if block.  That's not going to work if years > 1 *and* seconds > 1 (it will just perform the first matching condition's code)  You need a bunch of independent ifs.
Comment: But how they are related to each other, they are different variables?!
Answer: Math.round performs rounding (rounding up if the value would be above .5).
use Math.floor everywhere to take the truncated part.
I would also use modulo to avoid all the complicated logic you've added.
So
var minutes = Math.round(seconds / 60);

would become
var minutes = Math.floor(seconds / 60) % 60;

and so on.

Format time algorithm


Boostrap Responsive Menu Not Working

Question: I'm having an issue with my menu on the responsive size. For some reason my menu doesn't collapse so I cannot see any of my items on my menu on a tablet or a mobile. Using the inspect element I check and all the pages from my menu are in the html but the collapsing part is not working anymore. I'm currently using the Project Bootstrap .
Can anyone provide me some tips on how to troubleshoot this problem?
Any help will be appreciated.
Comment: Upgrade you jQuery to 1.9+ as the documentation at Project Bootstrap requires. It is at 1.7.1 currently.
Comment: @J.Reynolds Using the Jquery_update module I change my Jquery version to 1.10 and this still not working. Also, I clear caches and still not working.
Answer: Taking a look at the HTML on your homepage there, I'm seeing you're loading bootstrap in your  section, and then calling jQuery from near the footer, way down on line 223 (that'd be the line . That's why I'm at least seeing the error Uncaught Error: Bootstrap requires jQuery.  You want to load jQuery before you load Bootstrap, so ultimately your  should include the two lines:

I hope this at least gets you closer.
Comment: Yes, that is the problem. Good spotting. Though as he is using Bootstrap 3 he needs at least jQuery 1.9+ as well.
Comment: Thank you so much guys. I was using the advagg module and this change the Jquery_Update to 1.7. I'm not currently using this module so I remove it and the menu is working properly. Thank you guys.

Boostrap Responsive Menu Not Working


Pesquisa de string com caracter "|"

Question: Preciso realizar uma consulta em um arquivo txt no Python, porém estou com 2 problemas devido a interpretação de caracteres especiais.
Quando insiro | ou \ o resultado acaba sendo substituido: o | é interpertado como espaço em branco e \ é duplicado (\\).
import re

erro = r"FIM|2|"
linha = 'ahsuasaudsdad '

if re.search(erro, linha):
   print('Não deveria cair aqui')
   print(re.findall(erro, linha))

Neste caso eu faço a pesquisa da string FIM|2| dentro de um arquivo, porém de qualquer forma ele retorna true no if sendo que minha intenção é que retorne true apenas se a string conter FIM|2|.
Comment: `|` é um operador de `OU`, tente alterar para `FIM\|2\|`. Ou seja, deste modo `FIM|2|` você está procurando por FIM ou 2 ou nada. Veja [a demo](https://regex101.com/r/eMBgOU/1)
Comment: Era isso mesmo, muito obrigado !
Comment: Eu não tinha aceito ainda porque só posso aceitar 10 min depois dele ter respondido, eu já iria aceitar, obrigado!
Answer: O problema é que o caractere | é reservado na expressão regular. O que está acontecendo que é que você está buscando a palavra "FIM" ou o número "2" ou vazio. O vazio sempre será encontrado.
Para resolver o problema, você precisa escapar o caractere:
import re

erro = r"FIM\|2\|"
linha = 'ahsuasaudsdad '

if re.search(erro, linha):
   print('Não deveria cair aqui')
   print(re.findall(erro, linha))
else:
    print('Funcionou :D')

Comment: Obrigado, deu certo !

Pesquisa de string com caracter "|"


Auto-assemble RAID1 Array with mdadm on CentOS 7.6

Question: I'm new to this particular area of the Stack Exchange network so please be kind. We are experiencing issues with auto-assembling a RAID1 Array created with mdadm on CentOS 7.6, and no matter what we try, the array is either non-existent after reboot or the system has to be put into recovery mode to undo the changes. Prior to the first reboot though, the array worked beasutifully and we were able to create a physical volume on it with pvcreate, along with a volume group for SolusVM use. All the articles I'm finding myself on Google that pertain to this scenario seem to deal with Ubuntu or other Debian-type distros which is really frustrating also.
So what have we tried so far? We've tried adding rd.md.uuid= (with the UUID of the RAID array gathered from /etc/mdadm.conf) to GRUB_CMDLINE_LINUX of /etc/default/grub and then running the following commands:

dracut -a mdraid -f
grub2-mkconfig -o "$(readlink -e /etc/grub2.cfg)"

That resulted in the system not booting up and we had to go into recovery mode temporarily afterwards. We then tried variations of those commands with no luck, with the system booting up successfully some of the time but with no luck on mdadm auto-assembling the array at any point. We tried just running the following commands, separately, on their own without any luck:

dracut -a mdraid -f
dracut -f

We'd sincerely appreciate any help on this issue as the help we are finding via Google is not assisting in any manner, we are essentially going into this blind. Thank you and we look forward to your replies.
EDIT: I was told to give the output of mdadm --examine and cat /proc/mdstat so I went to assemble the array manually and the following output was given:
[root@omega phobosdthorga]# mdadm --assemble /dev/md0 /dev/nvme0n1 /dev/nvme1n1
\mdadm: Cannot assemble mbr metadata on /dev/nvme0n1
mdadm: /dev/nvme0n1 has no superblock - assembly aborted
[root@omega phobosdthorga]#

I followed the following guide for creating the array: https://www.tecmint.com/create-raid1-in-linux/
I suppose I have to find where I went wrong originally and try to fix that also, but I'd still like some advice on how I can auto-assemble the array afterwards, please.
Comment: The first thing you need to do is to investigate why the RAID array does not assemble. You did not post anything about this, but it is the most important thing you should have done. Please edit your question to show the status of your RAID arrays, e.g. the outputs of `mdadm --examine` or `cat /proc/mdstat` and any additional information you developed.
Comment: Thanks, Michael, I made some edits and hopefully they shed further light on where I'm stuck with this. Much appreciated.
Comment: What about `cat /proc/mdstat`?
Comment: One obvious, but kind of facepalm situation, is if you did something that blew away the array metadata.  Like, did you do pvcreate on /dev/nvme0n1 instead of /dev/md0?  Another less common situation is if you created the array using external metadata such as IMSM or DDF - sometimes these are written to the end of the device, rather than the beginning, and can inadvertently be destroyed.
Answer: Okay! I fixed the issue thanks to the suggestion of an article in the right sidebar :) What changed is that I created the RAID1 array using mdadm as normal but instead did the following:

Firstly run mdadm --stop /dev/md0 after the array had finished building.
Then perform mdadm --assemble /dev/md0 --update=homehost.

I then next followed what I did as per in my original question which was to:

Do all that was needed regarding rd.md.uuid with grub2.
Execute dracut -a mdraid -f afterwards.
Then lastly perform the grub2-mkconfig -o "$(readlink -e /etc/grub2.cfg)" command.

So yeah, the array auto-assembles on boot now! Thank you for your time and assistance, Michael and Mike.


Downtime-tolerant Linux scheduler with to-the-minute accuracy

Question: I have a server that I want to be able to schedule jobs on, and I need to be able to specify when those jobs happen to the minute. There will be a lot of jobs. (Things like sending e-mail notifications to clients).
This sounds like the perfect job for cron, however, I need to be able to handle downtime. In the event of downtime, I can't wait till anacron runs at the end of the day to reconcile all the missed tasks.
If I have a bit of downtime, I need all the overdue tasks to be run at boot.
For example:

Task is scheduled for 17:36
Machine is shut down at 17:33
Machine is booted at 17:40
Task is now overdue, and should be run as soon as possible.

Is there a way to change anacron into something that runs at boot and runs all the overdue cron jobs?
Or, is there some other common solution to this problem?
Answer: cron/anacron are not built with fault-tolerant or highly available scenarios. If your jobs are very critical I think Jobscheduler http://www.sos-berlin.com/jobscheduler-features will be beneficial for you. Just a headsup , its not easy to setup and will take a little time to get acquainted, but it is the best tool for scheduling
Answer: Any of the work queue systems out there should be able to do it.  Celery, Resque, Sidekiq, backgroundjob, etc etc etc.  Some of them have it built-in, others have a plugin that adds chronological dispatch.


incompatible types: Icon cannot be converted to int

Question: I'm trying to create a dynamic Icon for my notifications using a function that creates a Bitmap from a String.
When I started my project, I wanted to use API level 22, but I realized that public Notification.Builder setSmallIcon (Icon icon) was not available until API 23.
So I changed my MinSDKVersion, but i'm still getting that incompatible types error ...
package com.example.netmetah;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import android.app.Notification.Builder;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class NetMonitorService extends IntentService {

    public NetMonitorService() {
        super("NetMeterListening");
    }

    @Override
    protected void onHandleIntent(Intent workIntent) {
        Context context = getApplicationContext();
        CharSequence text = "Le service marche";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
        createNotification(createBitmapFromString("23","kb"));
    }

    private Bitmap createBitmapFromString(String speed, String units) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(55);
        paint.setTextAlign(Paint.Align.CENTER);

        Paint unitsPaint = new Paint();
        unitsPaint.setAntiAlias(true);
        unitsPaint.setTextSize(40);
        unitsPaint.setTextAlign(Paint.Align.CENTER);

        Rect textBounds = new Rect();
        paint.getTextBounds(speed, 0, speed.length(), textBounds);

        Rect unitsTextBounds = new Rect();
        unitsPaint.getTextBounds(units, 0, units.length(), unitsTextBounds);

        int width = (textBounds.width() > unitsTextBounds.width()) ? textBounds.width() : unitsTextBounds.width();

        Bitmap bitmap = Bitmap.createBitmap(width + 10, 90,
                Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        canvas.drawText(speed, width / 2 + 5, 50, paint);
        canvas.drawText(units, width / 2, 90, unitsPaint);

        return bitmap;
    }

    public static long[] readProc() {
        BufferedReader br;
        String line;
        String[] lines;
        long rx = 0;
        long tx = 0;
        try {
            br = new BufferedReader(new FileReader("/proc/net/dev"));
            while ((line = br.readLine()) != null) {
                if (line.contains("eth") || line.contains("wlan")) {
                    lines = line.trim().split("\\s+");
                    rx += Long.parseLong(lines[1]);
                    tx += Long.parseLong(lines[9]);
                }
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long[] bytes = {rx, tx};
        return bytes;
    }

    private void createNotification(Bitmap icon) {
        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        notificationIntent.setData(Uri.parse("http://www.google.ca"));
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, "fuck")
                .setCategory(Notification.CATEGORY_PROMO)
                .setSmallIcon(Icon.createWithBitmap(icon))
                .setContentTitle("C'est quoi un titre")
                .setContentText("C'est quoi un text")
                .setAutoCancel(true)
                .setVisibility(1) //Public
                .addAction(android.R.drawable.ic_menu_view, "View details", contentIntent)
                .setContentIntent(contentIntent)
                .setPriority(Notification.PRIORITY_HIGH)
                .setChannelId("fuck")
                .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}).build();
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(123, notification);

    }
}

Comment: possible duplicate of - https://stackoverflow.com/questions/16055073/set-drawable-or-bitmap-as-icon-in-notification-in-android/16055373#16055373
Comment: No it doesn't answer my question, In fact, I was originally using this post as a guideline to make this work
Comment: So in your code, are you showing icon in bitmap form, is that icon coming from server?
Comment: I'm generating it from a String using ** private Bitmap createBitmapFromString(String speed, String units)**

The created Bitmap works with setLargeIcon() but not with setSmallIcon()
It's like I was still on API 22, I can't use the "new" overloaded function from NotificationCompat.Builder
Comment: In the developer blog, in Notification section , it has mention if you want to use setSmallIcon() for that you need to pass R.drawable.image , because it exist in your package, so  what is the problem having with large icon?
Comment: As I said, I don't have any problem with setLargeIcon()
The doc says that I can provide a Icon object for setSmallIcon() instead
[link]https://developer.android.com/reference/android/app/Notification.Builder.html#setSmallIcon(android.graphics.drawable.Icon)[/link]

**public Notification.Builder setSmallIcon (Icon icon)**
Comment: I am also looking for your solution, if i get i will tell :)
Answer: You are using NotificationCompat.Builder. According to the documentation the setSmallIcon methods take a drawable resource ID.
It's easy to confuse this with the methods for Notification.Builder where one takes a drawable resource ID and the other one an Icon.
Comment: Thank you that was exactly what I was looking for :)


Unpacking a typelist

Question: Lets say I have a function that takes just a type template parameter, I cannot change it's definition/implementation.
template < typename T >
void do_it();

Now I have a typelist defined a usual way, can't change it either:
template< typename ...Ts >
struct typelist;

I want to implement a function that takes a typelist, and runs do_it() on every type:
template< typename List >
void do_them();

The only solution I found up 'till now is:
template< typename T >
void do_them_impl()
{
   do_it<T>();
}

template< typename T, typename Ts...>
void do_them_impl()
{
   do_it<T>();
   do_them_impl<Ts...>();
}

template< template < typename...> class List, typename ...Ts >
void do_them_extract( List<Ts...>&& )
{
    do_them_impl< Ts >();
}

template< typename List >
void do_them()
{
    do_them_impl( List{} );
}

But that requires 4(!) functions for each case I want to create a single do_them function. I will require quite a few of those, and I don't want to write a quad of functions for each. Am I missing something?
C++14 welcome, C++17 solutions too, but marked as such.
Answer: In C++14 you can use some awful tricks to introduce a valid pack expansion context:
template< template < typename...> class List, typename ...Ts >
void do_them_impl( List<Ts...>&& )
{
    (void)std::initializer_list<int> {
        (do_it<Ts>(), 0)...
    };
}

template< typename List >
void do_them()
{
    do_them_impl( List{} );
}

This allows you to avoid recursive template instantiation, which is generally more expensive.
Live Demo

In C++17 you can use fold expressions:
template< template < typename...> class List, typename ...Ts >
void do_them_impl( List<Ts...>&& )
{
    (do_it<Ts>(), ...);
}

template< typename List >
void do_them()
{
    do_them_impl( List{} );
}

Live Demo
Comment: @KornelKisielewicz yeah, you can use an array of integers or something like that: `int _[] = { 0, (do_it(), 0)... };`. The first 0 is there to avoid 0 sized arrays, that are not valid in C++.
Comment: @KornelKisielewicz I won't add another answer for that. It would worth to update this one and add the example with the array.
Comment: That was fast! C++14 - Is there a possibility to avoid std::initializer_list? (I'm coding without STL, various reasons). C++17 version - god, I cannot wait for this to be supported in Visual Studio -_-
Comment: I'll leave this question open for 24h, and if nothing ingenious pops up, I'll accept this one -- saved me 2 functions (I can live with changing void do_them() to void do_them( typelist&& ) )
Comment: @KornelKisielewicz is something like [this](http://melpon.org/wandbox/permlink/WahiJACV78G8NGj2) what you are looking for?
Comment: Don't want to use a struct because in fact it's a method, struct in class with `this` passing looks really messy.
Answer: Here is a solution that takes advantage of C++14's generic lambdas:
template <typename T>
struct type_ { using type = T; };

template <typename Type>
using type = typename Type::type;

template <typename List>
struct map_;

template <template <typename...> typename Container, typename... Ts>
struct map_<Container<Ts...>>
{
    template <typename Fun>
        void operator()(Fun&& fun)
        {
            (void)((int[sizeof...(Ts)]){(fun(type_<Ts>{}), 0)...});
        }
};

template <typename List>
auto map = map_<List>{};

Then for each function
#include <iostream>
#include <cxxabi.h>
#include <typeinfo>

template <typename T>
const char * type_name()
{
        return abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, nullptr);
}

template <typename T>
void do_it()
{
    std::cout << type_name<T>() << std::endl;
}

you can write:
template <typename List>
void do_them()
{
    map<List>([](auto v){ do_it<type<decltype(v)>>(); });
}

template <typename... Ts>
struct typelist {};

int main()
{
    do_them<typelist<int, char, bool>>();
    return 0;
}

Compiling with -O3 gives the same assembly as if we simply called do_it<int>, do_it<char>, do_it<bool> in succession.

Unpacking a typelist


About balanced and complete binary tree

Question: I found this and I just couldn't verify it. How come it is true?
The maximum number of nodes that a balanced binary tree with depth $d$ is a complete binary tree with $2^d-1$ nodes.
Let say I have the following tree
<code>   1
  / \
 2   3
</code>
The tree is balanced as well as a complete binary tree. The depth of the tree is 1. So according to the formula the max number of nodes should have been
2^1-1 =1 which is not but 3 in this case.
How come the statement
The maximum number of nodes that a balanced binary tree with depth d is a complete binary tree with 2d−1 nodes
correct then. Can anyone please clarify?
Answer: Maybe this diagram will be clearer. It shows the full balanced binary trees of depths 1, 2, 3, and 4.  The tree of depth 0 has no nodes at all.

The first tree has 1 node. The tree with depth 2 has twice as many (in green and blue) plus a root node (in red), which makes $2\cdot1+1 = 3$.
The tree with depth 3 has twice as many again (in green and in blue) plus a root node (in red), which makes $2\cdot3+1 = 7$.
The tree with depth 4 has twice as many again (in green and in blue) plus a root node (in red), which makes $2\cdot7+1 = 15$.
There are two things to know about this. First, if $M(d)$ is the number of nodes in the full binary tree of depth $d$, then $M(d+1) = 2M(d) + 1$.  You can see that from the diagram, since a tree of depth $d+1$ consists of two copies of the tree of depth $d$ (one in green and one in blue) plus a root node (in red). Each tree has the same kind of structure:

The second thing to know is that $M(d) = 2^d-1$ for all $d$. I will show that now.
I claim that the number of nodes in the tree of depth $d$ is always $2^d-1$. Suppose this was wrong, that there were some tree with some other number of nodes.  Then among all such trees, there must be one with the smallest possible depth.  Let's say that the smallest tree for which the claim fails has depth $m$.
Now evidently $m>1$, because you can see from the diagram that the claim is true for trees of depth 1. But a tree of depth $m>1$ is made of two smaller trees of depth $m-1$ (one in green, and one in blue) plus one root node (in red).
We said that the depth-$m$ tree is the smallest one for which the claim fails.  So the claim is true for the smaller trees of depth $m-1$: they have $2^{m-1}-1$ nodes each.  Then the depth $m$ tree has $2^{m-1}-1$ green nodes, $2^{m-1}-1$ blue nodes, and one red node, for a total of $\color{green}{2^{m-1} - 1} + \color{blue}{2^{m-1} - 1} + \color{red}{1}$. This adds up to $2\cdot2^{m-1} - 2 + 1 = 2^m - 1$, so the claim is true for our tree of depth $m$ also.  This contradicts our assumption that there was a tree for which the claim was false, so our assumption must be wrong, and so there is no such tree and there is no such $m$.
Comment: You said "You can see that from the diagram, since a tree of depth d+1 consists of two copies of the tree of depth d (one in green and one in blue) plus a root node (in red). Each tree has the same kind of structure:" Can you show it pictorially with a dashed line or something . I am having trouble follwing this premise..
Comment: I showed it pictorially by putting the two copies of the smaller tree in green and in blue, and the root node in red.
Comment: you mean the second picture in your post ?
Comment: Both pictures in the post.
Answer: Say $M(d)$ is the maximum number of nodes in a tree of depth $d$.  This tree
has a root node, a left subtree of depth at most $d-1$, and a right subtree of depth at most $d-1$.
If you want the tree to have the maximum number of nodes, then the left and right subtrees must individually have the maximum possible number of nodes, namely $M(d-1)$.  So we have: $$ \begin{eqnarray}M(d) & = & 1 + M(d-1) + M(d-1) \\ & = & 2M(d-1) + 1\end{eqnarray}$$
and clearly $M(0)=0$. The function $M(d) = 2^d-1$ satisfies both those conditions, so that's the answer.
Comment: I didn't get it, could please explain with an example, possibly with a tree

About balanced and complete binary tree


The absolute div won't scroll it is still static

Question: I am trying to place a box along side each image on my webpage that will scroll down with the page but only inside the confines of the post/image, like can be found at memecenter, but i am having some difficulties.
I have set the parent div (post) to position relative and the child div (scrolling box) to position absolute, and they are nested within each other in the html but the child div wont scroll it still stays static on the page.
See code here:
.parent {
position: relative;
width: 613px;
overflow: hidden;
padding: 10px 0;
border-bottom: 1px solid #dddddd;
}
.child {
    position: absolute;
    width: 46px;
    height: 100px;
    float: right;
    margin-right: 20px;
}

and html:

Answer: Css :
    .parent
    {
        background-color:Blue;
        position:fixed;
        width: 150px;
        height:200px;
        overflow: hidden;
        padding: 10px 0;
        border-bottom: 1px solid #dddddd;
        overflow:hidden;
    }
    .child {
        background-color:red;
        position: absolute;
        width: 460px;
        height: 220px;
        float: right;
        margin-left:150px;
        overflow:scroll;

    }

and html:

Please find a working fiddle.
http://jsfiddle.net/Victor_AJ/8GS7b/13/
Comment: i have been trying to find a working fiddle all day and have gotten nowhere.
Comment: It is working fine in the above mentioned fiddle.  http://jsfiddle.net/Victor_AJ/8GS7b/13/
Comment: It still is staying static for me in the fiddle, even if i change the length to a long way down it still wont scroll down the side along the length. Im not wanting the parent div to be fixed, only the child div see this fiddle.... http://jsfiddle.net/8GS7b/23/
Comment: Bump ... I think everyone is misunderstanding the question because none of these fiddles are showing me anything at all. none of the boxes are floating and scrolling with the page. all im after is something that is fixed but within a boundary and not the page itself. If this is only possible with javascript, can someone please provide me with a js edit i can try out?
Answer: You can use "top" and "left" values.
Css Part:
.parent {
    position.parent {
    position: relative;
    width: 613px;
    overflow: hidden;
    padding: 10px 0;
    border-bottom: 1px solid #dddddd;
    }

.child {
    position: absolute;
    left: 100px;
    top: 10px;
    width: 46px;
    height: 100px;
    float: right;
    margin-right: 20px;
    float: left;
}:

Html part:

This is image description

Comment: i tried this but it the box still stays static and wont scroll with the page like the example website.
Answer: CSS :
   .parent {
        background-color:Blue;
        position:fixed;
        width: 70%;
        height:100%;
        overflow: hidden;
        padding: 10px 0;
        border-bottom: 1px solid #dddddd;
        overflow-y:scroll;
        overflow-x:hidden;
    }
    .child {
        background-color:Grey;
        position: absolute;
        width: 30%;
        height:100%;
        float: right;
        margin-left:70%;
        overflow:hidden;
     }

 And Html :

Find a Fiddle Here Working EX


Is it possible to make a SPARQL query over parsed triples in ARC2?

Question: The ARC2 documentation is not really precise. It gives the two following examples:
First, parsing an RDF file:
$parser = ARC2::getRDFParser();
$parser->parse('http://example.com/foaf.ttl');
$triples = $parser->getTriples();

Second, making a SPARQL query on a datastore:
$q = 'SELECT ...';
$rows = $store->query($q, 'rows');

…but would it be possible to make a SPARQL query over the parsed $triples directly?
Answer: ARC2 doesn't have an in-memory SPARQL processor, I'm afraid. The SPARQL engine is based on rewriting the query to SQL statements, which is why you need the Store component to run queries.
All you can do to make it a bit more smooth is to skip the parsing step and do a $store->query('LOAD <URL>') to directly import the triples into the store, but you still need the MySQL-backed store, unfortunately.
Comment: Wow, I'm honored Mr. Nowack created an account on StackOverflow to answer this question! I guess your status of ARC2 core developer makes your answer authoritative on the question ;) Also, thanks for having seen the unwritten question: yes, the MySQL store is mandatory. I'll add this to the wiki whenever I get some time.


R-squared as sample size increases

Question: How do I prove that $R^2=1-\frac{SSR/n}{SST/n}$ converges towards $\rho^2=1-\frac{\sigma^2_u}{\sigma^2_y}$ as $n \rightarrow\infty$,
where $\sigma^2_u=\operatorname{Var}(u)$ and $\sigma^2_y=\operatorname{Var}(y)$?
I have got the following:
$R^2=1-\frac{\frac{1}{n}\sum{\hat{u^2_i}}}{\frac{1}{n}\sum{(y_i-\bar{y})^2}}$ and $\rho^2=1-\frac{\frac{1}{n}\sum{(u_i-\bar{u})^2}}{\frac{1}{n}\sum{(y_i-\bar{y})^2}}$
Comment: Welcome to Cross Validated! What are you struggling to prove, that $\dfrac{SSR/n}{SST/n}$ converges to $\dfrac{\sigma^2_u}{\sigma^2_y}$ or that $\rho^2 = 1 - \dfrac{\sigma^2_u}{\sigma^2_y}?$
Comment: Hi, it is the former that I'm trying to prove
Comment: What progress have you made so far? While this Stack does accept [tag:self-study] questions like homework problems, the way we handle them differs from how we handle other questions
Comment: Hint:  What are the definitions of SSR and SST?
Comment: I have edited the post above with what progress I have made
Answer: May be this can help https://en.wikipedia.org/wiki/Ratio_distribution
Look at the section Moments of random ratios.
A key aspect is for  SST and SSR to be independent.
Comment: Please add further details to expand on your answer, such as working code or documentation citations.

R-squared as sample size increases


Aplicações silenciosas

Question: Algumas aplicações ou boa parte delas tem uma opção de instalação "não assistida" ou silenciosa, conhecido como silent install, que é fazer a instalação de uma aplicação sem que o usuário ou equipe de suporte precise interagir com essa aplicação em sua instalação.
Comecei a trabalhar numa aplicação terceira, no qual possui a seguinte permissão relacionada:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />

Por padrão o Eclipse emite o seguinte erro:
Permission is only granted to system apps.

O que deve ser considerado na hora da criação de uma aplicação silenciosa para Android fora do Google Play Store? Porque acontece esse tipo de erro?
Comment: Pela mensagem, parece que só funcionará se o app tiver permissões de root no sistema, o que pra grande parte dos usuários não ocorrerá. Em alguns apps que necessitam disso, geralmente eles emitem um alerta orientando a gente mesmo a "permitir fontes desconhecidas", e depois fazer a instalação.
Comment: @diegofm obrigado pelo comentário. Me esclareceu algumas coisas que ainda não tinha entendido.
Answer: O erro informa que essa permissão só pode ser obtida por aplicações do sistema.
Para isso a aplicação terá de existir na "Android ROM" e ser assinada com a mesma key, ou então, num rooted device instalada em /system/app(/system/priv-app API4.4+)fonte
Para que o Eclipse deixe de emitir esse erro siga os seguintes passosfonte:

Window -> Preferences -> Android -> Lint Error Checking

Procure por ID = ProtectedPermission na lista e defina Severity para algo que não error
Se o que pretende é instalar a aplicação fora da Google Play Store, não necessita da permissão android.permission.INSTALL_PACKAGES, basta o dispositivo, onde vai ser instalada, ser configurado para "permitir fontes desconhecidas".
A permissão android.permission.INSTALL_PACKAGES é necessária para aplicações que façam a instalação de outras aplicações.
Comment: Como fazer com que **não apareça** o erro eu já tinha pesquisado e entendido. A questão era saber o porque do erro. Eu pesquisei para entender um pouco mais e consegui compreender porque e como exatamente é usado.
Comment: E esse porquê não é o que está nos 2 primeiros parágrafos da resposta?
Comment: Bom, dei uma atenção na resposta do @diegofm publicada como comentário da pergunta e fui um pouco a fundo. Realmente se a aplicação não tiver a "permissão fontes desconhecidas" e sucessivamente eu não inserir `android.permission.INSTALL_PACKAGES` no `manifest.xml`, a aplicação não será instalada. Para que o _app_, usando _silent install_ ,  funcione corretamente, é necessário ignorar o "erro" fazendo exatamente o que você disse a partir do terceiro parágrafo da sua resposta, que é o que eu já faço atualmente.
Comment: Eu só queria entender um pouco o conceito do [INSTALL_PACKAGES](https://developer.android.com/reference/android/Manifest.permission.html#INSTALL_PACKAGES)
Comment: Não entendi. Você está a dizer que consegue instalar essa aplicação num dispositivo que não seja *rooted* e que usa ela para instalar outras apps?
Comment: Estou a dizer que não precisa estar _rooted_ para instalar uma aplicação que não esteja no Google Play, basta usar `android.permission.INSTALL_PACKAGES` . Estou certo?!
Comment: Não, se é só para isso não necessita da permissão `android.permission.INSTALL_PACKAGES`, basta que seja indicado no dispositivo para "permitir fontes desconhecidas"
Comment: Enfim, agora estou mais esclarecido sobre o assunto. Abraços. Obrigado!
Answer:
No Eclipse:
Window -> Preferences -> Android -> Lint Error Checking.

Na lista encontre uma entrada com o id Permissão protegido. Defina a gravidade para algo mais recente do que erro. Desta forma, você ainda pode compilar o projeto usando Eclipse.

No Android Studio
File -> Settings -> Editor -> Inspections

Abaixo da opção Android Lint, localize Using system app permission. Desmarque a caixa de seleção ou escolha uma gravidade menor do que esse erro.
Fonte: https://stackoverflow.com/a/13802178/6362228

Aplicações silenciosas


Factor analysis to group questions into blocks?

Question: So we have a questionaire of 32 questions (answer 1-7 on each question) where we present the results in grouped in four areas (Question 1-8 in one, 9-16 etc), since we think that those questions belong together.
We are now trying to find out of these grouping are correct or if maybe some should switch between groups (say: question 12 should be in group 4 instead of 2).
And on the other hand: If 4 groups aren't correct and we should use 3 or 5 instead?
Can we use factor analysis for that? I have a feeling that is more used to answer the question: Can we replace our 32 questions with less and still get a good answer if I have understood it correctly.
Comment: It sounds like you seek for something like clustering questions (variables). Maybe. You ought to clarify what is questions "belong together", anyway.
Comment: With "belonging together" I mean that for example question 1-8 is about leadership, 9-16 about attractivness etc.
Answer: Actually, you CAN use factor analysis to answer your question, but it's not quite so straightforward. Basically, there are two kinds of factor analysis: exploratory factor analysis (EFA) or confirmatory factory analysis (CFA). Exploratory factor analysis is used as you might expect - to identify which questions might be redundant and can be removed, and how the questions group together into an underlying structure. Confirmatory factor analysis is used to test whether the data gathered fits to an existing model.
When you say that you "think" the questions group together, it looks like you mean that they have some theoretical connection to each other. Remember, though, that factor analysis will simply look at how to explain variance in the responses, and so your theoretical factors might not line up at all with the actual factors in your study.
Generally, people field a larger survey of questions developed through a robust process, and use exploratory factor analysis to examine the latent structure of the instrument. Confirmatory factor analysis is more useful when prior EFAs have been done on an instrument - for instance, if we are checking how an instrument fares in a different population.
So, I would recommend doing some EFA work on your responses to see how things group. It might be that your four sections are about different things, but that the underlying factor structure cuts across your explicit domains. But since you don't really have an existing model (beyond "these questions go together"), CFA isn't really a good fit for your project.
Comment: (+1) I'll add that in the often subjective and iterative process that is EFA, you may be able to determine 1. which variables belong on the questionnaire at all,  2. which ones belong together as part of certain factor scores, 3. how many such factors should be considered to exist, and 4. (your last point) to what extent factor scores can serve as stand-ins for larger sets of scores from individual items.  Good luck!
Comment: @rolando2 Excellent points all around (+1).


Measures on manifolds and zero measure sets

Question: On a differentiable manifold $M$ there is a standard notion of zero measure sets using charts ( a set $A\subseteq M$ has zero measure if for every chart $(U,\varphi)$ $\varphi(A\cap U)$ has zero Lebesgue measure in $\mathbb{R}^n$)
Moreover if we have a volume form $\Omega$ on $M$, by the Riesz-Kakutani representation there is a unique Radon measure $\mu$ on the Borel $\sigma$-algebra on $M$ such that for all compactly supported continuous function on $M$ we have
\begin{equation*}
\int_M f \Omega=\int_M f \mu.
\end{equation*}
How can I prove that if A is a Borel set with zero measure in the chart definition then it is also $\mu(A)=0$?
Is this fact actually true? I think so but I haven't found any prof yet. I tried for example using regularity of $\mu$ and approximation of characteristic functions with bump functions...
Thank you in advance.
Comment: Yes, it's true; see [Measure of null (or full) subsets of manifolds and absolute continuity of smooth measures](https://math.stackexchange.com/a/4471836/568204). There I used a slightly different characterization/initial definition of the measures, but using Riesz's theorem you get the same measure so while you might have to slightly reword the argument provided there, the ideas are the same. The idea is (by second-countability) to reduce to the case where $A$ is contained in a single coordinate chart, and then use the definition of integrals of forms supported in a single chart.
Comment: Thanks for the answer. I'm struggling understanding the equality in (*). I agree on the fact that I can work locally in a chart but we have $\mu(A\cap U)=\int_U \chi_{A\cap U} d\mu$ and the characteristic functions isn't continuous so I can't translate that immediately in terms of volume form via  Riesz theorem
Comment: This is why I was talking about approximation of characteristic functions with smooth ones in my question.
Comment: yes that's what I meant by 'slightly reword the argument'... which after writing out is longer than I thought it would turn out:) But yes, in general you should expect some such approximation arguments (indicators should be approximated by continuous functions). I'll leave these more general arguments to you.
Answer: Here's the argument adapted to the Riesz definition of the measure. For each point $p\in A$, choose a positively oriented chart $(U_p,\alpha_p)$ such that $p\in U_p$ and $\Omega|_{U_p}=\Omega_{\alpha_p}\,dx_{\alpha_p}^1\wedge \cdots\wedge dx^n_{\alpha_p}$ for some smooth bounded positive function $\Omega_{\alpha_p}:U_p\to (0,\infty)$ (positivity is because of the positively-oriented chart, and boundedness can be assured by shrinking the set $U_p$ small enough). We can now extract a countably many such $U_p$ whose union covers $A$. Then, $\mu(A)\leq \sum\mu(U_p\cap A)$, the sum over countably many $U_p$'s. If we show each of the terms on the right vanishes, then $\mu(A)=0$.
Hence, we are now reduced to the following situation: there is a single chart $(U,\alpha)$ such that $A\subset U$, $\lambda_n(\alpha[A])=0$, $\Omega=\Omega_{\alpha}\,dx^1\wedge \cdots\wedge dx^n$ on $U$, and $\Omega_{\alpha}:U\to (0,\infty)$ is smooth, positive and bounded, say by a constant $B>0$. Now, by the regularity properties of $\mu$ (or really if you just look at the proof of Riesz's theorem), we have
\begin{align}
\mu(A)&=\inf_{\substack{\text{$V\subset U$ open}\\A\subset V}}\mu(V)=
\inf_{\substack{\text{$V\subset U$ open}\\A\subset V}}\sup_{f\prec V}\int_M f\Omega.
\end{align}
So we take infimum over all open sets $V\subset U$ which contain $A$, and the supremum of the integrals over all continuous $f$ with $0\leq f\leq 1$ and $\text{supp}(f)\subset V$. Now, why did I go through all the trouble with the charts? it is so that I can now evaluate the integral on the right in a very simple manner. Recall that integrals of compactly supported continuous $n$-forms is defined by a sum involving a partition of unity; but if we have the form supported inside of a single positively-oriented coordinate chart, then the integral simplifies the most obvious thing, i.e integrate the chart-representative function
\begin{align}
\int_Mf\Omega&=\int_{\alpha[U]}(f\cdot\Omega_{\alpha})\circ\alpha^{-1}\,d\lambda_n.
\end{align}
We now use the obvious estimate $f\leq \chi_V$ and $\Omega_{\alpha}\leq B$ to get
\begin{align}
\int_Mf\Omega\leq \int_{\alpha[U]}(\chi_V\circ \alpha^{-1})\cdot B\,d\lambda_n=B\int_{\alpha[V]}1\,d\lambda_n=B\cdot\lambda_n(\alpha[V]).
\end{align}
Therefore,
\begin{align}
\mu(A)&\leq \inf_{\substack{\text{$V\subset U$ open}\\A\subset V}}B\lambda_n(\alpha[V])=B\cdot\inf_{\text{$V'\subset \alpha[U]$ open}\\ \alpha[A]\subset V'}\lambda_n[V']=B\cdot \lambda_n(\alpha[A])=0.
\end{align}
The first equality is trivial, I'm just using the homeomorphism $\alpha$ to 'transfer' sets on the manifold to $\alpha[U]$. The second equality is because the $n$-dimensional Lebesgue measure is outer-regular, and the final equality is by hypothesis on $A$. Hence, $\mu(A)=0$. This completes the proof.
Comment: Thank you so much! When I have some time in the next days i will go through the details and accept your answer.


why E-5 and A-open doesn't sound same even when they have same 110 frequency?

Question: I am trying to play Brushy one string's "No man stop me"

 on a different set of notes. He uses 3 notes there E-5, E-3 E-1.
E-5 and A-open have same 110 frequency. But I am not able to switch E-5 with A-open and have the same sound.
When playing the same note, how can I duplicate the same sound on different strings?
Answer: The fundamental frequency of a note only affects the pitch we hear, not the timbre.
Timbre is the quality of a note that makes it possible to tell what instrument is playing the note. Imagine if a bassoon or cello were playing the same A at 110 Hz fundamental frequency. It would be the same note, but you would instantly be able to tell that it's a cello or a bassoon and not a guitar.
Obviously the difference between a fretted A and open A on the same guitar is much more subtle than the difference between different instruments. There are many subtle differences between open and fretted A. The sounding lengths, string diameter and stiffness, string tension, and finally the difference between the impedance at the nut versus the finger and fret.
Being able to tell the difference between the same note fretted versus open is a sign of a fairly developed ear, so while you might be a little frustrated at having trouble reproducing the exact right sound, you can also feel happy that you're able to tell the difference.
Comment: @Tim I meant impedance, as in mechanical impedance, which has an effect on to what extent different vibration modes are reflected back down along the string.
Comment: Did you mean impedance? Possibly 'tone' would work?


Exibição de UL falha na altura

Question: Tenho uma UL e suas li's tem 50px de altura.
No caso a altura da UL deve obedecer esses 50px
Acontece que em algumas li's eu tenho imagens nelas e isso está causando uma aumento na altura da li.
O problema: Só ocorre no Chrome.
Existe algum hack para corrigir isso?
Veja no Firefox. (Não ocorre a falha)

Agora no Chrome

Ainda estou aprendendo CSS.

/* CSS Document */
@import url('http://fonts.googleapis.com/css?family=Open+Sans');
*,
*:before,
*:after,
*:active,
*:hover {
    font-family: 'Open Sans';
 margin: 0;
 padding: 0;
    border:0;
    outline: none;
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: content-box; /*Comprimir(diminuir) as medidas do elemento para não aumentá-lo quando adicinar margin e padding*/
}
ul {
 list-style: none;

}
ul li {
 height: 50px;
}
ul.topo{
 background-color: #CCCCCC;
 color: #FFFFFF;
}
ul.topo li {
 text-align: center;
}
ul.ulHorizontal {
}
ul.ulHorizontal li {
 display: inline-block;
 line-height: 50px;
}
ul.ulHorizontal li img {
    vertical-align: middle;
}

img {
    max-width: 100%;
}
a, a:hover {
    text-decoration: none;
}
button,
input[type=button],
input[type=submit],
input[type=reset] {
 cursor: pointer;
 background-color: #CCCCCC;
}
button:hover,
input[type=button]:hover,
input[type=submit]:hover,
input[type=reset]:hover {
 background-color: #DCDCDC;
 border: 1px rgba(0,0,0,.2) solid;
}
button:active,
input[type=button]:active,
input[type=submit]:active,
input[type=reset]:active {
 background-color: #FFFFFF;
}
/************   CORES   **************/
.bgcCinza100 {
 background-color: #CCC;
}
.bgcCinza25 {
 background-color: #DCDCDC;
}
.bgcPreto100 {
 background-color: #000;
}
.bgcBranco100 {
 background-color: #FFF;
}
.bgcVermelho100 {
 background-color: #F00;
}
.bgAzulCiano {
 background-color: #007EAE;
}
/************   CORES   **************/
.btnCarrinho {
 width: 50px;
 height: 25px;
 line-height: 15px;
 text-align: center;
}

ul#menuCategorias li {
 height: 50px;
 text-align: center;
}

CATEGORIA

NOME

PREÇO

FRETE

TRANSPORTE

EDITAR

BLOQUEIO

EXCLUIR

Leve

Produto 1

120.33

Eu sei que se eu adicionar o height das li's que é de 50px à UL.

...

isso resolverá o problema.
Mas, seria correto fazer isso uma vez que não é padrão para todos os browsers?
Comment: Carlos coloca o HTML e o CSS completo para podermos simular seu problema, só com a imagem não da para te ajudar muito
Comment: Adicionado o código ao final da pergunta @hugocsl!
Answer: O mais apropriado para este caso seria usar as tables do html, pois para fazer tabelas como essas elas servem bem melhor.
Tente alterar seu código para

        Categoria
        Nome
        Preço
        Frete
        Transporte
        Editar
        Bloqueio
        Excluir

        Leve
        Produto 1
        120.33

Vale lembrar que para uma melhor organização no código sempre é bom deixar todo o css em um arquivo externo.

Exibição de UL falha na altura


A $\Bbb Z$-module that is not a direct sum of cyclic modules

Question:
We would like to find a $\Bbb Z$-module that can not be written as a
  direct sum of cyclic modules.

My thought is: Let's consider the $\Bbb Z$-module $\Bbb Q$. In other words the abelian group $(\Bbb Q,+)$. This group is indecomposable. Indeed, let's assume that $\Bbb Q=\Bbb Za \oplus \Bbb Zb$, for some $a,b\in \Bbb Q$. But then, $ab \in \Bbb Za\cap \Bbb Zb$, so the intersection is not zero.  Generalising, if $\Bbb Q$ was a direct sum of more than one cyclic groups, then would not have that property and the argument is similar, ie the product if the generators would be in the intersection.
And since this abelian group is not cyclic, we are done.
Questions:
(1) Is this claim completely correct?
(2) Any other examples?
Thank you.
Comment: (1) The argument's fine, but $\mathbb{Z}$ itself is a cyclic $\mathbb{Z}$-module.
Comment: $\Bbb{Q}/\Bbb{Z}$ is an example. As is $\Bbb{Q}$.
Comment: A classic example is $\mathbb{Q}$.  Inside this, you can take the abelian group consisting of fractions $a/2^n$ for $a\in\mathbb{Z}$ and $n\geq 0$.
Comment: In your edit, you've only shown that $\mathbb{Q}$ is not the sum of two cyclic modules. (The sum of cyclic modules is not cyclic, so that doesn't generalize even to finite direct sums.)
Comment: Try and show that any two non-zero submodules of $\Bbb{Q}$ intersect non-trivially because any two non-zero rational numbers have a common non-zero multiple.
Comment: I think you mean: "... of *nonzero* cyclic modules"
Comment: Thank you for your answers, you are right. Please check my update. :)
Comment: Okay, let's try it again then. If $\Bbb Q$ was a direct sum of more than one cyclic groups, then clearly  would not have that property (and the argument is similar to this I did with 2 direct summands, ie the product if the generators would be in the intersection). Better now?
Answer: Your argument is correct.
Note that a $\mathbb{Z}$-module is an abelian group and by the fundamental theorem of finitely generated abelian groups any finitely generated abelian group is the direct sum of cyclic $\mathbb{Z}$-modules, so in particular we are looking for an abelian group that is not finitely generated. This naturally suggest to look at $\mathbb{Q}$.
Answer: Here's a hint that reflects what I think are the most important concepts here and doesn't depend on the structure theorem for finitely generated $\Bbb{Z}$-modules.
First a couple of standard definitions:

A $\Bbb{Z}$-module $M$ is said to be torsion-free if whenever $x  \in M \setminus \{0\}$, $m \in \Bbb{Z}$ and $mx = 0$, then $m = 0$.
For $m \in \Bbb{N}$ with $m > 1$, a $\Bbb{Z}$-module $M$ is said to be
$m$-divisible if for every $x \in M$, there is $y \in M$ such that $x = my$.

Now show that, if a sum $M = \bigoplus_i M_i$ of non-trivial cyclic $\Bbb{Z}$-modules is torsion-free, then each summand $M_i$ is torsion-free and deduce from this that $M$ is not $m$-divisible for any $m > 1$. But $\Bbb{Q}$ is torsion-free and $m$-divisible for every $m > 1$. (For a smaller example you can take the submodule of $\Bbb{Q}$ generated by the numbers $\frac{1}{m^i}$ for arbitrary $i \in \Bbb{N}$ and a fixed $m > 1$.)


Change compiz parameter by command line on XFCE

Question: Compiz has a useful tool, annotate. This feature allows write freely on your desktop. But has a limitation, only one color is configured: it is not possible to switch between stroke colors.
I would like to switch between annotate stroke colors quickly.
The current stroke color is stored on configuration:
dh4@GLOW:~$ cat .config/compiz-1/compizconfig/Default.ini
[core]
s0_active_plugins = core;composite;...;
s0_hsize = 4

[annotate]
s0_stroke_color = #0000FF

I tried to change value with dconf:
dconf write /org/compiz/profiles/Default/annotate/stroke-color "'#00AAAAAA'"

Also with gsettings:
gsettings set \
org.compiz.annotate:/org/compiz/profiles/Default/annotate/ stroke-color '#00AAAAAA'

No errors appears on execute commands, but has no effect, neither restarting compiz.
How can I do to change and apply parameter from script or command line to compiz without ccsm gui on XFCE?
Answer: You can do it activating dbus. Then just execute:
dbus-send \
  --print-reply \
  --type=method_call \
  --dest=org.freedesktop.compiz \
         /org/freedesktop/compiz/annotate/screen0/stroke_color \
         org.freedesktop.compiz.set \
         string:"#00ffffff"  #<-- new color

Red color is #ff0000ff
Blue color is #0000ffff


Chart Js Stacked Bar Chart with Multiple levels or categories

Question: I am trying to create a chart in ng2-charts that will have multiple labels, so for example the x access would have categories of all the Months, above that it will be broken down into each week, and then the bar sections would be something like rainy days, dry days, and snowy days.
I have found their documentation here https://www.chartjs.org/docs/latest/samples/bar/stacked-groups.html and have their example working, but need to expand on that to add another level, is that possible?
Comment: Set the `stack` option of all the `datasets` you want to stack to the same value. Check the "Setup" tab in the example you linked
Comment: @MatthiasSchmidt Thank you, that makes sense, do you know if they have a way to display the labels for the stacks?
Answer: The following is what I was able to get figured out. This code will allow create a chart with 3 categories on the x axis divided into 4 categories each. This isn't the full code set, but should hopefully give others an idea on how to proceed if they are stuck.
<canvas baseChart
  *ngIf="!loading"
  [datasets]="myChartData.chartData"
  [options]="barChartOptions"
  [legend]="barChartLegend"
  [chartType]="barChartType"
>
</canvas>

The following is the code that is used to set the bar chart options from data being returned by the api
this.barChartOptions = {
      responsive: true,
      scales: {
        xAxes: [
          {
            id: 'xAxis1',
            type: 'category',
            labels: this.myChartData.xAxis1Labels,
          },
          {
            id: 'xAxis2',
            type: 'category',
            labels: this.myChartData.xAxis2Labels,
            offset: true
          },
        ],
        yAxes: [
          {
            ticks: {
              beginAtZero: true,
              callback: function(value: number) {if (value % 1 === 0) {return value;}}
            }
          }
        ]
      },
      title: {
        display: true,
        text: this.myChartData.title,
      },
      legend: {
        labels: {
          filter: function (item, chart) {
            return item.text !== undefined && item.text !== null;
          },
        },
      },
      tooltips: { enabled: false },
      hover: { mode: null },
    };

This is the model that the api is returning:
import { ChartData } from "chart.js";

export class myChartData {
  chartData: Array<ChartData>;
  rankXAxisLabels: Array<string>;
  namcXAxisLabels: Array<string>;
  title: string;
}

Lastly, this is the format of the chartData Array that is being built by the api:
[
  {
    "data": [1,0,9,0,4,0,5,8,0,0,0,0],
    "label": "firstPartOfBar",
    "stack": "dataStack",
    "backgroundColor": "red",
    "hoverBackgroundColor": "red",
    "xAxisID": "xAxis1"
  },
  {
    "data": [1,0,8,0,5,0,0,0,0,0,6,7],
    "label": "Second Part of Bar",
    "stack": "dataStack",
    "backgroundColor": "blue",
    "hoverBackgroundColor": "blue",
    "xAxisID": "xAxis1"
  },
  {
    "data": [4,0,2,0,1,0,0,0,12,14,16,0],
    "label": "Third Part of stack",
    "stack": "dataStack",
    "backgroundColor": "green",
    "hoverBackgroundColor": "green",
    "xAxisID": "xAxis1"
  }
]


Numerical Methods - Fixed Point Iteration

Question: We were set the following question before we had learned about systems of non-linear equations and I'm confused as to how we're meant to answer it using the fixed point method theorems that we have been provided with.
Consider the fixed point iteration $\underline{x}^{n+1} = \underline{\Psi}(\underline{x}^{n})$ where
$\Psi(\underline{x}) = \Psi((x_1,x_2,x_3)^T))$ =

Analyse the convergence of the method to the fixed point $\alpha$ = $(0,\frac{1}{3},0)^T$.
Are we meant to show that $|\Psi(\underline{x})|<1$ and continously differentiable? And if so, do we do this using a Jacobian matrix?
Answer: When $x$ is near $\alpha$, the map $\Psi$ can be approximated by the first-order Taylor series
$$ \Psi(x) \approx \Psi(\alpha) + J(\alpha) (x - \alpha) = \alpha + J(\alpha) (x - \alpha) $$
where $J(\alpha)$ is the Jacobian matrix evaluated at $x=\alpha$.  Note that we have used the fact that $\alpha$ is a fixed point, i.e., $\Psi(\alpha)=\alpha$.
From this you can show that that the recursion
$$ x^{n+1} = \Psi(x^n) $$
is equivalent to
$$ x^{n+1} - \alpha = J(\alpha) (x^n - \alpha) $$
So if you define $y^n = x^n - \alpha$ then
$$ y^{n+1} = J(\alpha) y^n $$
so
$$ y^n = J(\alpha)^n y^0 $$
where the superscript on $J(\alpha)$ is an exponent rather than a time index.  Now the critical question is whether and how quickly $J(\alpha)^n$ shrinks with $n$.  This depends on the eigenvalues of $J(\alpha)$.
Basically, the fixed point is stable if all of the eigenvalues of $J(\alpha)$ are less than 1.  The convergence error is roughly $\lambda_1^n$, where $\lambda_1$ is the largest eigenvalue.


How to know the time interval between two dates in swift

Question: So I'm working on an AR app. Every 3 seconds a new node appears around the room the player's in until there are 25 created. In the creation time of them the user have to destroy the nodes as soon as they're created. But I want to create a time interval between the first node the user destroyed and the last one, so I can show the time taken to do so to the user, track the high score and all that.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {return}

        let location = touch.location(in: self)
        let node = nodes(at: location)

        if let sprite = node.first {
        let scaleOut = SKAction.scale(to: 3, duration: 0.4)
        let fadeOut = SKAction.fadeOut(withDuration: 0.4)
            let remove = SKAction.removeFromParent()
        let group = SKAction.group([scaleOut, fadeOut])
        let sequence = SKAction.sequence([group, remove])
            sprite.run(sequence)
            targetCount -= 1

    }

The guard statement makes sure that the computer can capture the first touch the user did, and then that touch save it in a variable, consults the location of that touch in the view. Then if there's any node at that location, the first one it'll be removed with animations using SKActions. If I need to be more specific, tell me. Thanks in advance.
Comment: So basically you have a timestamp property that you set when the first node is touched and then you have a timestamp or interval property you set/calculate when the last node is touched. You need to identify where in the code to do this, I guess `touchesBegan` can be used for both operations.
Answer: I think what you want to do is something like:
let startTime = Date()

/* Then some time later */

let timeInterval = Date().timeIntervalSince(startTime)

timeInterval is a TimeInterval, which is a type alias for Double.  It's the number of seconds between the two Date instances.
On the other hand, if what you want to do is actually delay to do something, but don't actually need the timeInterval for anything other reason, look into DispatchSemphore.wait(timeout:) or DispatchQueue.asyncAfter(...)
Comment: I was thinking about that, but I don't know where to put it. I have two variables, one is counting the nodes created and the other is counting the nodes destroyed by the user. So I was thinking about adding an if statement, something like "if targetsCreated == 25, and then I put the startTime, but the var could only be used within that statement.
Comment: Can it be a property of the object where you override `touchesBegan(_: with:)`?
Comment: Could you be more explicit? I don't know exactly what u mean
Comment: You said that your var could only be be used within the if statement you were contemplating.   If the var were moved outside of the function and made a property of the function into whatever UIResponder - probably your view - then it would persist between events and be available for the next one.


R-squared: X "explains" the percentage of variation of the Y values. Does axis order matter?

Question: Summary:  Am I correlating two independent variables?   Is that the problem?
Let's say I have data point for square footage of a house and the asking price.   Now, I can ask "Does square footage (x) determine price (y)?"  This is intuituve, and makes sense.  R-squared would end up saying "Square footage explains X% of the variation in price".  So far, so good.
But, what if I want to predict the square footage from the price?  That seems valid.  Now, I ask "Does price (x) determine square footage (y)?"  So far, it seems either can function as the independent or dependent variable.  However, the wording or r-squared seem off.  "Price explains X% of the variation in square footage".  Huh?  Square footage is not some sort of multi-factor variable.  It's more static.  Nothing "explains" the square footage, it just is.  Get what I'm saying?  Like if price only explains x% of square footage, what else would explain square footage?  Square footage is just square footage.  It's not like price, which can be determined by many things (square footage, renovations, size of yard, etc).
Another example can be age (x) and the mileage on a car (y).  With a regression equation, I can use one to predict the other.  Either order seems to work.  However does age "explain" the mileage, or does mileage "explain" the age?  In this case, both seem weird.  Both are just static independent variables.  Neither explains the other, if you ask me.
What am I missing here?  Thanks!
Comment: Incidentally, JackOfAll, are you aware of how the process of upvoting and accepting answers works on this site?  It's a valuable aspect of creating great questions and answers, so please spend a few moments reading our [FAQ](http://stats.stackexchange.com/faq) and act accordingly on the questions you have already asked.  In particular, any thoughtful, well-crafted useful answer, even if it's not the best in the group or only partially addresses your question, deserves your vote in recognition of the effort on the part of the respondent.
Comment: $R^2$ can be expressed as the square of the correlation between the observed and the fitted values in a regression model. Correlation is a symmetric operation (e.g. ${\rm cor}(X,Y) = {\rm cor}(Y,X)$ for two random variables $X,Y$) so, no, order does not matter.
Comment: Perhaps these observations will help a little: notice that it's the *variation* in something that is being "explained" here, not the something itself.  "Explained" is a particularly poor choice of words, IMHO.  "Accounted for" or "accommodated by the fitted model" are closer to what's going on, but they're longer and fussier to say or write.
Comment: So, why does the above example sound so off?
Answer: Your wording is implying causality, which is not what the R^2 represents. "Does price (x) determine square footage (y)?" is implying causality which is not what is captured through a correlation. "Price explains X% of the variation in square footage" describes that there is a relationship between price and square footage, but not a causal one. This only implies that these variables vary together, not that price causes square footage. Its more akin to saying "In general, when price goes up X amount, square footage happens to go up Y amount"
Comment: You're right, but it's ironic that people usually understand a phrase like "when price goes up, ... square footage goes up..." in the *causal* sense of changes in price creating changes in square footage.  (Realtor, I need more room in my house: please put it on the market and then increase the asking price by 20%!)  The commonplace interpretation of R^2 as "explaining" variance suffers from the same problem of colloquially implied causality, which I believe is at the root of the original question.  In light of this, it might be better to restate your last sentence in different words.
Comment: Good point something like "positive relationship between" or something which avoids some kind of underlying mechanism would be better.
Answer: Edited with added material in response to comments by @whuber
This is an answer based on probability theory, not statistical estimates, so your mileage may vary.
If random variables $X$ and $Y$ have correlation coefficient $\rho$, then the linear least-mean-square error estimate of $Y$ given the value of $X$ is
$$\hat{Y} = \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X),$$
and similarly,
the linear least-mean-square error estimate of $X$ given the value of $Y$ is
$$\hat{X} = \mu_X + \rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y).$$
Note that $\hat{Y}$ and $\hat{X}$ are  random variables that are linear functions of $X$ and $Y$ respectively. Their means are
$$\begin{align*}
\mu_{\hat{Y}} &=E[\hat{Y}] = E\left[\mu_Y+\rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X)\right]
= \mu_Y+ \rho\frac{\sigma_Y}{\sigma_X}E[X - \mu_X] = \mu_Y\\
\mu_{\hat{X}} &= E[\hat{X}] =  E\left[\mu_X+\rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y)\right]
= \mu_Y+ \rho\frac{\sigma_X}{\sigma_Y}E[Y - \mu_Y] = \mu_X
\end{align*}$$
while the variances are
$$\begin{align*}
\sigma_{\hat{Y}}^2 &= E[(\hat{Y} - \mu_{\hat{Y}})^2]
= \frac{\rho^2\sigma_Y^2}{\sigma_X^2}E[(X-\mu_X)^2] = \rho^2\sigma_Y^2\\
\sigma_{\hat{X}}^2 &= E[(\hat{X} - \mu_{\hat{X}})^2]
= \frac{\rho^2\sigma_X^2}{\sigma_Y^2}E[(Y-\mu_Y)^2] = \rho^2\sigma_X^2
\end{align*}$$
Finally, the variances of the residual
errors $Y - \hat{Y}$ and $X - \hat{X}$ are $\sigma_Y^2(1-\rho^2)$ and
$\sigma_X^2(1-\rho^2)$ respectively.  One can think of these results as
follows.

If we use the mean $\mu_Y$ as an estimate for $Y$, the mean-square error is  $\sigma_Y^2$, but if we know the value of $X$ and use $\mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(X - \mu_X)$ as the estimate of $Y$,  the mean-square error is reduced
  to $\sigma_Y^2(1-\rho^2)$.
If we use the mean $\mu_X$ as an estimate for $X$, the mean-square error is  $\sigma_X^2$, but if we know the value of $Y$ and use $\mu_X + \rho\frac{\sigma_X}{\sigma_Y}(Y - \mu_Y)$ as the estimate of $X$,  the mean-square error is reduced
  to $\sigma_X^2(1-\rho^2)$.
In both cases, the mean-square error is reduced by the same fraction
  $(1-\rho^2)$.

In terms of scatter plots (for discrete random variables or data)
on a plane with coordinate axes $x$ and $y$,
we have two straight lines
$$
\begin{align*}
y &= \mu_Y + \rho\frac{\sigma_Y}{\sigma_X}(x - \mu_X),\\
x &= \mu_X + \rho\frac{\sigma_X}{\sigma_Y}(y - \mu_Y),
\end{align*}
$$
of different slopes $\rho\sigma_Y/\sigma_X$ and
$\sigma_Y/\rho\sigma_X$ passing through the mean point
$(\mu_X,\mu_Y)$.  The reason for the different slopes is that
we are choosing the slope to minimize the sum of the squares of
the  vertical
distances of the points from the line in the first case, and to minimize the
sum of the squares of the horizontal distances of the points from the
line in the second case.  These sums of squared distances are
$\sigma_Y^2(1-\rho^2)$ and $\sigma_X^2(1-\rho^2)$ respectively.
As a simple example, suppose that $(X,Y)$ takes on values $(0,0)$, $(0,1)$ and
$(1,1)$ with equal probability $\frac{1}{3}$ each or we have a scatter plot
with these three points.  One can grind through the calculations if desired,
but it should be intuitively obvious that we should estimate $Y$ as $\frac{1}{2}$
if $X = 0$ and as $1$ if $X = 1$, while we should estimate $X$ as $0$ if
$Y = 0$ and as $\frac{1}{2}$ if $Y = 1$, that is the two lines have different
slopes $\frac{1}{2}$ and $2$ (in fact, reciprocal slopes since $\sigma_X^2 = \sigma_Y^2 = \frac{2}{9}$ in this example).  This is what probability
theory gives.  But if you treat the three points as a small sample from
from an unknown population and use estimates of the population
means, variances and correlation coefficent, then your results may be
different.
Comment: It would help to be explicit about what this says about $R^2$ and to provide some intuition for that.  Formulas are great--they provide rigor that is valued in good replies--but the question begs for *explanation.*  So why, then, should minimizing vertical distances and minimizing horizontal distances result in the same $R^2$?
Comment: @whuber I am not a statistician and am not too sure that I know what $R^2$ is.  Based on a cursory reading of what wikipedia says, it would seem to be similar to $\rho^2$, in which case Macro's comment seems to be pertinent.
Answer: Your example can legitimately be run the other way. Why not estimate square footage from price?  Suppose price data is publicly available, but square footage is not.  Yet you want to estimate square footage (to determine the carpet or furniture market, the likely heating cost, or whatever). It's perfectly valid to model square footage as a function of price.
In my opinion, you are getting hung up in the semantics of "independent" and "dependent" variables. Better to use "predictor" and "predicted".