For $\alpha\in (0,\ 1)$, $f(z)=\sum_{n=1}^{\infty}\frac{z^n}{(n!)^{\alpha}}$ satisfies $|f(z)|\leq A_{ε}e^{b_{ε}|z|^{\frac{1}{\alpha}+\epsilon}}$

Question: Let $\alpha \in (0, \ 1)$. Then $f(z)=\sum_{n=1}^{\infty}\frac{z^n}{(n!)^{\alpha}} $ satisfies $\vert f(z) \vert \leq A_{\epsilon} e^{b_{\epsilon} \vert z \vert^{\frac{1}{\alpha} + \epsilon}} $ for any $\epsilon>0$ for some constants $A_{\epsilon}>0$ and $b_{\epsilon}>0$.
I can show the result is true for $\alpha \geq 1$, but I don't know what to do for $\alpha \in (0, \ 1)$.
If $\alpha \geq 1$, then $\vert f(z) \vert \leq \sum_{n=1}^{\infty} \vert\frac{z^n}{(n!)^{\alpha}}\vert= \sum_{n=1}^{\infty} \left(\frac{ (\vert z \vert^{\frac{1}{\alpha}})^n}{n!}\right)^{\alpha}$ and $(\frac{ (\vert z \vert^{\frac{1}{\alpha}})^n}{n!})^{\alpha} \leq \frac{ (\vert z \vert^{\frac{1}{\alpha}})^n}{n!}$ for all except finitely many $n$.
Any hints or reference are appreciated.
Comment: Did you try using Stirling's Formula?
Answer: For $\alpha\in (0,1)$, I suggest Cauchy-Schwarz.
Let $g(r) = \max_{|z|=r} |f(z)|$.
Fix  $\delta \in (0,\alpha)$. Let $1/p = \alpha-\delta$ and $1/q = 1- (\alpha-\delta)$. Then $p$ and $q$ are Holder conjugates.
Let's crank the CS machine:
\begin{align*} g(r^{\alpha-\delta} ) &\le \sum \left(\frac{ r^{n}}{n!}\right)^{\alpha-\delta}\times \frac{1}{n!^\delta}\\
& \le \left(\sum \frac{ r^{n}}{n!}\right)^{\alpha-\delta}\underset{=c_\delta}{\underbrace{\left (\sum \frac{1}{n!^{\frac{\delta}{1-\alpha+\delta} }} \right)^{1-\alpha+\delta}}}\\
& = e^{(\alpha-\delta) r} c_\delta,\end{align*}
and the result follows.


Does the azure service configuration file override web.config files?

Question: On any given server there are several sets of config files. Most obviously the Machine.config which sets up a lot of default values and then the web.config .
Any values specified to the web.config take precedence. Does the service configuration file override any of these settings ?
Answer: No, these are different concepts.  They actually have no relationship whatsoever.  I have a post on what the service configuration and config relationship is here.  You will have to substitute 'RoleEnvironment' for 'RoleManager' as things have changed since I last posted this, but it is the kernel of truth here still.


MacOS app, altool validation fails with "Could not find the main bundle or the Info.plist is missing a CFBundleIdentifier"

Question: I have an .app which I want to distribute on the AppStore. The AppStore page is set up. I would like to upload a first build. I create a .pkg file with
<code> pkgbuild --install-location ~/Applications --component ./AppName.app ./PkgFileName.pkg
</code>
This succeeds, and if I run this file created locally it correctly installs in the applications folder. After this I would like to validate this file with altool:
<code>xcrun altool --validate-app -f ./PkgFileName.pkg -t osx -u <my_apple_id> -p @keychain:"altoolpass"
</code>
This fails with the following message:
<code>*** Error: Validation failed for 'PkgFileName.pkg'.
*** Error: Could not find the main bundle or the Info.plist is missing a CFBundleIdentifier in 'PkgFileName.pkg'. Unable to validate your application. (-21017)
 {
    NSLocalizedDescription = "Could not find the main bundle or the Info.plist is missing a CFBundleIdentifier in \U2018<app_name>\U2019.";
    NSLocalizedFailureReason = "Unable to validate your application.";
}
</code>
I'm stumped by this, because the original .app file contains an Info.plist in .app/Contents/Info.plist, and this file has the CFBundleIdentifier key, and the value is the same as we set up on the AppStore page. Why is it still giving me this error?
Answer: AFAIK you can't distirbute the pkg via Appstore.
The Appstore way is to just download an app to the /Applications folder and run it, that is it.
The error you got is because altool is not designed to work with pkg files at all.
Let's say, you need to do some preparations before apps first launch, so you are using pkg for this. You can instead put some checks into the code, and do stuff right from there on first start.
You should be able also to create an app which run pkg from inside its bundle, so called app-installer. But this is not according to the guidelines ofc.
In the end, if you really need pkg, you can distribute it from your own website/other sources (signed and notarized), but not from AppStore.
Comment: https://help.apple.com/app-store-connect/#/devb1c185036
You can use the transporter app, which accepts a .pkg or .ipa. Regardless, the error is the same with the .app itself.
Comment: Could you show your Info.plist and your bundle structure for the .app bundle you are trying to pass to the altool?


what does it mean that there is leakage of information when one uses a test set?

Question: I have read about the term "leakage of information" that occurs when one tries to estimate the generalization error by using a test set in Machine Learning models. However, I was not able to find any formalism (maths or statistics) that could help me to clarify why this situation happens. Could anybody explain to what does this term refers to?
Answer: Data leakage occurs when there is information in your test set's predictors that wouldn't be available when the model is "live." There are egregious and subtle cases of data leakage.
Egregious case.
Say the goal is predicting retention of an insurance policy during the first year. At month 3 there is a scheduled check-in with a company representative, and after the check-in the data element had_check_in flips from False to True. A junior modeler is working on a cross-sectional data set (no time dimension) with information from the last two years, and has_check_in is one of the variables. The modeler concludes that this variable is very important, because when it is True, the policy holder is more likely to keep the policy throughout the period of study. Clearly that contains information from the future, and in a live run of the model, all had_check_in values would be False for new cohorts!
Subtle case.
Suppose that now the junior modeler is approaching the above problem with a time dimension, having learned from the last mistake. He takes a holdout set of 2000 policy holders (across all time) and use the remaining policy holders' retention values to build a model that, among other variables, uses month and year. Then he runs the predictions on this test set to get holdout metrics. While this is  unlikely to be a disaster, there's information leakage in that aspects of the particular months and years can be learned from the members of the training set. In a prediction scenario, you couldn't estimate the properties of the future time period from actual policy holders, so the holdout metrics are likely to be optimistic.
I've seen both cases in practice, but the subtle case is much more common. It makes me hesitant to use automatic cross validation routines from sklearn, etc., because I feel these situations need to be carefully thought out in general.
Comment: While I appreciate your answer, most leakage between train and test data comes from dependence across rows, i.e. grouped or even duplicated rows.
Comment: I think my second case is similar to grouped data in that you have a group of rows for each time period, and you're learning the properties of the group that apply to the holdout. I was also considering updating to mention the "purging" and "embargoing" concepts from the Advances in Financial Machine Learning book. Feel free to beat me to it!


Returning a value of a high order function doesn't

Question: I have the following:
def retSomething(x: Int): Int => Int = x*x

assert(retSomething(5)(5) == 25)
assert(retSomething(1)(1) == 1)
assert(retSomething(1)(0) == 0)

But the assertions fail. Surely that is correct, but it says implementation is missing when running it.
Answer: I think the implementation you are looking for is:
def retSomething(x: Int): Int => Int = y => x * y

What does the method retSomething mean? It takes an Int and returns a function Int => Int.
The function Int => Int takes another Int and returns an Int.
So we want to return with a function that takes a new Int, that's why we need: y => x * y.
Type inference works nicely here, you don't need to write (but can): (y: Int) => x * y
Answer: this returns Int while expecting Int => Int
def retSomething(x: Int): Int => Int = x*x

it should be
def retSomething(x: Int): Int => Int = x => x*x


What are things to look for when buying a new keyboard?

Question: I'm a complete newbie to music and I've been wanting to buy a keyboard for a while now. However, upon doing some research I was surprised at the vast amount of technical details associated with each keyboard. The more I researched on it, the more confused I became.
Does pressure sensitivity matter? Are a higher number of accompaniment voices better? Do total number of instrument voices make any differences from a learning perspective? Super confused about what I should watch out for in particular when purchasing a keyboard. I've considered either the CASIO CS-S300 or the Yamaha PSR-E373, but as I said, I'm just so lost in the details. If someone can mention what major things to look out for, it would be appreciated. Thanks
Comment: Do you want to play it like a piano or play it like a synthesizer or like an organ or... other?
Comment: How do you plan to use the keyboard? Some info on your short and longer term goals, or knowing you haven't considered goals, would help get you the best advice.
Comment: @Aaron right. My short term goal is to become proficient enough to be able to play songs on it. Nothing professional, but something I can play in the house and impress some friends with.Getting really comfortable with the basics and having a good grasp so I can adapt to play the tune of any song I'd like on the keyboard. In the long term, my goal is small performances in my local community at annual functions and events.The usage is definitely casual and not professional yet.
Comment: @ToddWilcox Definitely not like an organ, just a regular keyboard.
Comment: I think the point that ToddWilcox was getting at is that a piano would have weighed keys (so something that you plan too use to play piano music should probably have them too) while many other keyboard instruments wouldn't have weighed keys. Therefore you should probably think about what you plan to use it for.
Answer: This is in danger of being closed, although you're not actually asking for specific keyboards to buy - like the vtc-ers seem to think - but in any case, you've been minimal as to what you think you need.
It sounds like an electronic piano would be a good bet. 61 notes should be the absolute minimum. You won't use all of them for a while, but when you do reach that stage, with fewer, you'll have to start shoppng again.
The action on acoustic pianos is very different from that on an organ - which has keys that are merely switches. You need a keyboard that is sensitive to how hard/soft it is played. More like a piano. There are many that have that facility, but at the same time, unless they feel like a piano, you'll be searching later.
The facility to change sounds is a personal thing. Some players are happy with just a piano sound, but it's fun to change to others at times. Only you will be the judge of that.
Some pianos have internal speakers, some don't. you seem like you'll need the former, and a headphone socket is a useful addition.
No recommendations here - that's off remit for this site, so you need to try out several - many - and eventually make your own wishlist. Price and portability are other aspects, but no clues from the question.
Comment: I've been thinking of that. A 61 key keyboard with sensitivity to how hard the keys are pressed. The major ones I've looked at are the casio and yamaha. So far, I've thought of the Yamaha PSR-E373, let me know your thoughts.
Comment: Like I said, no recommendations!


Why does this trig equation have only 2 solutions and not 4?

Question: Upon solving this equation:
$$
5\sin x - 5\cos x = 2
$$
for the interval $0 \le x < 360^\circ$, I manipulated it in order to get a solvable trigonometric equation below:
$$
\sin 2x = 21/25
$$
Normally this would procure 4 solutions: $28.6^\circ, 61.4^\circ, 208.6^\circ, 241.4^\circ$ (one can easily plot this into Desmos to see that it is true).
However, the answers only include the middle 2 solutions: $61.43^\circ, 208.57^\circ$. Why is this? Why do 2 of the solutions simply disappear? Could it have something to do with the way in which I manipulated the original equation (by squaring and substituting using the appropriate trigonometric identities)?
After looking at the original equation, it makes sense to some degree, but then I'm not a fan of such methods, especially since one could encounter more complicated equations in the future.
Am I missing/forgetting something fundamental?
Comment: How did you manipulate the original equation to get your $4$ answers ?
Comment: You do not need to use a double angle here. Recall that $\cos x=\sin (\frac{\pi}{2}-x)$ and apply difference to product formula.
Answer: $$\sin{x}-\cos{x}=\frac{2}{5}$$
$$(\sin{x}-\cos{x})^2=\frac{4}{25}$$
$$1-2\sin{x}\cos{x}=\frac{4}{25}$$
$$\sin{2x}=\frac{21}{25}$$
In the second step, when we square both sides, we inadvertently include the solutions of:
$$\sin{x}-\cos{x}=-\frac{2}{5}$$
This equation is true for $28.6^{\circ}$ and $241.4^{\circ}$, which are the extra two solutions which we don't need.
Comment: Thanks, this makes total sense. That was the exact mistake I made, by squaring both sides, and forgot that this would invoke the existence of the other 2 solutions.

Appreciate the help!


Cordova 3.5 - Back button event firing in Android emulator but not firing in real android device

Question: I'm using cordova 3.5 to develop an android application, I want to close the application when back button is pressed. I'm using the following code -
document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        document.addEventListener("backbutton", backKeyDown, true);
    };
    function backKeyDown(){
    if(confirm("Exit Application?")) {
       navigator.app.exitApp();
    }
    };

This code seems to work fine in android emulator and I get a confirm dialog when back button is pressed. But in real device, it just navigates back to previous page.
I tried preventDefault() also, still no use.
Someone help me with this.
Answer: The problem is fixed now, Previously while debugging i commented this line in cordova.js
return prompt(argsJson, 'gap:'+JSON.stringify([service, action, callbackId]));

Uncommenting the line fixed the problem.


Play stream from gstreamer in browser

Question: I want to play stream from gstreamer in a web browser.
I played around a with RTP, WebRTC and SDP files but, while VLC was able to connect to stream by simple SDP, browsers were not. I later understood that WebRTC requires secure connection which only complicates things and is not needed for my purposes. I stumbled upon Media Source Extension (MSE) of html5, which seems that it could help, but I'm not able to find some comprehensive tutorial or appropriate specs on how to get gstreamer to stream correct data and later how to play them using MSE. I'm also not sure about latency with using MSE.
So is there a way to play stream from gstreamer in a browser?
Thanks.
Answer: Using node webrtc project, I was able to combine output from gstreamer with webrtc call. For gstreamer, there is a project which enables it's use with node gstreamer superficial. So basically, you need to run gstremaer process from node process, which can then control output from gstremaer. On every gstreamer frame there is a callback called which takes the frame and can send it to webrtc calls.
Then an webrtc calls needs to be implemented. There is required some signaling protocol for calls. One side of the call will be the server and another will be the client's browser, instead of two browsers. Then a video track will be created where frames from gstreamer superficial will be pushed.
<code>const { RTCVideoSource } = require("wrtc").nonstandard;
const gstreamer = require("gstreamer-superficial");

const source = new RTCVideoSource();
// This is WebRTC video track which should be used with addTransceiver see below
const track = source.createTrack();

const frame = {
        width: 1920,
        height: 1080,
        data: null
};

const pipeline = new gstreamer.Pipeline("v4l2src ! videorate ! video/x-raw,format=YUY2,width=1920,height=1080,framerate=25/1 ! videoconvert ! video/x-raw,format=I420 ! appsink name=sink");
const appsink = pipeline.findChild("sink");
const pull = function() {
        appsink.pull(function(buf, caps) {
                if (buf) {
                        frame.data = new Uint8Array(buf);
                        try {
                                source.onFrame(frame);
                        } catch (e) {}
                        pull();
                } else if (!caps) {
                        console.log("PULL DROPPED");
                        setTimeout(pull, 500);
                }
        });
};

pipeline.play();
pull();

// Example:
const useTrack = SomeRTCPeerConnection => SomeRTCPeerConnection.addTransceiver(track, { direction: "sendonly" });
</code>
Comment: That's different topic
Comment: how to use this to open the stream on a web browser?
Comment: Ok, but if you can guide, that would help. I am trying to build a GStreamer - WebRTC - Browser project. So far, I could only find GStreamer's webrtcbin pipeline. But nowhere I could find how to them use this pipeline to display live stream on a browser. You solution looks close, so you help will be appreciated.

Play stream from gstreamer in browser


Adding multiple users to a field using user/autocomplete

Question: I have the following code to add a field to my custom module to add in users. But I can only add in one user using the user/autocomplete feature.
<code>$form['usershare'] = array(
  '#title' => t('Share Collection with:'),
  '#type' => 'textfield',
  '#autocomplete_path' => 'user/autocomplete'
);
</code>
How do I enable multiple users? These users should be separated by a comma on the back end for me to process it.
Comment: This post should answer your question: https://drupal.stackexchange.com/questions/51089/creating-module-with-autocomplete-and-accepting-multiple-values-in-textfield
Answer: as @Geat said:
Your form should be like below.
<code>    $form['usershare'] = array(
      '#title' => t('Share Collection with:'),
      '#type' => 'textfield',
      '#autocomplete_path' => 'user/autocomplete',
      '#multiple' => TRUE,
    );

    // Implemenbts hook_menu() for user/autocomplete path.
    function module_name_menu() {
      $items['user/autocomplete'] = array(
        'page callback' => '_user_autocomplete',
        'access arguments' => array('access user autocomplete'),
        'type' => MENU_CALLBACK
      );
      return $items;
    }

    // Implements callback function to get users in autocomplete with comma seperated
    function _user_autocomplete($string) {
      if ($string) {
        $items = array_map('trim', explode(',', $string));
        $last_item = array_pop($items);
        $prefix = implode(', ', $items);
        $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
        foreach ($result as $user) {
          $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
          $matches[$value] = check_plain($value);
        }
      }
    // return output in JSON format.
    drupal_json_output($matches);
}
</code>


How can I prevent 'Error messages' to be shown to anonymous users?

Question: Like any Drupal site, my site also shows red notifications from time to time...
The problem is that when these notifications are error messages, they appear at the bottom of the site in a new "Pseudo-reigion"... I use the term "Pseudo-region" because they establish a new "Region" under the site.
It's not really a region but rather a white area with an H1 and some text under it. It is displayed with the word "Error" (as a title, using a
 HTML tag), and the text below it is "The website encountered an unexpected error. Please try again later.". This is how it looks like in my site:

So my single aim is to not display these error messages (and this whole "Pseudo region" actually), at least for anonymous users, since it's uglyfies my site.
I've tried to use the following CSS syntax but with no success:
body.not-logged-in div.messages.error {display: none !important;}

This "error" pseudo-region is extremely problematic since it appears even in cases when I hide the notifications themselves via the "Disable messages" module.
I'm sure this error is native to Drupal but I've already tried everything I know to remove it, so any help is appreciated.
An important note
It's a long story why, but disabling the errors through /admin/config/development/logging doesn't help in this case. I'm looking for a solution which is either CSS, a Javascript (not jQuery) tweaking of the css by the text itself, or, some change in the Drupal PHP code that will prevent to program of printing this error.
Comment: Go to /admin/config/development/logging What is "Error Messages to Display" set to?
Comment: As you're asking for a "pure CSS solution" this is off topic here. Questions about CSS can be asked on Stack Overflow, though. If you change your mind and decide a Drupal-related solution will work, just edit the question and flag for re-opening
Comment: This message is not generated by Drupal. This is generated by your webserver/php and should be logged as a 500 error in your PHP or Web Server logs which you need to look at and fix. Hiding the error is like covering the white elephant in the room with a cloth and pretending like it's not there.
Comment: It caused when a certain module works. But anyway, how can you prove it relates to the PHP?
Comment: You've proven it relates to PHP yourself @benos - that error message can only be seen as the result of a PHP exception. We can't see what that exception is, only someone with access to the backend of the site and/or server logs can
Comment: I tried to understand how did you guys knew this is not a php error native to Drupal? I guess you have seen it in other PHP installments?... Ben.
Comment: @benos: please verify my edited (enhanced?) version of your question, to make sure I did not introduce anything you didn't intend/want. Of course feel free to further enhance where appropriate. Hope it'll help to get this question reopened ...
Comment: No, it's a generic error page that Drupal outputs when PHP encounters an exception that it can't recover from. You need to find out what that exception is, so that you can identify the part(s) of code you need to fix. It can't be done from here, only by someone with access to your server.
Answer: Like @Screenack suggested.

Navigate to /admin/config/development/logging
Set the radio to None
Select Save Configuration

Please note that I recommend keeping the errors on locally and trying to fix them.
Comment: Hello Albertski, Thanks deeply for you answer, but I really need a pure CSS solution this time. I've updated the question. Sorry for not mentioning that.
Comment: If I remember correctly what could fix it is a JS manipulation on the css, but it seems the problem itself was coming from the server and fixing it there was best.


Views field rearrange

Question: I am using Field group module for creating fieldset in content type.

Can I have similar features while rearranging the fields selected in views.
Answer: You can try using module Field group views
Project page says

Provides a view format for Field group.
In other words, a field group can be displayed using a view. One
  possible usecase would be to generate a table using fields as columns.
Comment: I tried this module, it promises to do that, but I am not able to select the "field group" in my view field.

Views field rearrange


Format telephone numbers for values

Question: I have created a webform with telephone field, the submitted data is displayed in a views table, however the numbers in submitted data are in random format such as 1234567890, 234-987-9870, how do I configure the number field in views to be displayed in (123) 123 1234 format for the existing values and new submission.
Comment: Does this work with Views? https://www.drupal.org/project/telephone_formatter
Comment: @cilefen, there is no view format options for the module
Answer: If you are able to use Jquery here is a solution:
$('.phone').text(function(i, text) {
return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});
http://jsfiddle.net/Xxk3F/1/
Answer found at: https://stackoverflow.com/questions/8760070/how-to-format-a-phone-number-with-jquery

Format telephone numbers for values


Distorted sound coming from Yamaha Electronic Piano

Question: I have a Yamaha PSR-E303, and all of a sudden one day when I play a note it comes out warped and transposed several octaves down. The speakers are full of static as well. Unplugging the thing for a while and letting it be fixes the problem, but only for a few seconds, before the sound becomes warped all over again.
This has happened before, but after I let it be for a month, it started to behave correctly again. I suppose the problem returned when I absent-mindedly placed a laptop on top of the thing one day. So to all the electronics-savvy guys in this forum: Is my keyboard doomed?
Answer: It's broken.  Very unlikely to be anything to do with putting a laptop on top. Quite likely the power supply, if only on the principle that whenever any electronic item fails, the power supply is the first suspect!   Whether it's worth taking a sub-$200 item to a repair shop is questionable I'm afraid.
Comment: True, but not terribly helpful.
Comment: Helpful, but not terribly optimistic!
Answer: I agree w/ Lawrence "House Of"  Payne that it's not worth taking to a repair shop. From your description, it's quite possible that there's a bad solder joint which opens up when the electronics warms up (PC board warping).  If you have a friend who's handy with a soldering iron, ask him/her to open up your KB and see if there's a visible failure point.  If you're getting octave shifts, there's also a good chance that a capacitor has failed in some resonant circuit. Again, this might be located by your electronics-savvy friend.
Comment: @AlphonsoBalvenie most SMDs _can_ be re-soldered with a standard soldering iron – it's tricky, but I wouldn't say "nearly impossible". However I wouldn't give to much hope that the failure point is easily visible, and just re-soldering all suspicious joints will indeed probably cause more new damage.
Comment: unfortunately those types of boards are usually made with micro surface mount components, and are nearly impossible to re-solder with a standard soldering iron.
Answer: Most likely culprit's are -cold or dry solder joints especially in the Audio output section, Shorted electrolyte capacitors, or decentred speaker coils
Answer: I recently had issues with my yamaha p115. And after long research found that it is affected by headphones. Probably their cable was causing an induction ,which affected some component in the piano. Static noise that resolves itself after 2 days off. When disconnected from phones, waited 2 days off, brings no problem.
Answer: Humidity and wet weather causes my Yammy keybord to blast out a terrible cacophonous mess on certain chord structures. Put a blow heater or refrigerated aircon (not evaporative) at it for a few hours and see if this fixes it.


Comic relief probability

Question:
Let $X_0,X_1,...$ be i.i.d and let $N = \inf \{ n\ge 1:X_n >X_0 \}$.
Prove that $P(N>n) \ge \frac{1}{n+1}$.

My attempt,for $E = \{N>n\} = \{N = n+1 ,n+2,n+3,...\}$ and we know for $\{N = n+k\}$ means for the first $n+k+1$ element the first one i.e. $X_0$ rank exactly $n+k$, and $X_{n+k}$ rank exactly $n+k+1$, which means it has probability $\frac{1}{(n+k+1)(n+k)}$ by symmetric reasoning.Hence the sum for all $N>n$ is $\frac{1}{n+1}$.
What I don't understand is why it may greater than $\frac{1}{n+1}$.
This is the example from Durrett probability page 70.Comic relief
Answer: Think of the case where all the $X_i$'s are 0. What is $N$? That should hopefully be enlightening to tell you where the symmetry argument fails, and that it is indeed exact if $P(X_i = X_j) = 0$

Comic relief probability


checking fields in csv for a number

Question: I'm trying to stop my process hanging when it sees a misentry in a csv file, which is usually  "#N/A", where is should have a double (I know its a string when read in...)
But this doesnt work, why?
String ColumnString = (values[Column]);
String NA = "#N/A";
if (ColumnString==NA);
{
     Console.WriteLine(values[Column]);
     Console.WriteLine("non numeric value detected, Skipping line #{0}", LineNumber);
     break;
}

Comment: changed to this as using Linq,,,
Comment: how do you post a change to coding? no {code} option in comment,
Comment: What exactly doesn't work? What is the type of `values`?
Comment: do you need to know that ColumnString has at list a numeric character?
Comment: the values{[column] should hold a double value for processing, but hardware issues sometimes result in #N/A being entered into csv file, i have to catch this and ignore that line, or file, until i get to end of the .csv dataset, sorry i should have been clearer,,,, when i test this it always catches it, even if it is not #N/A
Answer: If you sure that type of ColumnString  is string the you can check it for at least  one numeric character as follow with linq query
bool hasnumeric = ColumnString.Any(t => char.IsNumber(t));
if(hasnumeric== true)
{
//colomnString has at least one numeric character
}else{
//colomnString doesn't have any numeric characters
}

Comment: does this work with String though, my csv file has strings in it.
Comment: yes the linq query above will work on any string
you can fetch whole data from csv file into a string variable then check the variable with this query
Comment: do you want to search whole csv for a special string value?
like this "#N/A"?
Answer: string ColumnString = (values[Column]);
string NA = "#N/A";
if (string.Compare(ColumnString,NA)==0)
{
 Console.WriteLine(values[Column]);
 Console.WriteLine("non numeric value detected, Skipping line #{0}", LineNumber);
 break;
}

checking fields in csv for a number


Sum $\sum \frac{1}{n}\not \in N$

Question: If $S_n$ denote sum of $n$ terms of H.P. $\frac{1}{2},\frac{1}{3},\frac{1}{4}$ ..... , Then prove using summation of series that $S_n\not\in N$ $\forall \ n \in N$;
Comment: check out [this post](http://math.stackexchange.com/questions/2746/is-there-an-elementary-proof-that-sum-limits-k-1n-frac1k-is-never-an-int)
Comment: What do you mean by your emphasis on 'using summation of series?'
Answer: For $\,n\ge 2\,$:
$$S_n:=1+\frac{1}{2}+\frac{1}{3}+\ldots+\frac{1}{n}=\frac{n!+\frac{n!}{2}+\frac{n!}{3}+\ldots+\frac{n!}{n}}{n!}$$
If we now choose $\,k\in\Bbb N \;\;s.t.\;\;2^k\mid n!\;,\;\;2^{k+1}\nmid n!\,$ , then all the summands in the last expression's numerator are even except one, namely
$$\frac{n!}{2^k}$$
and thus that expression's numerator is odd, whereas the denominator isn't...
Comment: No, I am not since I don't know what "using summation of series" can possibly mean.
Comment: are u sure this would be accepted as a answer to the question: " using summation of series"?
Comment: @DonAntonio I don't know what I'm missing-If n=7, 7!/4 = 1260, which is even...
Comment: but in this case, k =2 and k+1 =3, so that 4| 7! and 8|7! also. So that k does not satisfy the condition that $2^k | n! $ and $ 2^{k+1}\nmid n!$

Sum $\sum \frac{1}{n}\not \in N$


Implementing Latent Dirichlet Allocation - notation confusion

Question: I am trying to implement LDA using the collapsed Gibbs sampler from
http://www.uoguelph.ca/~wdarling/research/papers/TM.pdf
the main algorithm is shown below

I'm a bit confused about the notation in the inner-most loop. n_dk refers to the count of the number of words assigned to topic k in document d, however I'm not sure which document d this is referring to.  Is it the document that word (from the next outer loop) is in?  Furthermore, the paper does not show how to get the hyperparameters alpha and beta.  Should these be guessed and then tuned?  Furthermore, I don't understand what the W refers to in the inner-most loop (or the beta without the subscript).
Could anyone enlighten me?
Answer: I had this same problem and had to read a lot about the Dirichlet distribution to understand what was going on here. Stijn Vermeeren answers most of your questions, but I think there's a bit more to say.
Types and Tokens
One thing that is confusing about a number of descriptions of LDA available online is that they don't distinguish carefully between word types and word tokens. The vocabulary size is the number of word types; there is one type for "if", and one type for "the", and so on. But there will (almost always) be multiple tokens of that word type in the corpus.
So to answer your first question, yes, the d refers to the document containing the current word token under consideration. This is iterating over every word token in the corpus, and is storing the word type, the topic assignment, and the document for that particular token -- in word, topic, and d respectively. Only the topic will change in this process; the other two are constant for our purposes.
Hyperparameters
Answering your last three questions is more complicated, and requires that I talk for a moment about symmetric and asymmetric hyperparameters.
Basically, in many implementations of LDA, the values of a[k] are all different. They govern the shape of the Dirichlet distribution of topics over documents. Making the values different allows some topics to be much more prominent than others across many of the documents. So, for example, there might be a topic that makes up a solid 30% of almost every document. That, in turn, allows the algorithm to sequester common, uninteresting words into a few very common topics.
But in many implementations of LDA, the values of b[word] are all the same. They govern the shape of the Dirichlet distribution of words over topics. Because they are all the same, no one word appears more frequently in all topics than any other word. (Some words will appear much more frequently in a given topic, but those topics are outliers; the words will probably appear much less frequently in others.)
Now, in the pseudocode above, the numerator uses the notation b[w] to refer to the beta parameters. That's confusing, because if the beta value is the same for all words, then we don't need a subscript at all. But if the beta value differs for each word, then it really ought to be b[word], not b[w], since w has already been used to refer to the entire corpus of word tokens! Then, in the denominator, a different notation is used: b x W. There's no subscript, and a mysterious W appears. As Stijn says, the W is indeed the vocabulary size -- the number of word types (not tokens). So here, b is being treated as the same for all words, and we're just multiplying that value by the number of word types. You could just as easily use summation notation, and if the values of b[i] were indeed different, then you would have to.
So my interpretation of the above is that b[w] refers to the beta value for each word type -- which is always the same. And so the bottom ought to be b[w] x W, or else the top ought to be just b.
If you wanted to have different beta values for each word, you could use summation notation instead, and sum over the values of b[word] for each word. But most implementations I've seen follow the advice of this paper, which suggests that making beta values asymmetric is unnecessary -- and might even degrade performance slightly.
To answer your final question: yes, you can just guess. By default, MALLET uses symmetric alpha and beta, with defaults of 50 (as the sum of alpha values) and 1.0 (as the individual beta values -- for good reasons that I won't get into here).
Answer: I would suggest you look at page 8 of "Probabilistic Topic Models" by Mark Steyvers and Tom Griffiths. I found their explanation of the Gibbs algorithm quite clear and easy to implement.
To answer your questions:

i seems to range over (indexes for) all the words in all the documents, and d indeed seems to refer to the document of the word under consideration.
There are some algorithms for estimating alpha and beta but I haven't really understood any of them myself. Just tuning the parameters manually should be ok in most cases.
W seems to be the size of the vocabulary, i.e. the number of unique words.
I'm confused about the beta with / without subscript as well. If they use a different beta per word, then maybe in the denominator it should say the sum of all beta_w, instead of beta * W?


Term for exp(beta) from a Gamma-GLM

Question: I have read a lot about interpretation of coefficients from Gamma-GLMs (using a log-link function), e. g. from this thread How to interpret parameters in GLM with family=Gamma , and found this to be very helpful.
However, I wonder what is the correct scientific term for the exp(coefficient) from a Gamma-GLM? From my understanding this would describe the ratio between two means, and could therefore be interpreted as a mean-ratio. This should be somewhat similar like when you would compare two odds in a logistic regression and call it an odds-ratio. Is this correct or is there any other more suitable term?
Answer: There is no scientific term in common usage for the exponential of a GLM coefficient. In some cases exp(coefficient) might represent the log-ratio of two group means, but not always. It depends on the experimental design and on how the GLM model has been parametrized.
In the simplest case that Group is a factor will two levels (A and B say) and a gamma GLM is fit by
fit <- glm(y ~ Group, family=Gamma(link="log"))

then exponentiating the second coefficient, exp(coef(fit)["GroupB"]), would indeed yield the ratio $\mu_B/\mu_A$ where $\mu_A$ and $\mu_B$ are the expected values for groups A and B respectively.
In the bioinformatics contexts that I work in, exp(coef(fit))[2] might be called the fold-change and coef(fit)[2] the log-ratio or log-fold-change.
My advice would be to choose terminology appropriate for your specific context.

Term for exp(beta) from a Gamma-GLM


Showing $|\mathrm{Gal}(f(x))| = \deg(f)$

Question: How can I prove that if $f(x)$ is a separable irreducible poly. and $\mathrm{Gal}(f(x))$ is abelian then $|\mathrm{Gal}(f(x))| = \deg(f)$?
Answer: Let $K$ be the ground field and let $a$ be a zero of $f$. Then $K(a)$ is a subfield of the splitting field $L$ of $f$. Since $\mathrm{Gal}(L/K)$ is abelian the subgroup fixing $K(a)$ is normal, so $K(a)/K$ is a normal extension. Since $f$ is irreducible and it has a zero in $K(a)$, it splits completely in $K(a)$. So $L=K(a)$. Therefore $[L:K]=\deg(f)$, which means $|\mathrm{Gal}(L/K)|=\deg(f)$.


How to print first element from dropdown list on change?

Question: I have this function :
function LoadRegions() {
    var region = $('#RegionID');

    var url = "/Account/GetRegions";
    $.getJSON(url, { countryId: $('#CountryID').val() }, function (response) {
        // clear and add default (null) option

        //region.empty().append($('<option></option>').val('').text('Please select'));

        for (var i = 0; i < response.length; i++) {
            region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
        }

    });
}

When user choose countrie i call this function but i want to display on start first element from that list...
With this line i get "Please select" but i want first element from list:
  region.empty().append($('<option></option>').val('').text('Please select'));

If i comment this line i get blank...any help?
Answer: I believe the problem could have been the issues with chaining. See the documentation for end().
The empty() and append() were being done on the same chain. This can sometimes cause issues because of the chaining algorithm. The documentation has good description of the issue.
This can fix your problem.
$.getJSON(url, {
    countryId: $('#CountryID').val()
}, function(response) {
    // clear and add default (null) option
    region
        .empty()
        .end()
        .append($('<option>', {
            value: '',
            text: 'Please select'
        }));
    $.each(response, function(key, tocken) {
        region.append($('<option>', {
            value: tocken["Id"],
            text: tocken["Name"]
        }));
    });
});

Answer: you need to set the attribute selected in the option tag in order to set the option as selected. To do this, you need to modify your for loop like this:
for (var i = 0; i < response.length; i++) {
    if(i==0)
        region.append($('<option selected></option>').val(response[i].Id).text(response[i].Name));
    else
        region.append($('<option></option>').val(response[i].Id).text(response[i].Name));
}

Answer: var s_string = '<option>Select Value </option>';

for () // your for loop
{
  s_string+=''; //your option tag code (appned fetch data in same variable and appned that variable after for loop end)
}

// appand s_string variable to your destination id or class (append)


Grabbing specific variable from while loop for form submit

Question: I have a while loop generating information with a checkbox, I would like to update the database with the new "completed" value. How can I select the specific checkbox that is generated. Please help with showing me how I can grab the specific value of a checkbox and the task_name.
Thanks, Ryan
    while ($row = mysql_fetch_array($query)){
        $task_name = $row['task_name'] ;
        $task_description = $row['task_description'];
        $task_completed = $row['completed'];
        $tasks .= '

                    <form action="" method="post">Completed? <input name="completed" type="checkbox" '.
                    ($task_completed == 1?'checked="checked"':'').
                    ' /><input type="submit" value="Update">

                    '.$task_name.'

'.$task_description.'

</form>
';
        }
}
echo $tasks;

Comment: what do you want to do?please explain more.
Answer: You need to name your input with something unique for the row, such as the task_name, or better, a database record ID.
Then when the user submits the form, you will use $_POST["YourTaskNameOrIDHere"] to check the value.
What you have currently calls all the check boxes the same thing.

EDIT: I'm sorry, you're isolating all of these in their own forms, I just realized that.
What you can add is an <input type="hidden" value="$task_name" name="TaskName" /> to the form, so you can look what the checkbox is corresponding to. Then, when the user submits the form, use $_POST["TaskName"] to find out the name of the task.
Comment: Where and how would i do this? @Barrakoda
Comment: @Ryan please see my revised edit. I misunderstood what you were doing at first.
Answer: Add a hidden field to each of your forms containing the task_id
<form action="" method="post">
    Completed?
    <input name="completed" type="checkbox" <?=($task_completed == 1?'checked="checked"':'')?> value="1" />
    ...
    <input name="task_id" value="<?=$task_id"?> type="hidden" />**strong text**
</form>

After submit:
if (isset($_POST['task_id']) { // form has been submitted

    $task_id = $_POST['task_id'];
    $completed = $_POST['completed'];

    $sql = "UPDATE task SET task_completed=$completed WHERE task_id=$task_id LIMIT 1";
    // code for updating database
    // better use PDO or mysqli-* instead of old and deprecated mysql_*
}


What chord completes this chord progression?

Question: Not sure how to complete this chord progression in guitar tab. I think the chord on the left is CaddG followed by a Cadd9. What comes after that?
3     3
3     3
0     0
0     2
2     3
3     x

I tried the following but it didn't sound right.
3
3
2
3
x
x

Comment: We can't tell you what to write. That's subjective. We can tell you that the first chord is just a G major chord. Not a "CaddG". Also check out "Closer to Fine" and "Wonderwall" for chord progressions that include your first two chords. Might give you some ideas.
Comment: These two chord form the basis of the Greenday song Time of your life. Pretty common chord sequence.
Comment: 'CaddG' can't be right, as G is already part of a C triad.
Comment: The second chord is a c major chord with the 9th added. The D on the B String.
Comment: @NeilMeyer you're right. I believe in the song Dmaj is the third chord.
Answer: The first chord is Gmaj, and the second is, as you say, Cadd9.
Since you're looking to "complete" the progression — i.e., create a cadence:

A very logical next chord would be Fmaj, completing a 2-5-1 root movement.

1
1
2
3
3
1

Another option would be the treat the 9 in the Cadd9 as a suspension from the G chord, and just resolve it to Cmaj.

3
1
0
2
3
x

The chord that didn't work,

3
3
2
3
x
x

most likely didn't work because of the two top notes: D and G. That chord, in this context, is best named F6add9, and, because of the 6 and 9, does not create the sense of resolution that a "plain" Fmaj chord gives.
Comment: Thanks for suggestions and background! I'll try out the Fmaj and Cmaj tomorrow.
Comment: Aaron, your alternate voicing of the F6(add9) is close to unplayable. At best it's very awkward and difficult. You have to do partial bars with both the 3rd and 4th fingers. I was actually able to play it but it felt my hand was going to seize up!
Comment: I'm not sure I'm playing the chords in the right order but `Fmaj` didn't seem to resolve the sequence. May be because I couldn't play the full barred chord. Not sure what this chord is but it seemed better `x 0 0 2 3 3`. Not totally satisfying but it did provide some resolution.
Comment: @JohnBelzaguy Note to self: have a guitar handy before getting too clever. Thanks. I've removed the hand-torture chord.


Unable to remove entry from a file using Ansible regex

Question: Note: i m seeking solution for Ansible. Here is the issue description:
I have a file filedet.yml as below, however realtime this yaml may contain many more IP and file details.
---
10.9.9.111:
  /tmp/test.jar:
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb

  /tmp/best.jar:
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb

10.8.8.44:
  /tmp/conf/extra/httpd-ssl.conf:
    hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2

  /tmp/conf/httpd.conf:
    hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2

I wish to extract a particular IP and the file details so that it can be removed from the yaml using state: absent attribute . Thus, the desired regex should return the below:
10.9.9.111:
  /tmp/test.jar:
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954e

  /tmp/best.jar:
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb

I decided to have the start pattern as '10.9.9.111' and search until there are no spaces or newlines which means until it gets to the next IP.
I prepared the below regex and it shows correct, desired FULL Text match on http://regex101.com. See snapshot.
Regex query below:
[^#](^10.9.9.111:)(.|\n)*^(?!( |\n))

The same regex works fine with grep -Pzo and returns the desired string. However, the regex fails to work with ansible's lineinfile module as it does not yeild any results.
i want this regex or any other solution to work with Ansible so i can remove the given IP and it's file details from the yaml
Ansible:
   - name: "Remove entry from file."
     lineinfile:
       path: "/app/filedet.yaml"
       regexp: "[^#](^10.9.9.111:)(.|\n)*^(?!( |\n))"
       state: absent

Can you please suggest what is the issue here ?
Comment: Does this answer your question? [How to find patterns across multiple lines using grep?](https://stackoverflow.com/questions/2686147/how-to-find-patterns-across-multiple-lines-using-grep)
Comment: In POSIX *REs, circumflex in the middle of a regular expression matches a regular circumflex; it loses its meaning as a special character. And IIRC a POSIX grep can't perform a multiline match
Comment: `grep` only examines one line at a time; there is no way really to specify matches which should straddle newlines with this tool.
Comment: I m not seeking a solution for grep but seeking a regex that will work with Ansible
Comment: `grep -Pzo` works for me. But how can i get it to work with Ansible's lineinfile ?
Comment: Shall i repost specific to Ansible?
Comment: @Ashar, you might want to remove the irrelevant info about grep and POSIX. It's all about Python regex. And, in the end, it's not about regex at all, I think.
Answer:
Q: "I wish to extract an IP and the file details."

A: Use include_vars. For example
    - include_vars:
        file: filedet.yml
        name: my_dict
    - debug:
        msg: "{{ my_dict['10.9.9.111'] }}"

give
    "msg": {
        "/tmp/best.jar": {
            "hash": "e6df90d38fa86f0e289f73d79cd2cfd2a29954eb"
        },
        "/tmp/test.jar": {
            "hash": "e6df90d38fa86f0e289f73d79cd2cfd2a29954eb"
        }
    }

Q: "Remove an entry from the file."

A: Use template. For example
$ cat filedet.yml.j2
{% for item in my_dict_keys %}
{{ item }}:
  {{ my_dict[item]|to_nice_yaml|indent(2) }}
{% endfor %}

The task below
    - set_fact:
        my_dict_keys:
          - "10.8.8.44"
    - template:
        src: filedet.yml.j2
        dest: filedet.yml

gives
$ cat filedet.yml
10.8.8.44:
  /tmp/conf/extra/httpd-ssl.conf:
      hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2
  /tmp/conf/httpd.conf:
      hash: 1746f03d57491b27158b0d3a48fca8b5fa85c0c2

Notes:

It's a bad idea to use lineinfile for this purpose
Data in the question is not valid YAML. The key is repeating

10.9.9.111:
  /tmp/test.jar:
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb
  /tmp/test.jar:
    hash: e6df90d38fa86f0e289f73d79cd2cfd2a29954eb

Comment: can you get the template to include all ip and file details except the one i wish to remove inthis case 10.9.9.111
Comment: No. I can't. The template is fine as it is. Instead, you can test what you want first and update your question with all the relevant details.
Comment: Vladimir i updated the question with all the details. Can you have a look ?
Comment: New post with refined description here: https://stackoverflow.com/questions/59948370/remove-contents-of-a-include-vars-file-using-ansible


How do I use hook_theme() in a module?

Question: I need help in using hook_theme in my custom module. Any good examples is much appreciated. I have created a CCK input form and I want to theme the input form using hook_theme. The content type is created using hook_install().
I have used hook_form_FORM_ID_alter() to alter the theme of the input form. Following is the code for that.
 function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id) {
   theme('footer_menu_node_form', array('form' => $form));
 }

 function footer_menu_theme($existing, $type, $theme, $path) {
   return array('footer_menu_node_form' => array(
     'arguments' => array('form' => NULL),
     'template' => 'footer-menu-node-form',
     'render element'=> 'form',
   ));
 }

I have also created a footer-menu-node-form.tpl.php file inside the module, and the following is the code in the template file.

 <?php print drupal_render($form['title']); ?>

Menu Tree

 <?php print drupal_render($form['title']); ?>
 // this one is for rendering all the remaining items, like hiddens:
<?php print drupal_render($form); ?>

When I load the footer menu content type. The content within the
 tag is alone printed and then I get the following error:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 40961 bytes)

Can anyone tell me what I doing wrong, or could anyone suggest me an efficient way to use hook_theme() in modules?
Comment: You should also show the code for `footer_menu_node_form()`, or it is not possible to answer this question without giving guesses.
Answer: The proper way to assign a theme function to a form using hook_form_alter() is like this:
function footer_menu_form_footer_menu_node_form_alter(&$form,&$form_state,$form_id){
  $form['#theme'] = 'pz_footer_menu_node_form';
}

I can't tell if you're using Drupal 6 or 7; you're using the arguments property in your theme declaration which is only valid in Drupal 6, and also the render element property which is only valid in Drupal 7.
Judging by the out of memory error I'm guessing Drupal 7. As you call drupal_render() on the the $form object in your template file, it runs that variable back through the same theme function, and you end up with an infinite loop.
Try changing the last line in your template file to this:
<?php print drupal_render_children($form); ?>

That should stop the error from happening.
Comment: I am using Drupal 7. I am new to drupal 7 and its really confusing. and no proper online resources as well.
Comment: @DrupalDeveloper I just realised you're probably using D7; I've updated the answer, it should solve the problem
Comment: There are loads of good resources out there for Drupal 7, it's just knowing where to find them really. Personally I'd recommend reading [Pro Drupal 7 Development](http://www.drupalbook.com/), it's a great book. Also check out the [Examples module](http://drupal.org/project/examples), it has tons of Drupal API examples.
Comment: thank you very much for your help and support. You have been clarifying most of my questions. I am indebt to you.
Comment: should I pass the arugment in hook_theme for drupal 7
Comment: `arguments` was actually renamed to `variables` in Drupal 7 so normally you'd use that; but as you're using `render element` on a form there's no need to pass `variables` as well. You can take out `arguments` altogether and everything should still work fine :)
Comment: can you please tell me what are the arguments that could be passed to hook_theme function.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3219/discussion-between-drupal-developer-and-clive)
Answer: In your theme function definition, you use the "arguments" index, but you should use the "variables" index; then, as reported in hook_theme(), "variables" and "render element" exclude each other: If you are using one, you should not use the other.

Each information array must contain either a 'variables' element or a 'render element' element, but not both. Use 'render element' if you are theming a single element or element tree composed of elements, such as a form array, a page array, or a single checkbox element. Use 'variables' if your theme implementation is intended to be called directly through theme() and has multiple arguments for the data and style

Using drupal_render() could cause an infinite loop, but only if $form, or one of its sub-elements uses the #theme (or #theme_wrappers) property, and that property points to a theme function using the same template file that you are showing in your question.
drupal_render() calls theme(), but only in two cases.
  if (isset($elements['#theme'])) {
    $elements['#children'] = theme($elements['#theme'], $elements);
  }

  if (isset($elements['#theme_wrappers'])) {
    foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
      $elements['#children'] = theme($theme_wrapper, $elements);
    }
  }

If $elements['#theme_wrappers'] and $elements['#theme_wrappers'] (where $elements is the argument passed to drupal_render()) are not defined, drupal_render() doesn't call theme().
Comment: This is what i ve been looking for.I will try this method and let you know.

How do I use hook_theme() in a module?


Issues of injection surjection and bijection

Question: Please let me know the issues of injection surjection and bijection. I wants the fully explanation or mathematical definition of it.
Also you can share me issues of injection surjection and bijection
Comment: Consider the integers $\mathbb{Z}$.  The identity map $\iota: \mathbb{Z} \rightarrow \mathbb{Z}$ is a bijection.  The inclusion map $f: \mathbb{Z} \rightarrow \mathbb{Q}$ where $f(x) = x$ for all $x \in \mathbb{Z}$ is injective because each possible output corresponds to a unique input.  The map $g:\mathbb{Z} \rightarrow \{0, 1\}$ where a given integer's parity determines its output is surjective because everything in the range of the function is a possible output of $g$.
Comment: Can you share me an example of the same ? with new response
Answer: If we have a function $f:F\to F'$, then:

Injective: $x\in F\ne x'\in F \to f(x)\ne f(x')$
Surjective: $\exists x \operatorname{s.t.} y\in F' \to f(x)=y$
Bijective: both of the above
Comment: Thanks Man. Its perfect it will be good if you will share me an theory as well thanks you much dude.
Comment: they're definitions - no theory involved
Comment: Fine thanks. Its good here with this.
Comment: @ni3 try the chat for broader discussion based type questions.


What is the order of this group? Real simple right?

Question: This is a real simple question.
If I have a group $Z_4\times Z_6$, is its order $24$ or $lcm(4,6)=12$. My teacher told me its $24$, which makes sense because there are $4$ cosets for $H=\langle(2,2)\rangle.$
I only ask this because I have also seen that the group $Z_{10}\times Z_{15}$ has order $30$ and same goes for $Z_{30}\times Z_5$.
My question is which is it?
Comment: The order of a direct product is the product of the orders
Comment: The direct product symbol is written as \times
Comment: are we using an external direct product?
Comment: yes. i dont know the symbol for that. sorry
Comment: so it is 24, then. So then the order of Z10/Z + Z15/Z is 150?
Comment: yes, that is the order of that group
Answer: I think you may be confused between the concepts of the order of a group and the order of an element in the group.
The order of a group is the number of elements in the group. If $G$ and $H$ are finite, then the number of elements in $G\times H$ is the product of the number of elements in $G$ and the number of elements in $H$: the order of $G\times H$ is the order of $G$ times the order of $H$.
You could also ask what the maximum order of any element in such a group is: the order of an element $g$ in a group is the smallest positive integer $k$ such that $g^k = e$. In the case of $\mathbb{Z}/m\times\mathbb{Z}/n$, the largest order of any element is in fact $\mathrm{lcm}(m,n)$, so that for example in $\mathbb{Z}/4\times \mathbb{Z}/6$, the maximal order of an element is $\mathrm{lcm}(4,6) = 12$.


Having done them in Win8, how do I do Split Pages in Windows 8.1?

Question: My team and I have recently migrated our app from Windows 8 to Windows 8.1. It worked fine until I went to update the existing pages and add a new one. Instead of any errors, just nothing happened.
The way I understand it is, in Windows 8, split pages had their information stored in a DataSource class, and I could even put all the stuff for all the split pages into the one class if I wanted to.
It's changed in Windows 8.1, though, so all the content for the pages go into the code behind pages for that actual page.
I can't actually seem to find any examples, articles or anything online on how to do this. Would anyone be able to link me to such an article or explain how the groups and items are meant to go into the class?
Thanks!

Reply to htuomola:
When I tried adding a new split page, at the time I didn't realise that how you put the content into the page is handled differently, so I just went and did the same as before. I admit, it might not be best practice to have done it like this, but at the time I felt it made the most sense. I had all the groups and items for the various split pages in the one data source class, and the individual pages just pointed to which items/groups I wanted. So, not knowing any better, I made an identical split page to the others, and it didn't pick up the new groups/items, but it did find the old ones. The old split pages were working fine at this point too. It was only when I tried to make a new 8.1 style split page, that they all stopped working and threw errors like "The type 'IME.Miscellaneous.Additional.Help' already contains a definition for 'itemDetailGrid'" and ""IMEDataSource" does not exist in the namespace "using:IME.Data".", even though I didn't change the pages that are having these errors - at all.
Answer: The Split Page item template still exists with Windows 8.1 applications even if the NavigationHelperand visual state handling code is a bit different. I think it also works pretty nicely out-of-the-box. Did you try adding a new Split Page page to you project, what problems are you facing?
Some documentation that you can find is in MSDN project templates and item templates pages. You should probably find a few samples in MSDN that use the Split Page/App template.
About the information storage, do you mean that in Windows 8.0 there was a separate view model class and 8.1 only has an ObservableDictionary property on code behind? Nothing prevents you from replacing that with a better solution. I'd just delete it and follow MVVM guidelines, setting up a ViewModelLocator and view models.
Comment: Thanks for the reply! My reply was too long, so I've added it to the main question.


Getting Billing details of Subscription android?

Question: I am using InAppBilling version 3 in my app, I am able to purchase subscriptions using test account. Now my question is how do I know the billing details in my app againt one subscription plan. Suppose I have purchase one plan and it renews Daily, Is there any provision or method to know that renew is done to this product with details(like for ex. product_id, time, date, update, renewing_status...etc). I have refered to this link.
And the other thing is that do a user can subscribed to multiple subscription at a time ?
Answer: After searching quite a bit, finally I found my solution. Google don't provide subscription order number for test purchases(if you are using test account to test your application without going to production). It only provide product_id, token, purchase_time, developer_payload, autoRenewing, package_name and purchase_state as if Google don't send details to Play Billing server as it is not a real purchase. Still your can implement your own logic as it provide autoRenewing = true(if product is in renewal state) and false(if product is in non-renewal state) with purchase_state = 0(purchased) , 1(canceled) and 2(refunded). And one more thing I came to know after reading documentation of Google that, test user who has taken the subscriptions the recur on daily basis, but they will only get the same details, which they get while purchasing a test subscription plan.
It provide order Id for real purchases with other details. If your subscription is monthly and your order Id is GPA.1234-5678-9012-34567 while purchasing the plan. Then next month Google append your order Id with GPA.1234-5678-9012-34567..0(second month) , GPA.1234-5678-9012-34567..1 (third month) and so on. So you can track your renewal of purchases with order Id as described in here. Rest are same.
Comment: I Agree with you.Thank You.:)


"Swing-Shell" java.lang.InternalError: Could not initialize COM: HRESULT=0x80010106

Question: I have a Java 9 app that I'm trying to package for the Windows Store. The strange thing is that it works as expected when I run the exe-launcher directly, but I get the following strange error when I run the launcher via the APPX package:
Exception in thread "Swing-Shell" java.lang.InternalError: Could not
initialize COM: HRESULT=0x80010106
at java.desktop/sun.awt.shell.Win32ShellFolderManager2.initializeCom(Native Method)
at java.desktop/sun.awt.shell.Win32ShellFolderManager2$ComInvoker$1.run(Unknown Source at java.base/java.lang.Thread.run(Unknown Source)

HRESULT=0x80010106 means RPC_E_CHANGED_MODE which I guess means that COM is somehow already initialized in MTA mode. But why is this only an issue in the Windows Bridge sandbox? Does the Windows Bridge somehow pre-initialize COM somehow for some reason?
I'm not sure if this is a Java 9 issue, or a Desktop Bridge issue, or both. Does anybody have any ideas on how to identify the cause of the issue or workaround?
I have made a minimal Sample Project to reproduce the issue
The application works when executed directly, but not when executed via the APPX launcher. Why?
Comment: A possible thread dump would be a better insight and reporting this to open jdk mailing list, bug tracker etc should also help.
Comment: Not sure if these are related, but do take a look at [JDK-8189604](https://bugs.openjdk.java.net/browse/JDK-8189604)
Comment: Can you distill this down to a small test case that reproduces the issue so that it can be attached to https://bugs.openjdk.java.net/browse/JDK-8189938 .
Comment: I have added a test case:
https://github.com/rednoah/JDK-8189938

@AlanBateman Since I don't have an OpenJDK account, maybe you can help me update the bug report with the example application?
Comment: @AlanBateman The issue does not duplicate outside of the APPX container. Running `jar -jar main.jar` works as expected with Java 9.
Comment: `JDK-8189938` as been marked as resolved, without actually being resolved, or looking / running my example project. Not cool.
Comment: @rednoah Did you try accessing the same on [JDK10](http://jdk.java.net/10/)? The issue is marked resolve on the version 10.
Comment: Same issue with `jdk-10-ea+32`. The bug reviewer didn't have the Windows SDK installed and thus couldn't build an APPX package to reproduce the issue.

That particular piece of native code where the exception is thrown didn't change between [Java 8](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/native/sun/windows/ShellFolder2.cpp#l234) and [Java 9](http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/65464a307408/src/java.desktop/windows/native/libawt/windows/ShellFolder2.cpp#l257).
Comment: If I had access to all the Java 9 EA builds than I could narrow down which build introduced the issue, but I can't find them for download anywhere and I couldn't figure out how to build them myself from source.
Comment: I'm using Java 9 at both compile time as well as runtime. The error message indicates that `ant` is using Java 8. You can set the `JAVA_HOME` environment variable to make `ant` use your Java 9 install. You will also need to make sure that `makeappx` is in the `%PATH%`. That's part of the UWP SDK.
Comment: As suggest in bug please try with Java JDK9 b57 version
Comment: Where can I download the `JDK9 b57` release files?
Comment: I would ideally expect @AlanBateman to write up an answer over the plan for resolving this or where can these be tested if already resolved.
Comment: @AlanBateman I'm happy to test new or old JDK builds anytime. Just give me a download link. ;)
Comment: @rednoah JDK 8u151 should work: http://www.oracle.com/technetwork/pt/java/javase/downloads/jdk8-downloads-2133151.html
Comment: @karliwson Yes. Java 8 runs fine, but Swing doesn't correctly render on HiDPI screens, so I need Java 9 / JEP 263.
Answer: Analysis
The JDK parts, that rely on COM being initialized (D3DPipeline, Sound and windows shellfolder access) all follow the same pattern:

the run the code in a separate thread
for this thread CoInitialize is called
at the end of the user level code CoUnitialize is called

This is in line with the documentation the MSDN holds for COM and the analysis is correct, the error indicates, that the COM subsystem is already initialized to be MTA threaded.
So I modified the java launcher (jvm.dll) and inserted
debugging statements into some of the native methods in os_windows.cpp.
I focused on the threading methods. What I found was this:

create_main_thread, create_os_thread, pd_start_thread all
run with COM not yet initialized
the native thread initializer (thread_native_entry) is already
running with COM initialized

I looked more into in _beginthreadex and indeed I finally found a lead
on stackoverflow. That pointed me to the sourcecode of threadex.c,
which is part of the Visual Studio 2013 Express Installation.
There you find, that _beginthreadex does not directly start the
supplied thread function, but runs a library initializer
(_threadstartex) first. Part of this initializer reads:
_ptd->_initapartment = __crtIsPackagedApp();
if (_ptd->_initapartment)
{
    _ptd->_initapartment = _initMTAoncurrentthread();
}

_callthreadstartex();

_crtIsPackagedApp detects via a kernel function if the application is
run as a "PackagedApp" (i.e. AppX package) and if so, then the
RoInitialize function is called, which from my understanding acts like the big
brother of CoInitialize.
Long story short: If your application is build with Visual Studio 2013
and run as a packaged application, you get a broken environment.
It was confirmed, that the working versions of the Oracle JDK were build with VS2010 SP1 and the broken version was build with VS2013SP4.
Workaround
With the above information google finally found a reference, that supports the analysis:
https://blogs.msdn.microsoft.com/vcblog/2016/07/07/using-visual-c-runtime-in-centennial-project/
Quote from that article:

Note that the existing VC++ 12.0 libraries created during the
  Windows 8 timeframe have runtime checks to determine whether the
  app is running under the app container or not. When running
  desktop apps as a packaged app, these checks might limit the
  functionality of the desktop app or cause it to behave like a UWA
  (Universal Windows Application) (limited file system access or
  create thread initializing MTA etc.). We have fixed this behavior
  in the VC++ libraries contained in these framework packages and
  thus removing the modern app limitations from your desktop
  applications.

So I see to options to fix applications, that shall be distributed as AppX packages:

either force the users to have the updates VC++ 12.0 binaries installed (by introducing the dependency cited in the blog post) or
replace the msvcr120.dll that is bundled with Java 9 (and I assume also Java 10) with the fixed version from the update packages

I would go with the second version and I tested this. Starting with a clean up-to-date Windows 10 System, I installed JDK 9.0.4, I cloned the supplied testcase, modified it use the locally installed JRE (not the JDK!) and build the appx package. Running this, I reproduced the problem. I then replaced the msvcr120.dll's in the JRE folder of my systems installation with the one contained in the APPX container from:
https://www.microsoft.com/en-us/download/details.aspx?id=53176
Hint: *.appx are just ZIP files with additional signatures, so you can
just rename them and extract the contents.
I rebuild the testcase and it is working as it should (no COM
initialization errors anymore).


How do you calculate sample variance for the difference between outcomes under two experimental conditions?

Question: Suppose we have a group of volunteers who we each ask to undertake a task under two different conditions. $X_i$ is the outcome for the $i^{th}$ volunteer under the first condition, $Y_i$ the outcome under the second condition. Let $Z$ be the difference between $X$ and $Y$, $Z_i=X_i-Y_i$.
There are two ways to calculate the sample variance of $Z$. One can either do it directly from the $Z_i$, working out
$$\sum_{i=1}^n (Z_i-\bar{Z})^2/(n-1),$$
or one can calculate the sample variances $\sigma_X^2$ and $\sigma_Y^2$ of the two outcome variables and then use $\sigma_X^2+\sigma_Y^2$ as your sample variance for $Z$.
Which should one use? Are there conditions under which one should be used rather than the other, or are there assumptions that are required before either should be used? In general they give different answers, which will have an effect if you for instance use the sample variance of $Z$ in calculating a confidence interval for the mean of $Z$.
Answer: Your formula $\sum_{i=1}^n (Z_i-\bar{Z})^2/(n-1)$ is the correct formula for sample Var(Z).
$Var(Z) = Var(X - Y) = Var(X) + Var(Y) - 2Cov(X,Y)$
Your formula $\sigma_x^2 + \sigma_y^2$ is missing the $-2Cov(X,Y)$ term, and would be correct only if $Cov(X,Y) = 0 $,  i.e., if $X$ and $Y$ were uncorrelated.
Given that $X_i$ and $Y_i$ for a given $i$ correspond to the same individual, it is not surprising that $X$ and $Y$ could be correlated, as is apparently the case in your data.


Azure App Service drops connection with http/2 enabled, no errors

Question: I have an ASP.NET website that's hosted on Azure App Service. There's a particular page that I cannot visit; Azure App Service drops the connection within a second. The logs show that my website returned with a 200 response. With cURL the output is as follows:
<code>* Recv failure: Connection reset by peer
* LibreSSL SSL_read: Connection reset by peer, errno 54
* Failed receiving HTTP2 data: 56(Failure when receiving data from the peer)
* Connection #0 to host my-website.azurewebsites.net left intact
curl: (56) Recv failure: Connection reset by peer
</code>
The problem is related to http/2 as I can request the page using <code>--http1.1</code> just fine. I've so far disabled http/2 on the website and I can now open the page in my browser as well.
Answer: After further investigation I've found that the particular page has a large response header, to the tune of 24k characters. After removing this header, the page loads fine using http/2 as well.


Is creating array with a variable number of elements possible?

Question: Whenever I need to create an array with a number of elements not known until execution time I do this.
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int myArray[n];
for(i = 0; i < n; i++)
    myArray[i] = 0;

However I've been told by 3 people with a PhD in Computer Science not to do it, because "it's not guaranteed to work on every compiler", and that the number of the elements in an array must be known at compile-time. So they do that like this.
int myArray[1000];
int n, i;
printf("Number of elements: ");
scanf("%d, &n);
//we must stop at the n element
for(i = 0; i < n; i++)
    myArray[i] = 0;

Which one should I use? When it's not guaranteed to work? Is it just a memory waste or a need to maintain legacy?
Comment: Neither. Use something like `int * myArray = malloc( n * sizeof *myArray);` and do your cleanup later when finished.
Comment: Use dynamic memory allocation if you want to implement dynamic arrays in C.
Comment: It is completely compiant to the C99 version of the standard. It is called variable length array (VLA). Due to some unknow reason, the commitee made VLAs optional in the current version (C11) - against their established practice of backwards-compatibility at all cost. I'd still recommend to use it. A modern desktop compiler will support it (e.g. gcc and clang). Don't use outdated compilers like MSVC. They have other problems with modern C, too. Sometimes one has to make a cut. WQe don't use horse-cariages either anymore. Or morse emails. Your PhDs should move on
Comment: @clarasoft-it: A VLA is not a dynamically allocated array, but a normal automatic variable.
Comment: Just in case my comment was not clear: Use VLAs, but make sure they will not overflow the stack (as for any other automatic variable!). Use modern compilers, no outdated rubbish from vendors who sell them for some 1k bucks/euros/etc. without going forward.
Answer:
"it's not guaranteed to work on every compiler"

Yes, basically, correct.
The first approach, VLA, variable length array, was a part of C99 standard. However,

in C11, that has been made optional. You better not rely on that feature.
C89 did not have that as a port of the standard. gcc extensions were there, however, to support them.

Quoting C11, chapter §220.127.116.11/p5

[....] If the size is an integer constant expression
  and the element type has a known constant size, the array type is not a variable length
  array type; otherwise, the array type is a variable length array type. (Variable length
  arrays are a conditional feature that implementations need not support; see 22.214.171.124.)

As an alternative approach, you can always use a pointer and dynamic memory allocation like malloc() and family, if you have to rely on run-time values.
Taken together, to answer the question

Is creating array with a variable number of elements possible?

It is possible, but only with VLA support. Without that, you have to sate yourself with a pointer and memory allocation functions, at best.
Comment: @Olaf Sir, thank you for the comments. First of all, I am not against VLAs, I just tried to suggest as _alternative_, as you can see. Secondly, I was trying to specify the compiler supports for each of them. If you think my answer in biased in any way, please suggest changes in wordings or feel free to modify. :)
Comment: Hi Sourav! I stongly disagree with your conclusion not to use VLAs. Just because there's still people using horse-carriages does not mean all motorways shall have a speed-limt of 20 km/h. There are enough modern compilers which do support C99, thus VLAs. Compilers which do not support C99/full C11 likely don't support other features, too in modern C. C seems to be the only alnguage stuck to a 27 year old version just because people refuse to learn something new and request modern featurres from their vendors.
Comment: Dynamic allocation is **not** a replacement for VLAs in general. Not only the functions are not available for most implementations - condidering most implementations are freestanding without the then not required parts of the standard library. Then they are not usable if you need multidimensional arrays, because you need a pointer to VLA for 2D already if you use dynamic allocation..
Comment: @Olaf You're very correct. Replacement, no. Alternative approach, yes. In case, VLAs are not around (not supported), then we have to work around them using pointer and `malloc()`, don't you agree? Also, VLAs are stack-size limited, at least in `gcc`, while `malloc()` is probably more generous. :)
Comment: No, the work-around is to drop support for rubbish (and often expensive) compilers. Might sound harsh, but that is the only way to put them under pressure. WIthout that C will never get out of the C90 depression. Re. stack size: is that different from fixed-size arrays or other variables or recursion? Sorry, but that is no argument against VLAs, but automatic variables in general (which you hopefully agree is pretty nonsense). Btw. the C standard does not mandate using a stack, you can very well allocate automatic variables using dynamic memory allocation. And the size is not compiler-specific
Answer: If you want something that is C89 compliant and doesn't use too much memory, there is a third option which is to allocate memory dynamically:
int n, i;
printf("Number of elements: ");
scanf("%d", &n);
int *myArray = malloc(sizeof(int)*n);   // allocate space for n ints
if (myArray == NULL) {
    perror("malloc failed");
    exit(1);
}
for(i = 0; i < n; i++)
    myArray[i] = 0;

Just be sure to call free on the allocated memory when you're done with it.
Comment: @Sheldon Using dynamic allocation is more portable.  However if your compiler supports variable length arrays and you don't plan on migrating it, it has the advantage of not having to worry about freeing memory that's been allocated.
Comment: @KevinDTimm: `calloc` zeroes all bits. That is identical with the value `0` for integers only. Fine here, but not true for floating point or pointers. (It differs from default initialisers in this aspect, btw.) Just let the compiler figure out how to optimise that, A good compiler might use `memset`/`memclr` or even collapse both part into `calloc`. if that works.
Comment: @dbush I always use pointers and malloc whenever I need to change the size dinamically, in this case I don't. When using MinGW with the c89 compiler flag it works the first way. Why should I use this instead? (what are the "benefits")
Comment: @Olaf - OP has declared an array of int, I'm solving his problem, not the problem of others.  If he wanted a solution to a generic problem, I assume he would have asked.


How to submit a query to Google Dialogflow using Flask

Question: I have the following python script that is connecting to Google Dialogflow using Flask and is using a webhook to retrieve the response from Google Dialogflow.
The limitation is that I currently only enter the query in to the Google Dialogflow frontend, with the result returned here in variable result
However how can I use this same script to submit the query to Google Dialogflow, instead of entering in the front end?
Any help appreciated, thanks!
import json
import os
from flask import Flask
from flask import request
from flask import make_response`

`enter code here # Flask app should start in global layout
app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    req = request.get_json(silent=True, force=True)

    res = processRequest(req)
    res = json.dumps(res, indent=4)
    r = make_response(res)

    r.headers['Content-Type'] = 'application/json'
    return r

def processRequest(req):
    result = req.get("queryResult")
    result_message = result['fulfillmentText']
    print(result_message)

@app.route('/test', methods=['GET'])
def test():
    return "Hello there my friend !!"

if __name__ == '__main__':
    port = int(os.getenv('PORT', 5000))
    app.run(debug=True, port=port, host='0.0.0.0')`

Answer: I discovered shortly after posting this that a webhook is whats known as a reverse API, and only shows results as opposed to two way interactions.


How can I create persistent SSH connection to "stream" commands over a period of time?

Question: Say that I have an application running on one PC that is sending commands via SSH to another PC on the network (both machines running Linux).
For example every time something happens on #1, I want to run a task on #2. In this setup, I have to create SSH connection on every single command.
Is there any simple way to do this with basic unix tools without programming custom client/server application? Basically all I want is to establish a connection over SSH and then send one command after another.
Comment: [Independent *file descriptors* for one or more *SSH* connections.](https://unix.stackexchange.com/a/553028/27653)
Answer: Automatic Persistency Using OpenSSH
You can also use the ControlMaster feature of OpenSSH, which opens a unix domain socket for the first connection and reuses this connection in all subsequent calls.
To enable the feature, you can either use -M as the command line switch or enable the ControlMaster option in your ~/.ssh/ssh_config, e.g.:
ControlMaster auto

Additionally, you should set the ControlPath using the following lines in your ~/.ssh/ssh_config:
Host *
   ControlPath ~/.ssh/master-%r@%h:%p

To maintain a persistent connection to a host, e.g. if you want to run a script which needs to establish many ssh connections to the host, none of which persistent over the whole lifetime of the script, you can start a silent connection in advance using:
ssh -MNf remotehost

Cheerio,
nesono
Comment: I signed into server fault just to +1 vote your answer. Yours worked!
Comment: `ssh -N` starts a session without remote command, seems no corresponding options in ssh_config.
Comment: You may also want to configure `ControlPersist 480m` (adjust time to preference) to keep the connection alive for some time even after the SSH session has ended, to avoid having to re-enter your password/MFA each time.
Answer: Not sure if it can be used in production but you can do something like this:
create file on #1
1> touch /tmp/commands
Then run command:
1> tail -f /tmp/commands | ssh firstname.lastname@example.com
That will open file /tmp/commands and start sending its content to server x.x.x.x (#2) and run it there line by line
now, every time something happens on #1 do:
1> echo "ls -l" >> /tmp/commands
or
1> echo "reboot" >> /tmp/commands
whatever you add to file /tmp/commands will be sent to #2 and executed. Just make sure you do not run anything interactive, or deal with it somehow.
Comment: I'd add that you should use `tail -F`, which will detect that the file has been replaced, so when it gets to be giant you can erase it and start over with a new file.
Comment: @DerfK, alternatively, `mkfifo /tmp/commands` should be a better solution
Comment: This is exactly what I've been looking for, very creative solution :)
Comment: @solotim full sample: [Independent *file descriptors* for one or more *SSH* connections.](https://unix.stackexchange.com/a/553028/27653)
Answer: In /etc/ssh/ssh_config add
# Send keep alive signal to remote sshd
ServerAliveInterval 60

Answer: If you run into this sort of thing a lot, try Parallel. It is like dsh (distributed shell) but has some neat features like counting semaphores and it is actively maintained.
From the documentation:
EXAMPLE: GNU Parallel as queue system/batch manager
GNU Parallel can work as a simple job queue system or batch manager. The idea is to put the jobs into a file and have GNU Parallel read from that continuously. As GNU Parallel will stop at end of file we use tail to continue reading:
echo >jobqueue; tail -f jobqueue | parallel

To submit your jobs to the queue:
echo my_command my_arg >> jobqueue

You can of course use -S to distribute the jobs to remote computers:
echo >jobqueue; tail -f jobqueue | parallel -S ..

There are many great examples that just scratch the surface. Here is a cool one.
EXAMPLE: Distributing work to local and remote computers
Convert *.mp3 to *.ogg running one process per CPU core on local computer and server2:
  parallel --trc {.}.ogg -j+0 -S server2,: \
  'mpg321 -w - {} | oggenc -q0 - -o {.}.ogg' ::: *.mp3

Answer: yes it is possible with a pipe:
echo 'echo "hi"' | ssh -i my_private_key tester@host2

this will execute the command echo "hi" on host2
you just have to write a programm, that just gives out the commands ( don't forget the ; ) and then pipe that output to ssh
Answer: You might want to use program like dsh (Distributed SHell) that is made to do just that :), After configuring it with host names and setting up publickeya auth, you can use it to run commands on multiple machines either in series ("run on machine a then run on machine b") or in pararell ("run on all machines on same time").
Or just make script
#!/bin/sh
ssh machine -- $@
exec $@

Answer: DISCLAIMER: I can't test this right now, as I'm on a windows machine with bash but without ssh.
In a bash script, you can do something like this:
exec 4> >(ssh --ssh-options-here user@host)

And then to send commands, write them to FD 4.
echo 'echo hi' >&4

If you do it this way, you can't access the results of the commands easily, but based on your question it doesn't seem like you need to.


How to perform a likelihood ratio test in a new dataset?

Question: I understood the purpose of likelihood ratio test. However, I am confused by the table below from a published investigation. Clearly the author compare a nested model (VMNS) and a full model (VMNS + tumor differentiation) in C-index, and likelihood ratio test chi square.
Now the question is:

I know how to do a likelihood test for two nested models in the training set in R like, anova(coxph1,coxph2), but how can I do it in the validation set? Does the following code right? (though I thought it's wrong...)?
coxph1 <- coxph(Surv(time,status) ~ age, data = datatrain)
coxph2 <- coxph(Surv(time,status) ~ smoke + age, data = datatrain)
pred1 <- predict(coxph1,newdata = datatest)
pred2 <- predict(coxph2,newdata = datatest)
coxph1.test <- coxph(Surv(time,status) ~ pred1, data = datatest)
coxph2.test <- coxph(Surv(time,status) ~ pred2, data = datatest)
anova(coxph1.test,coxph2.test)

Is there a function to test C-index for cox model in R (third colum in the table)?
Comment: Please add a link to the publication from which you got this table. The original publication might contain hints about how these particular authors did these comparisons, which will help provide an answer to your question.
Comment: Thx for your advice. Here is the link "https://pubmed.ncbi.nlm.nih.gov/34515782/". I believe all statements related were located at the last sentence of the first paragraph of Statistical Analysis
Answer: As best as I can tell from the linked publication, the models based on the training set were applied, with the same regression coefficients, to the data in the internal and external validation sets.
The problem with your proposed approach is that the coxph() function will try to re-fit models to pred1 and pred2 on the new data. You would get a new regression coefficient for each model, a slope for how each of pred1 and pred2 is associated with log hazard in the new data set. That's useful in some contexts; for example, it's how the validate() function in Harrell's rms package evaluates the optimism in a model. But that's not what you want.
The trick with likelihoods based on a model with pre-defined regression coefficients is to recognize that you just want to evaluate the (partial) likelihood of the data, given that model. AdamO shows, with code, a very simple way to do this with Cox models:

If you simply want the partial likelihood, why not fool R into giving it to you? Simply initialize beta and allow no iterations, then extract the loglik value from the coxph object.

I don't know if that's precisely how the authors of this study did this, but that's the basic idea. An alternative might be to use offset(pred1) and offset(pred2) to force their regression coefficients to be exactly 1, then extract the log likelihoods.
For the C-index calculations, the authors say that they used tools in the compareC package. I don't have experience with that package. The basic R survival package has a concordance() function that can evaluate the C-index for a model applied to new data.
A few warnings.
First, as the authors note, even Harrell doesn't find the C-index useful for comparisons among models. It's a good measure of discrimination for a single model.
Second, a split into training and validation sets isn't the most efficient use of data when there are so few cases. See this post, for example. Resampling from a combined data set is generally better unless there are tens of thousands of cases.
Third, the authors' use of LASSO might have found a set of predictors that work OK, but the same procedure applied to a new data set might well find a different set of predictors. It's not clear that the authors' use of bootstrapping evaluated the entire model-building process including the LASSO predictor selection. That's another advantage of a full resampling-based validation of the model-building process in this situation.

How to perform a likelihood ratio test in a new dataset？


Counting the number of possibilities to build a vector of length 20

Question: I'm trying to count all the vectors of length $20$ that contains $i$ times the number $i$ and $j$ times the number $j$ where $i,j\in\{1,...,6\}$. The vector can contain any number in the set $\{1,...,6\}$.
The solution in my book: We will choose $i$ places out of $20$ where we will place the number $i$ in $20 \choose i$. Also we will choose $j$ places out of $20-i$ where we will put $j$ in $20-i \choose j$. In other $20-i-j$ places we have the other $\{1,...,6\}\backslash\{i,j\}$ numbers. So the result is:
$$
{20 \choose i}{20-i \choose j}
$$
I don't understand why they did not continue counting the number of possibilities to place the other numbers  $\{1,...,6\}\backslash\{i,j\}$. They only counted the number of possibilities to place $i$ and $j$. What about the rest? I will be glad to have an explanation.
Comment: Not sure the rules are clear.  $1+2+3+4+5+6=21$  so you can't pass your test for all $i\in \{1,2,3,4,5,6\}$.  Are you saying that you want this condition met for exactly two of those six digits?  At least two?  Something else?
Comment: @lulu only two of those digits fulfil this condition. For example, $5$ and $6$. So $5$ will be placed $5$ times and $6$ will be placed $6$. Other $\{1,2,3,4\}$ will be in the other $20-6-5=9$ places (does not matter how).
Comment: Are $i,j$ specified in advance?
Comment: @lulu No, we just know that $i\neq j$.
Comment: but then your answer should sum over the choices $i,j$...and you have to subtract the cases that are multiply counted.
Answer: As the question is written, the other $20-i-j$ places have four choices each (anything except $i$ and $j$), so the book solution should be  multiplied by $4^{20-i-j}$


Step in proof that product of compact spaces is compact

Question: Many proofs of the fact that the product of compact spaces use the tube lemma, and therefore start somewhat like this:
Let $X$ and $Y$ be compact spaces. Then for each $x\in X$, $\{x\}\times Y$ can be covered by finitely many open sets.
Why is this true? I understand intuitively but am having a hard time rigorously justifying this.
Comment: Let O be open in X and U be open in Y. Then O X U is open in X x Y. Now Y can be covered by finitely many sets W because it is compact. Let x in O an open set in X. Then {x} X Y can be covered by a finitely many O X W.
Comment: For proof: https://en.m.wikipedia.org/wiki/Tychonoff's_theorem
Answer: Consider how the topology of $\{x\}\times Y$ is defined, and you will see that $f(p)=(x,p)$, for $p\in Y,$ is a homeomorphism from $Y$ to $\{x\}\times Y.$ Compactness is a topological property, that is, it is preserved by homeomorphism. And $Y$ is compact, so $\{x\}\times Y$ is compact.
Answer: The subspace $\{x\}\times Y$ is homeomorphic to $Y$, which is compact by assumption. Compactness is a topological property, meaning if $X\cong Y$ and $X$ is compact, then $Y$ is compact as well.


Const char * allowing to change the character value, why?

Question: I have this code
int main()
{
    char A = 'E';

    const char * i;

    i = &A;

    A = 'B';

}

which actually compiles with MSVC, why?
Isn't a const char * supposed to point to a constant character variable? Why can I change A to 'B' in the last line?
Am I missing something?
Comment: You're not using a `const char *` on the last line.
Answer: There is a difference between a constant of type char being pointed to (a.k.a. the pointee) and a constant pointer of type char*. If you want to protect a pointer from (accidental) modification, you can declare it constant:
char* p = '...';
char* const cp = 'Hello, World!'; // a constant pointer
cp[1] = ','; // okay, the pointee is not constant
cp = p;      // error, the pointer is constant

A variable pointer to a constant can change:
char *p = '...';
const char* pc = 'Hello, World!'; // pointer to a constant
pc[1] = ','; // error, the pointee is constant
pc = p;      // okay

And finally, you can declare a constant pointer to a constant with
const char* const cpc = 'Hello, World!';
cpc[1] = 'a'; // error, pointee cannot change
cpc = p;      // error, pointer cannot change

This is from §5.4.1 of "The C++ Programming Language", Stroustrup.
You can change A to 'B' in the last line, because A is of type char and therefore can be changed. It isn't declared a const char, which would prevent you from doing so.
Answer: A const char* only prevents you from modifying the pointed-to variable through that pointer. It does not, and indeed, cannot, ever, prevent you from modifying it through other means. const pointers and references would be of little use if they could only point or refer to const values.
Answer: const char* implies that you can't modify the pointee through this pointer. That doesn't mean someone else won't be able to do it.


Is there this integers

Question: Given an integer n, show that an integer can always be found which contains only the digits 0 and 1 (in the base 10 notation) and which is divisible by n.
How to solving this problem?
Comment: http://math.stackexchange.com/questions/233746/existance-of-multiple-of-n-with-only-0-and-1-as-its-digits
Answer: Let be $n=2^r\cdot3^s\cdot5^tm$. Let be $u=\max(r,t)$. Let be $k=3^{s+2}m$.
Consider the number $$N=\frac{10^{\phi(k)}-1}9\cdot10^u$$were $\phi$ is the totient function.  We'll show that $N$ is multiple of $n$ and that its digits are $0$ and $1$.
Euler's theorem tells us that $10^{\phi(k)}-1$ is multiple of $k=3^{s+2}m$. Hence, $(10^{\phi(k)}-1)/9$ is multiple of $3^sm$ and $N$ is clearly multiple of $n$.
The decimal representation of $N$ has $\phi(k)$ $1$'s and $u$ $0$'s, which completes the proof.

Is there this integers