VMWare Workstation virtual vs physical disk?

Question: I recently started playing with VM and saw that I have 2 options when creating a VM, I can use a Virtual Disk or a Physical Disk.
I belive using the physical disk would be faster and better and I would like to confirm if this is true ?
Another thing I was wondering is if I have to make the partitions myself of if the VMWare will do it for me ?
For example if I have a 500GB disk that has 400 being used by the host OS so I have 100 spare size would it let me repartition those 100 or it would either ask for the entire 100 or for me to point an already created partition to be used ?
Comment: @Chris it is not a worry, it is an interest to know my options, and if they will reflect on later, the computer i am using for VM inst a very good machine, would say it is a bellow average one but if there are points that i can maximize the use of its resource i don't see why not to ask and learn about the options avaiable.
Comment: If you need to move the VM to another machine then the virtual disk is the way to go.
Comment: I dont need to move it anywhere it is just a test host running test VMs for learning tha can be wiped clean anytime.
Comment: then don't worry about the physical disk feature. It's for a few specific situations and not relevant for your usage.
Answer: We need to clarify here as there are two types of 'physical' disks referred to in a VMWare world. The first is where a virtual drive is defined within a single VM as being physical to allow for multiple VMs to access it simultaneously, these are often Raw Device Mappings to genuinely physical disks or SAN LUNs to allow for things like MS Clustering to work (i.e. where you put your Quorum and MSDTC volumes). The other type is really a hold-over from a physical-to-virtual (P2V) conversion of a legacy server/PC. VMWare kindly offer for you to simply mount a real physical drive on the host and pass it directly through to a VM for exclusive VM-to-disk use. This has sped up many complex conversions but is really only a stop-gap until admins have properly converted the drive over to a virtual one.
For both cases VMWare is not able to snapshot these disks.
It seems pointless to repartiion your host drive or to use the first physical disk option unless you actually need that functionality. What I'd suggest is that you simply let VMWare Workstation create virtual disks for you in the existing partition, this will be the simplest solution and will allow you to concentrate on learning other aspects of the software - perhaps coming back to this area later. That said if you're particularly concernted about VM performance I'd highly recommend putting your VMs on a second disk or array, but not in a separate partition of your existing disk. Oh and VMWare wouldn't repartition anyway, it's not what it does.
Hope this helps, feel free to come back with any follow up questions you may have.
Comment: +1 yes it does help and you actually pointed out some extra interesting information i was not aware of. I am no expert in VM in any way or was planning to become one but i felt that i need some extra knowledge about it to know that i was really doing it the right way. Once again thanks for you nice reply.
Comment: My pleasure, it's questions like yours that this site thrives on.
Comment: :P don't worry i am sure I will bring some nice questions along my learning curve from what I am currently doing... or so I hope... hehehe
Answer: You may run into problems, like driver issues or booting issues!
http://www.vmware.com/support/ws55/doc/ws_disk_dualboot_scsi_issues.html
I have yet to actually try this, but most would use a physical disk as a storage disk for the virtual machine. If it's for the OS then you will get the same or maybe better performance by running it as a virtual disk. I have actually seen a higher disk performance score in the Windows Experience index on a virtual machine, as opposed to the host OS index score...
If the 100GB is an unpartitioned (raw) part of the disk, then yes Vmware would partition it for you. If it's just unused space on your primary partition then you would need to shrink your main partition down to 400 and have the 100GB as raw.
If it were me, I would format that 100GB partition as an area to store the VM files and virtual disks.
Definitely read up on it before trying it.
Hope that helps
Comment: +1 I actually meant to say partition A using 400GB and rest of disk 100GB unpartitioned. thanks for the reply, i guess for now i will stick to virtual disk since i just began with it and still learning and maybe later move if i see that it is worthed to...


How do I save an HTML element(s) to a jQuery object?

Question: I'm trying to add another one of these on an image click:

    @Html.DropDownList("role", DSS.WebUI.Helpers.CustomHelpers.SelectListItemsForRole(Model.ExistingRoles, role))

And here I'm trying to create a new .roleoption whenever the add image is clicked:

The MVC3 code you see up there, generates the following script on View render:

I get the following error:

Could not convert JavaScript argument arg 0
  [nsIDOMDocumentFragment.appendChild]

How can I make this work and how can I clean up this code?
I think the issue lies in the fact that my HTML helper return the select element as multilines, how can I workaround this fact?
Edit:
If I do:
var $selectList = $(' @Html.DropDownList("role", DSS.WebUI.Helpers.CustomHelpers.SelectListItemsForRole(Model.ExistingRoles, 1)) ');

I get:
    $(document).ready(function () {
        var $roleOption = '

';
        var $selectList = $(' <select id="role" name="role"><option selected="selected" value="1">Anonimo</option>
<option value="2">Registrado</option>
<option value="3">Tecnico</option>
<option value="4">Empresario</option>
<option value="5">Editor</option>
<option value="6">Financias</option>
<option value="7">Administrador</option>
</select> ');
        $($roleOption).append($selectList);

        $('img.add-role').click(function() {
            $(this).parent().append($roleOption);
        });
    });

Answer: I believe you are correct that the error is due to the line breaks returned by the server-side code because the resulting JavaScript is invalid since you can't have line breaks in a string literal like that. You need to remove those line breaks on the server-side. I'm not sure of the exact syntax, but something like this:
var $selectList = '@Html.DropDownList("role", DSS.WebUI.Helpers.CustomHelpers.SelectListItemsForRole(Model.ExistingRoles, 1)).Replace("\n","")';

You may need to chain an extra .Replace("\r","") after the first replace. And you may need a .ToString() before the first .Replace().
Beyond that though I think you have another problem because I suspect the following code isn't doing quite what you think it is:
$($roleOption).append($selectList);
$('img.add-role').click(function() {
    $(this).parent().append($roleOption);
});

The $roleOption and $selectList variables are both strings. When you do this:
$($roleOption).append($selectList);

jQuery will parse $roleOption to create a new jQuery object and then append the $selectList to that object, but you don't actually save a reference to the resulting object in a variable at all. So then within the .click handler when you append $roleOption it is just appending the original string. Probably you meant to do this:
$roleOption = $($roleOption).append($selectList);

Answer: You should be able to wrap $() around the html and it will be parsed by jQuery.  I don't know exactly how MVC3 plays with this, but I would try:
var $selectList = $(' @Html.DropDownList("role", DSS.WebUI.Helpers.CustomHelpers.SelectListItemsForRole(Model.ExistingRoles, 1)).Replace("\n", "") ');

Edit:  Due to the fact that @Html.DropDownList() returns multiple lines, you would need to remove them by adding .Replace("\n", "").  I think.
Comment: `could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]` - Do you have a link to the documentation on that specific jQuery fuction. Maybe I have to wrap my HTML output with strings.
Comment: Ok, added the quotes inside the jQuery wrapper and the issue still stands. I highly suspect it's the multiline HTML that's generate that confuses the javascript engine. What can I do to workaround this? Any suggestion is very welcome.
Comment: What is the output of the MVC3 render with my latest edit (single quotes)?
Comment: Argh, I forgot that javascript doesn't play nice with multi-line strings... hmm.
Comment: Can you do a `.Replace("\n", "")` on your MVC code as I did in my edit?


Valid method for analysing if positive association between giving a drug and increasing ordinal scores

Question: I have a set of ordinal scale scores for a group of patients before and after an intervention (drug). I was wondering what would be a valid statistical method for analysing if there was a positive association between administration of the intervention and increasing ordinal scale scores. The number of scores before and after the administration of the intervention are never equal in my data set because it was not a controlled study. The ordinal scale used is a 62-item scale. Image is of example results from two patients to better describe the data - I have data for 14 patients in total.
Comment: Welcome to Cross Validated. The first step should be inspection of a simple plot of the values. Make a graph with date as the x-axis and  score as the y-axis. Look to see if there is are any obvious patterns in the data.
The relationship between dose and effect is very reliable with drugs. Do you have information regarding the doses?
Comment: This is the wrong research design to conclude much about the drug - you really want a control group.
Comment: @MichaelLew, thank you for your response, it's very much appreciated. I have information regarding doses, however I would just like to know whether there is a difference before and after drug administration so as to keep things as simple as possible. The scatter graph showed no obvious patterns. Would taking two medians for each patient (one median for scores before drug administration, and one median for scores after drug administration) and then doing a sign test on the differences between medians be a valid method? Thanks again
Comment: @Bjorn, thank you for your response - agreed. It's a study to see if there is any association between prescribing of these drugs and improved scores in clinical practice. The drugs are used off-label with little evidence to support prescribing. We wanted to follow our patients who were prescribed these drugs to see if there is improvement in formal assessment scores. The study is not capable of proving causation but we at least wanted to see if there was any sort of positive association. Ideally I would have liked an A-B-A design with patients being their own control but this was not possible.
Answer: Given the comments, it sounds like you are at a very preliminary stage of research on the topic and an exploratory approach would therefore be sensible. Do not be put off by that fact that the data are not from an ideal study. See what the data can tell you.
You are looking for a possibly small signal in fairly noisy data that has variability in the number of observations per patient and per condition. That means that your inferences will have to be quite cautious, and the outcomes can, at best, point to areas for further investigation.
Try plotting the averages of before treatment and during treatment (I'd look at means and at medians). Join the dots within patient and see if the  differences are at all consistent.
You could, perhaps, treat the several measurements in each patient as technical replicates and therefore take an averages for each patient (before and during) and perform a paired t-test (or a permuations test) on the averages. (Treat the results with caution.) A more sophisticated analysis that weights averages with lots of values more heavily than averages with few values, but that is beyond my capability.
Comment: Thank you @MichaelLew. Your advice was very helpful.


How to find the Number of tries to get a value greater than 4 tossing a fair die

Question: You've decided to repeatedly toss a fair six-sided die. Let's make the reasonable assumption that tosses are independent.
On average, how many tosses does it take until you see a number larger than four?
I have seen a few solution of the kind here, but not able to understand why do I need a probability distribution curve or average.
Let's say I get a value greater than 4 in nth attempt, will the probability not be 2/6n.
Since E is 2 and S 6xn.
Can I not equate this with sum of a gp with n terms?
Comment: The probability you first get more then $4$ on the $n$th throw is the probability you get $4$ or less on the first $n-1$ throws times the probability you get more than $4$ on the next throw, which is $\left(\frac46\right)^{n-1}\times \frac26$
Answer: I will give it a try. There are several ways to approach this problem. You indicate something with series, so I will use that.  You need Expectation for this.If you get more than $4$ in one go, than "contributes" in the Expectation as $(1)(\frac{2}{3})^0\frac{1}{3}$. First throw 4 or below, second throw more than 4 contributes as $(2)(\frac{2}{3})^1\frac{1}{3}$. First two throws 4 or below, third throw more than 4 contributes as $(3)(\frac{2}{3})^2\frac{1}{3}$. So if you factor out $\frac{1}{3}$ and use $x=\frac{2}{3}$, then essentially we are interested in the series $\frac{1}{3}(1+2x+3x^2+4x^3+...)$. We recognize the derivative of the geometric series here. The geometric series is $\frac{1}{1-x}=1+x+x^2+x^3+...$ and thus derivative is $\frac{1}{(1-x)^2}=1+2x+3x^3+...$. For $x=\frac{2}{3}$ this yields $9$, subject to $\frac{1}{3}$ gives $3$. So the expectation would be $3$ throws. If this is not what you are looking for, I can take it off.
Comment: Why n is being multiplied to get the expectation? Why 1x2+2x2+3x3+.... why coefficient is 1,2,3 and so on. (Typing from mobile.)
Comment: It's the formula for expectation. $n$ stands for the number of throws and each $n$ is multiplied by its corresponding probability
Answer: So you have a sequence of trials which independent and identical success rate $2/6$, and you wish to find the expected count of trials until the first success.
Thus the count has a Geometric$_1$ Distribution.   There are several ways to derive the expected value of a Geometric$_1$ Distribution, but the result is well known.
The easiest way is to use the Law of Total Expectation, and the fact that if we make it to the second trial the "experiment" resets with one trial done. [Called the "memmoryless" property.]
$$\begin{align}\mathsf E(X)~=~&\tfrac 46~\mathsf E(X\mid X>1) + \tfrac 26~\mathsf E(X\mid X=1) \\ =~& \tfrac 23(1+\mathsf E(X))+\tfrac 13 \\~\\ \therefore \mathsf E(X)~=~&3\end{align}$$
Answer: Here is another perhaps a bit "unusual" approach: Recursion. Let $n$ be the expected number of throws for success (throwing greater than 4). On any given moment, the probability having greater than 4 is of course $1/3$. But if you fail $(2/3)$, you are back to square one and you have to throw again. So if you have already failed, say $n$ times, to fail another time, you will throw $n+1$ times so that is $(2/3)(n+1)$. Now the important step comes: Recursion: The expected number of throws for success is then $n=(1/3)(1)+(2/3)(n+1)$. First component is for success, second component for fail. From here $n$ can be solved. Verify that it follows $n=3$
Comment: So it means £(probability*number of throws) = total number of throws ? (Sorry no math symbols available)
Comment: Right hand side is not purely probability, its is expectation: $E(X)=\sum(X)P(X=x)$


Shake animation não para?

Question: Eu tenho um problema com o shake animation, uma vez que ele começa, não consigo fazê-lo parar
var shakeit = null;
function abre(a){
    clearInterval(shakeit);
}
function fecha(){
    var shakeit = setInterval(function(){
        $(".left_noti2").effect("shake",{direction:"up", distance:"5", times: "2"});
    }, 3000);
}

Uma vez que eu carregue no botão para fechar a div, eu gostaria que o botão ela tivesse o efeito shake, mas mal abrisse de novo, gostaria que ela (função) parasse, mas o código que tenho não está a resultar, existe alguma solução?
Answer: O erro está na linha var shakeit = setInterval(function(){, onde você está definindo uma variável shakeit dentro do escopo da função fecha(), sendo assim a função abre() não tem acesso.
Segue o trecho funcionando:

var shakeit = null;

function abre() {
  clearInterval(shakeit);
}

function fecha() {
  shakeit = setInterval(function() {
    $(".left_noti2").effect("shake", {
      direction: "up",
      distance: "5",
      times: "2"
    });
  }, 3000);
}

$('#btnAbre').click(function() {
  abre();
});

$('#btnFecha').click(function() {
  fecha();
});
.left_noti2 {
  width: 200px;
  height: 200px;
  background-color: blue;
}

<button type="button" id="btnAbre">Parar</button>
<button type="button" id="btnFecha">Agitar</button>

Shake animation não para?


How to have a table with very huge data as a data source to Tableau

Question: I have a situation in which I need to make a table (having  up to 20 million rows) as a data source to Tableau.
Will Table partitioning work or any other method to try as I must have all the data in this particular table only?
Please assist.
Comment: You can connect a table that large to Tableau. I have used 300 million row Vertica tables before. Take an extract to improve performance.
Comment: Hi, Thank you so much for the reply here. However, my table is taking around 20 minutes to return the data. So if in this pattern, my extract will take too long to refresh. Please suggest.
Answer: Please optimize your extract based on performance checklist is followed and also optimize the extract as much as possible.
https://www.interworks.com/blog/bfair/2015/02/23/tableau-performance-checklist
Or
https://www.interworks.com/sites/default/files/InterWorks%27%20Tableau%20Performance%20Checklist.pdf
OR
http://onlinehelp.tableau.com/current/pro/desktop/en-us/extracting_optimize.html
OR
https://docs.powertoolsfortableau.com/best-practices-analyzer/#understanding-the-rules


How to display a custom block in a view?

Question: I created a custom block "Share". This one is not displayed on any page.
I installed the "Twig Tweak" module.
How to display a custom block in a view ?
Answer: If you want to add it to the header or the footer, edit your view, and in the middle column next to header or footer click add and then select Rendered entity - Custom block

When adding the block, just use the block ID (that can be found in the block's URL - in the image you uploaded your block ID would be 103)

Make sure these options are checked / filled in.


Same view on navigation in ios6

Question: In my application i use the following code to navigate to a new view on receiving a click, It is working properly on iOS5. However, When i try with ios6 it is showing the current view and Is not goin to the next view. Do i need to change anything for ios6 in this code.
please help me to solve.
<code>scoreview *sview=[[scoreview alloc]  initWithNibName:@"scoreview" bundle:nil];
[self.navigationController pushViewController:sview animated:YES];
</code>
Comment: In iOS6, Have you test to see if self.naviationController == nil ?
Comment: @VinceBurn can you make clear what you asking
Comment: NSLog (@"self.navigationController == %@", self.navigationController); When there in no push what's the result of this?
Comment: just check [self.navigationController presentViewController:sview animated:YES completion:nil];
Comment: @VinceBurn this is is the result `self.navigationController == `
Comment: @Rose this is output `Warning: Attempt to present  on  whose view is not in the window hierarchy!`
Comment: where are u calling this method??
Comment: 2 Questions : scoreview is a subclass of UIViewController? How are you putting your UINavigationController in your Window? iOS 6 is more touchy than iOS 5 about that.
Comment: @VinceBurn yes Scoreview is  subclass of UIViewController,i initialise  Uinavigationcontroller in appdelegate file itself
Comment: @Rose when score button clicks i call that method
Comment: not where, how do you add it?
Comment: @Fazil:check this link:http://stackoverflow.com/questions/11748845/present-more-than-one-modalview-in-appdelegate
Comment: @VinceBurn  `navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];` in appdelgate file
Answer: Try these lines:
<code> scoreview *sview=[[scoreview alloc]  initWithNibName:@"scoreview" bundle:[NSBundle mainBundle]];

[self.navigationController pushViewController:sview animated:YES];
</code>
Answer: Can you please check your view is Correctly connected with UIInterfaceBuilder

Same view on navigation in ios6


React Native image cropping with multi picker and permission handling

Question: I'm working on an application that is based on image processing. I need to select multiple images from the picker at the same time and show them in the view container, where first it will ask for permission then pick images from the gallery or camera. I also need a cropping feature in it to crop the image. Something like the utility class of image selection supports all the options needed for the application. I'm using the following code
<code>class App extends Component {

  state = {
    image: Images.placeholderImage
  }

  onPress = () => {
    // Here goes the picker code
  }

 render() {
    return (
      <View>
        <View>
          <Image source={this.state.image} style={{width:200, height:200}}/>
        </View>
        <TouchableOpacity onPress={this.onPress}>
          <Text>Select Image</Text>
        </TouchableOpacity>
      </View>
    )
  }
}
</code>
Answer: Go to Simulator > Device > Erase All Content and Settings
worked for me in iOS


transpose double[][] matrix with a java function?

Question: Do anybody have a function with which I can transpose a Matrix in Java which has the following form:
double[][]

I have function like this:
public static double[][] transposeMatrix(double [][] m){
    for (int i = 0; i < m.length; i++) {
        for (int j = i+1; j < m[0].length; j++) {
            double temp = m[i][j];
            m[i][j] = m[j][i];
            m[j][i] = temp;
        }
    }

    return m;
}

but its wrong somewhere.
Comment: Make a attempt then ask
Comment: `for (int j = i+1; ...` => `for (int j = 0; ...)` - also you don't need to return m, the caller already has a reference to it.
Comment: @Pshemo This one got closed a little too fast it seems...
Comment: @assylias Yes, it was closed before OP posted his attempt. I voted to reopen it after that.
Comment: @gurehbgui What are you trying to do? If you are trying to change positions of elements in "square" matrix then your code works correctly. If you want to transpose non square matrix lets say {{1,2,3},{4,5,6}} into {{1,4},{2,5},{3,6}} you will have to create and return new array because you cant add/delete rows to already existing array.
Comment: Please refer to my solution using Apache library
Answer:     public static double[][] transposeMatrix(double [][] m){
        double[][] temp = new double[m[0].length][m.length];
        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m[0].length; j++)
                temp[j][i] = m[i][j];
        return temp;
    }

Comment: Shouldn't you check that `m[0]` does not result in an `IndexOutOfBoundsException`?
Comment: This code works perfectly, if you don't mess up rows with columns. [m[0].length] represents the size of the row in a newly created matrix, and [m.length] the column. So transposed matrix is created oppositely to the intuition. First it takes the size of the "old" column and then the size of the "old" row: `double[][] temp = new double[columnSize][rowSize];`
Answer: If you would like to use an external library, Apache Commons Math provides the utility to transpose a matrix. Please refer to it official site.
First, you have to create a double array double[][] arr, as you have already done. Then, the transposed 2d matrix can be achieved like this
MatrixUtils.createRealMatrix(arr).transpose().getData()

Answer: Since Java 8, you can do this:
public static double[][] transposeMatrix(final double[][] matrix) {

    return IntStream.range(0, matrix[0].length)
        .mapToObj(i -> Stream.of(matrix).mapToDouble(row -> row[i]).toArray())
        .toArray(double[][]::new);
}

Answer: Here is a code to transpose a two dimensional matrix "In Place" (not using another data structure to save output) and hence is more memory efficient:
Same below algorithm can be used for int or char or string data types as well.
  public static double[][] transposeDoubleMatrix(double[][] matrix) {
        int n = matrix.length;
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                double tmp = matrix[j][i];
                matrix[j][i] = matrix[i][j];
                matrix[i][j] = tmp;
            }
        }
        return matrix;
    }

Answer: Java Class to Transpose a matrix :-
import java.util.Scanner;

public class Transpose {

    /**
     * @param args
     */

    static int col;
    static int row;
    static int[][] trans_arr = new int[col][row];

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        col = m;
        int n = sc.nextInt();
        row = n;

        int[][] arr = new int[row][col];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                arr[i][j] = sc.nextInt();
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        int[][] trans_arr = new int[col][row];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                trans_arr[j][i] = arr[i][j];
            }
        }
        for (int i = 0; i < col; i++) {
            for (int j = 0; j < row; j++) {
                System.out.print(trans_arr[i][j] + " ");

            }
            System.out.println();
        }

    }

}

Answer: Here is the method
public static double[][] transpose(double arr[][]){
    int m = arr.length;
    int n = arr[0].length;
    double ret[][] = new double[n][m];

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            ret[j][i] = arr[i][j];
        }
    }

    return ret;
}

Answer: Here's a small change!
for (int j = i; j < m[0].length; j++)

Comment: Hi, I see that you are new contributor to the site, could you please explain so it is not just a line of code. Thanks!


How to use Vector and Comparable Interface

Question: I did
public class Employee implements Comparable <Object> {
    public int compareTo (Object other ){

i did the implementation well (it works fine) and calles it from other class:
import java.util.Vector;

public class Firm {

    private Vector <Employee> employees = new Vector<Employee>();

and using in the same class (Firm) Comperator Vector in function :
public void SortVector(Vector <Comparable> vector) {

and calls it with:
SortEmployeesBy(this.employees); ////Error is here

and in this line the compiler said:

The method SortVector(Vector) in the type Firm is not applicable for the arguments (Vector)"

Note: i required to use only vector and need to use SortVector several times so that i need to use the comparator because i have many vector and other classes like Employee, customer, Artist... tha each has own implementation for Comparable
why is that, and how to fix it?
Comment: For completeness' sake: Are you aware of [`Collections.sort`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List))?
Comment: i required using only vector, my friend
Comment: By whom? Is this a school assignment? `Vector` shouldn't be used in new code.
Answer: Try any one
public void SortEmployeesBy(Vector<? extends Comparable<Object>> vector) {..}
public void SortEmployeesBy(Vector<Employee> vector) {...}

instead of using
public void SortEmployeesBy(Vector<Comparable> vector) {...}

--EDIT--
You can try with Firm class making it parametrized as shown below to make it more generic.
class Firm<T extends Comparable<Object>> {

    private Vector<T> employees = new Vector<T>();

    public void SortEmployeesBy(Vector<T> vector) {...}
}

Firm<Employee> f = new Firm<Employee>();


Inequality between differential quotient and Sobolev norm

Question: I was looking at the question whether
$$ \int_{\mathbb{R}^N} \left|f(x+h)-f(x)\right|^p dx \leq \left( |h| \cdot \left\Vert f\right\Vert_{W^{1,p}(\Omega)} \right)^p $$
holds for a function $f\in W^{1,p}(\Omega)$ for $1\leq p < \infty$. In Evans' book on PDE, chapter 5 on Sobolev spaces, difference quotients are defined in section 5.8.2. Then follows theorem 3:

$(i)$ Suppose $1\leq p < \infty$ and $u\in W^{1,p}(U)$. Then for each $V\subset \subset U$
  $$\left\Vert D^hu\right\Vert_{L^{p}(V)} \leq C \left\Vert Du\right\Vert_{L^{p}(U)} $$
  for some constant $C$ and $0<|h| < \frac{1}{2} \text{dist}(V,\partial U)$.

I am pretty sure that there is no neead to assume the bound on $h$ and $V\subset\subset U$.
My question for this post is: Can I use the above theorem to prove my initial statement?
Answer: If $f\in W^{1,p}(\Omega)$, then you cannot write $\int_{\mathbb{R}^N} \left|f(x+h)-f(x)\right|^p dx$ since $f$ is not defined outside $\Omega$.
Instead of $\mathbb{R}^N$ you can use the set
$$\Omega_h=\{x\in\Omega:\, x+th\in\Omega\text{ for all }t\in [0,1]\}.$$
You need the segment to be contained in $\Omega$ because the proof relies on the fundamental theorem of calculus along that segment. This is why Evans was restricting to the sets $U$ and $V$, to make sure $x+h$ stays inside $\Omega$.
PS: Extending $f$ to be zero outside $\Omega$ will not do because you will lose the property that $f$ is a Sobolev function and won't be able to use the FTC.


"Dependency" definition

Question: Origin Lab has in their fitting parameter's statistics "Dependency". Each parameter has a dependency. It's not like the covariance between 2 parameters. I thought it could be defined from all the covariances of the parameter with the others (i.e. with the covariance matrix) but I couldn't find any documentation.
I don't know if it's a general concept because I have zero knowledge in statistics. The main goal it's to implement it on Python, so if the definition is not trivial (e.g. aritmethic expressions), I would appreciate a function that can compute it.
Comment: Not a waste of time -- I learned something.
Comment: It is not a general concept.  A [tiny bit of Googling](https://www.google.com/search?client=firefox-b-1-d&q=origin+lab+parameter+dependency) (the third hit) produced the answer at https://www.originlab.com/doc/Origin-Help/NLFit-Theory#Dependency.
Comment: Please supply a reference or clear quotation so that we aren't left to guess what you are asking about.
Comment: @whuber, I don't understand what do you mean, I'm sorry. If "Dependency" is a general concept, I'm asking for a definition. If it's not, and it's something Origin Lab made up, I'm asking to someone who knows about Origin Lab's definitions.
Comment: @whuber, thank you, I'm sorry for wasting your time. I looked into the programs help center and I found nothing. I also googled and got into the forums but still no answer. I should improve my googling skills. Thanks again.
Answer: For completness I will write an answer. Thanks to @whuber. It's defined in the documentation as
$$\text{Dependency}_i = 1 - \frac{1}{[\mathbf{C}]_{ii} \cdot [\mathbf{C}^{-1}]_{ii}},$$
where $\mathbf{C}$ is the covariance matrix.
Answer: To add to the contributions @whuber and @MacroCiafa, I will include a Python implementation since that was your end goal. stats.SE is not primarily about coding, so consider this post merely a supplement to the accepted answer.
import numpy as np

def dependence(X):
    '''
    Calculate the dependence of a
    collection of variables from a data
    matrix.

    PARAMETERS
        X (2D array-like): Data matrix

    RETURNS
        (1D array): Dependence score of each variable.
    '''
    C = np.cov(X)
    result = np.diag(C) * np.diag(np.linalg.inv(C))
    return 1 - 1 / result

If you're fine with using the Moore-Penrose pseudoinverse, then this can be adjusted slightly into the following.
import numpy as np

def dependence(X):
    '''
    Calculate the dependence of a
    collection of variables from a data
    matrix.

    PARAMETERS
        X (2D array-like): Data matrix

    RETURNS
        (1D array): Dependence score of each variable.
    '''
    C = np.cov(X)
    result = np.diag(C) * np.diag(np.linalg.pinv(C))
    return 1 - 1 / result

"Dependency" definition


showing that all convex polehedron graphs are 3-connected

Question: I'm trying to figure out how to show that two nonadjacent vertices in the graph of a convex polyhedron can be disconnected from one another by the removal of at least three vertices.
I know what a convex polyhedron is (I at least have a clear picture in my head of what they look like), and it is clear that they are planar, but I can't quite characterize them to even begin to prove this. I want to try assuming that the removal of two vertices would disconnect two nonadjacent vertices, but I can't see what to do from there. Any help or suggestions would be appreciated.
Comment: The edge-vertex graphs of some 3-dimensional convex polytopes are more than 3-connected. For example the regular icosahedron's graph is 5-connected. One approach to 3-connectedness is to say that every pair of distinct vertices u and v can be joined by at least 3 paths whose only vertices in common are u and v. On the icosahedron for any pair of distinct vertices there are 5 such paths so the icosahedron is 5-connected.
Comment: @JosephMalkevitch Thank you for that example. You are right, the icosahedron graph is 5-connected. Then I am confused by the statement I have been asked to prove..  It says: "For the graph of a convex polehedron show that any two nonadjacent vertices are separated by at least three others." Your example is a counterexample, is it not? Unless I am not understanding what the author means by "separated"...
Comment: @JosephMalkevitch This question is from Tutte's graph theory book, by the way.
Comment: Tutte tended to use somewhat different terminology from some other authors, and I don't know his definitions here. The now "standard" approach to Steinitz's Theorem: A graph is 3-polytopal if and only if it is 3-connected is described in the books of polytopes by Grünbaum and Ziegler. Their approach allows graphs to be 4 or 5-connected but also 3-connected. Some 3-connected graphs are not 4-connected or 5-connected. The only proof I know of that 3-polytopes are 3-connected uses a theorem of M. Balinksi that the graphs of d-polytopes are d-connected.
Comment: Typo in above in my statement of Steinitz's Theorem: A graph is 3-polytopal if and only it is planar and 3-connected.
Answer: An n-polyhedral graph (sometimes called a c-net) is a 3-connected simple planar graph on n nodes. Every convex polyhedron can be represented in the plane or on the surface of a sphere by a 3-connected planar graph. Conversely, every 3-connected planar graph can be realized as a convex polyhedron. Polyhedral graphs are sometimes simply known as "polyhedra" (which is rather confusing since the term "polyhedron" more commonly refers to a solid with n faces, not n vertices).
Through duality, each polyhedral graph on $V=n$ nodes corresponds to a graph with F=n faces. So the polyhedral graphs on n nodes are isomorphic to the convex polyhedra with n faces.  The icosahedral graph with $12$ vertices is 5-connected and corresponds to the dodecahedron, a convex polyhedron with $12$ faces which is 3-connected. In every case either the polyhedral graph or its planar dual would be 3-connected.


Acessando os elementos HTML no Array

Question: Ao utilizar o script, eu estou quebrando uma tabela de
 com elementos . Alguns dos
 tem o background vermelho e amarelo. Meu Script isola esse elementos no vetor sla. Cada elemento do vetor fica com um texto de
, cheio de . Eu não sei como fazer, mas gostaria de quebrar o  e fazer um vetor com os valores isolados de cada . Como fazer?
const chamados = Array.from(document.querySelectorAll('tr'));
const sla = [];
for(i=0;i < chamados.length;i++){
  if(chamados[i].style.backgroundColor == "red" || chamados[i].style.backgroundColor == "yellow"){
    sla.push(chamados[i]);
    for(j=0; j < sla.length; j++){
      console.log(sla[j]);
    }
    console.log(i);
  }
}

Answer: Primeiramente não é necessário esse Array.from.
Utilize o children para pegar os elementos filhos desse tr, que esses filhos são o td. Se o td tiver o backgroundColor == 'red' ou backgroundColor == 'yellow' ele vai armazenar o texto que está no td desse tr percorrendo um por um.

const chamados = document.querySelectorAll('tr')
const sla = []

for (let i = 0; i < chamados.length; i++){
  if (chamados[i].style.backgroundColor == 'red' || chamados[i].style.backgroundColor == 'yellow'){
  for (let j = 0; j <chamados[i].children.length; j++)
  sla.push(chamados[i].children[j].innerText)
  }
}
console.log(sla)

    tr0 td0 red
    tr0 td1 red
    tr0 td2 red

    tr1 td0 green
    tr1 td1 green
    tr1 td2 green

    tr2 td0 yellow
    tr2 td1 yellow
    tr2 td2 yellow

Espero ter ajudado
Answer: O exemplo do @NoFace usando o chidren para pegar os elementos filhos resolve o problema, mas gostaria de sugerir uma abordagem mais funcional e declarativa.
Pra entender mais sobre o Destructuring usando no parametro da funcão trVermelhoOuAmarelo você pode dar uma olhada aqui: Destructuring assignment. Basicamente ele obtem uma propriedade que está dentro do objeto.
Sobre como funciona o filter aqui: Array.prototype.filter().
Sobre o map e flatMap aqui: Array.prototype.flatMap(). Basicamente o flatMap pega arrays dentro de array e transforma em uma coisa só, se eu tenho [[1,2],3], usando o flatMap eu terei [1,2,3].

const chamados = Array.from(document.querySelectorAll('tr'));

const trVermelhoOuAmarelo = ({ style: { backgroundColor }}) =>
  backgroundColor === 'red' || backgroundColor === 'yellow';

const obterInnerText = (element) => element.innerText;
const obterFilhos = (element) => Array.from(element.children);

const sla = chamados
  .filter(trVermelhoOuAmarelo)
  .flatMap(obterFilhos)
  .map(obterInnerText);

console.log(sla);

      0.0 red
      0.1 red
      0.2 red

      1.0 green
      1.1 green
      1.2 green

      2.0 yellow
      2.1 yellow
      2.2 yellow

Você ainda pode deixar as coisas mais simples já filtrando apenas os elementos vermelhos e amarelos no querySelector, exemplo:

const expression = "tr:not([style*='green'])";
const chamados = Array.from(document.querySelectorAll(expression));

const sla = chamados
  .flatMap(x => Array.from(x.children))
  .map(x => x.innerText);

console.log(sla);

    0.0 red
    0.1 red
    0.2 red

    1.0 green
    1.1 green
    1.2 green

    2.0 yellow
    2.1 yellow
    2.2 yellow

Acessando os elementos HTML no Array


Cauchy problem doesn't have solution

Question:
Prove that the following Cauchy problem doesn't have solution
\begin{align}
y'(x) \sin(x) &= y \ln(y) \\
y \left( \frac{\pi}{2} \right) &=1 \\
\end{align}

I solved the ODE and I found:
$$\ln \left|\ln(y) \right|=\ln \left|\tan \left(\frac{x}{2} \right) \right|+c$$
When I put the initial condition, I found $\ln(0)$. How do I prove that this problem doesn't have a solution?
Comment: This is my problem, i try to found c and i stucked, because i found $ln(0)$ so doesn't exist c.
Comment: $ln(0)$ doesn't defined
Comment: This is no Cauchy or initial-value problem (IVP), as the coefficient of the (highest) derivative at the initial point is $\sin(\frac\pi2)=0$, the whole line $x=\frac\pi2$ does not belong to the domain of the DE, thus the initial point is not inside the domain.
Answer: The ODE can be solved as:
$$
y(x)=e^{c_{1} \tan (x / 2)}
$$
According to The uniqueness of the solutions of differential equations and the solution satisfies Lipschitz condition. Bring in the initial value and you can get $c_{1}=0,y=1$.
Comment: I understand your answer, but according to the uniqueness of the solutions of ode, we see, that y(x)=1 is a solution for initial value problem.
Comment: Yes, so y=1 is the solution of the ODE.

Cauchy problem doesn't have solution


KVM Guest with NAT + Bridged networking

Question: I currently have a few KVM Guests on a dedicated server with bridged networking (this works) and i can successfully ping the outside ips i assign via ifconfig (in the guest).
However, due to the fact i only have 5 public ipv4 ip addresses, i would like to port forward services like so:
hostip:port -> kvm_guest:port
UPDATE
I found out KVM comes with a "default" NAT interface, so added the virtual NIC to the Guest virsh configuration then configured it in the Guest, it has the ip address:
192.168.122.112
I can successfully ping 192.168.122.112 and access all ports on 192.168.122.112 from the KVM Host, so i tried to port forward like so:
iptables -t nat -I PREROUTING -p tcp --dport 5222 -j DNAT --to-destination 192.168.122.112:2521
iptables -I FORWARD -m state -d 192.168.122.0/24 --state NEW,RELATED,ESTABLISHED -j ACCEPT

telnet KVM_HOST_IP 5222 just hangs on "trying"
telnet 192.168.122.112 2521 works
[root@node1 ~]# tcpdump port 5222
tcpdump: WARNING: eth0: no IPv4 address assigned
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
23:43:47.216181 IP 220.127.116.11.51183 > null.xmpp-client: Flags [S], seq 1183303931, win 65535, options [mss 1400,nop,wscale 3,nop,nop,TS val 445777813 ecr 0,sackOK,eol], length 0
23:43:48.315747 IP 18.104.22.168.51183 > null.xmpp-client: Flags [S], seq 1183303931, win 65535, options [mss 1400,nop,wscale 3,nop,nop,TS val 445778912 ecr 0,sackOK,eol], length 0
23:43:49.415606 IP 188.8.131.52.51183 > null.xmpp-client: Flags [S], seq 1183303931, win 65535, options [mss 1400,nop,wscale 3,nop,nop,TS val 445780010 ecr 0,sackOK,eol], length 0

7 packets received by filter
0 packets dropped by kernel
[root@node1 ~]# iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             192.168.122.0/24    state NEW,RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

[root@node1 ~]# iptables -nvL
Chain INPUT (policy ACCEPT 976 packets, 57008 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   11   640 ACCEPT     all  --  *      *       0.0.0.0/0            192.168.122.0/24    state NEW,RELATED,ESTABLISHED

Chain OUTPUT (policy ACCEPT 673 packets, 40901 bytes)
 pkts bytes target     prot opt in     out     source               destination
[root@node1 ~]# iptables -nvL -t nat
Chain PREROUTING (policy ACCEPT 549 packets, 34067 bytes)
 pkts bytes target     prot opt in     out     source               destination
    1    64 DNAT       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:5222 to:192.168.122.112:2521
    3   192 DNAT       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:5222 to:192.168.122.112:2521
    1    64 DNAT       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:5225 to:192.168.122.112:2521
    1    64 DNAT       tcp  --  *      *       0.0.0.0/0            0.0.0.0/0           tcp dpt:5222 to:192.168.122.112:2521

Chain POSTROUTING (policy ACCEPT 45 packets, 3169 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 44 packets, 3105 bytes)
 pkts bytes target     prot opt in     out     source               destination

All help is appreciated.
Thanks.
Comment: Please provide the output of `iptables -nvL` and `iptables -nvL -t nat` (these show packet counts so you can tell which rules are being enacted). Please also provide a `tcpdump -n` from inside the guest so we can see what's getting to the guest. Are you testing the connection from the host itself or from a different location?
Comment: @mrgorven check updated answer, tested connection from host and local box.
Comment: Two things: Why are you doing this at all? You can just assign public IP addresses to the guests. Second, where's your IPv6?
Comment: @michaelHampton Please re read the question "However, due to the fact i only have 5 public ipv4 ip addresses, i would like to port forward services like so:"
Comment: So you ran out of IP addresses? You should clarify this.
Comment: @MichaelHampton They're expensive at my host
Comment: @Daniel Do you have to use KVM's default NAT? We use the bridge networking where I work and every guest get's a real IP address on our LAN. We then just point our external IP + port to a guest's IP + port via our firewall box.
Comment: Sorry for writing this as an answer; I'd comment but I can't yet. I second what F. Hauri commented on the previous answer. I'll phrase it in a different way: can you reach the Internet from your guest? Can you, say, ping an outside host, or run a `telnet www.google.com 80` and get a successful connection?
Comment: The server doesn't connect to a local LAN/NAT router, it's hosted in a D.C
Answer: if you run kvm in this way:
kvm -drive... -net nic -net tap ....

you will become a new interface (in root host) named tapX (where X is a number). This interface is normally configured by default via a script located in somewhere in /etc (/etc/kvm/kvm-ifup, /etc/qemu-ifup or else) you could change them with: kvm -drive... -net nic -net tap,script=mynatbrigescript...
From there, this interface have to be configured on each points:
ifconfig tapX 192.168.124.1/30

and in the client os:
ifconfig eth0 192.168.124.2/30

so if you hit (on root host), you will see a new local network (assuming your public ip is 18.104.22.168):
ip r s
184.108.40.206 dev eth0 ...
192.168.124.0/30 dev tapX  proto kernel  scope link src 192.168.124.1

From there, you must be able to ping to 192.168.124.2 from the root host. You could then DNAT your incomings tcp packets with:
iptables -t nat -A PREROUTING -i eth0 -d 192.168.122.31 --dport 5222 -j DNAT --to-destination 192.168.124.2:2521

and SNAT the answer packets in the other direction:
iptables -t nat -A POSTROUTING -o eth0 -s 192.168.124.2 -j SNAT --to-source 192.168.122.31

now if for the root node, this work:
telnet 192.168.124.2 2521

Then from your localdomain, this must do the same:
telnet 18.104.22.168 5222

At all, your root host have to forward ip packets, this could be verified by:
cat /proc/sys/net/ipv4/ip_forward
1

or
sysctl net.ipv4.conf.all.forwarding
net.ipv4.conf.all.forwarding = 1

This could be set by:
echo 1 > /proc/sys/net/ipv4/ip_forward

or
sysctl net.ipv4.conf.all.forwarding=1

Comment: I'm not running KVM this way, i'm using virt-install/virsh configuration files
Comment: @Daniel: Did you SNAT (or MASQUERADE) in the *answer* way, what you DNAT in *request* way?
Answer: First, your DNAT rule should be updated to include the destination IP of the KVM host. As it is, even traffic going from your virtual machine to the internet (on port 5222) would get DNATted.
iptables -t nat -F PREROUTING
iptables -t nat -A PREROUTING 1 -d KVM_HOST_IP -p tcp --dport 5222 -j DNAT --to-destination 192.168.122.112:2521

Other than that your iptables configuration seems okay. Only thing I can suggest is to make sure that your system allows IP forwarding:
sysctl -w net.ipv4.ip_forward=1

If running the above command solves the problem you should update /etc/sysctl.conf so it is preserved over reboots.
As others have suggested, running tcpdump -nn -i any port 5222 or port 2521 on the KVM host can give you a hint if the packet is getting forwarded or not. When you try telnet KVM_HOST_IP 5222 you should see two packets. One going to KVM_HOST_IP.5222, and another going to 192.168.122.112.2521.
Comment: still doesnt work iptables -t nat -A PREROUTING -d HOSTNODEPUBLICIP -p tcp --dport 5222 -j DNAT --to-destination 192.168.122.112:2521
iptables -I FORWARD -m state -d 192.168.122.0/24 --state NEW,RELATED,ESTABLISHED -j ACCEPT
Comment: Did you also check the `ip_forward` sysctl? `sysctl net.ipv4.ip_forward` should be set to 1.
Comment: still doesnt work [root@node1 ~]# sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1

KVM Guest with NAT + Bridged networking


Extracting indices from an R matrix to form a new matrix, using for-loops

Question: I am learning R, and currently am learning about loops.
I have a task to create a function ans(A) which:
1) Takes as input a 10x10 matrix A, with values 1 and 0. (so like "true and false")
2) Takes the elements which are value 1, and saves them in a new 2-column matrix. The first column is the row index, and the second column is the column index. It then returns this new index matrix. The index matrix is formed with matrix().
The task suggests the use of two nested for-loops
I'm not really sure how to do this task, particularly with for-loops. The input matrix A can be created for example by a simple diag(10), before the function itself, and then used as the input for the function for testing purposes.
The function would using for-loops take the diagonal indices and insert them into a new matrix and then return it as the answer.
Comment: What have you tried up to this point?
Answer: For the case you describe there is no need for any kind of loop:
<code>set.seed(42)
mat <- matrix(sample(0:1, 100, replace = T), ncol=10)
mat.ind <- which(mat==T, arr.ind=T)
> mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    0    1    1    0    0    1    0    1     1
 [2,]    1    1    0    1    0    0    1    0    0     0
 [3,]    0    1    1    0    0    0    1    0    0     0
 [4,]    1    0    1    1    1    1    1    0    1     1
 [5,]    1    0    0    0    0    0    1    0    1     1
 [6,]    1    1    1    1    1    1    0    1    1     1
 [7,]    1    1    0    0    1    1    0    0    0     0
 [8,]    0    0    1    0    1    0    1    0    0     1
 [9,]    1    0    0    1    1    0    1    1    0     1
[10,]    1    1    1    1    1    1    0    0    0     1

> mat.ind
      row col
 [1,]   1   1
 [2,]   2   1
 [3,]   4   1
 [4,]   5   1
 [5,]   6   1
 [6,]   7   1
  ... ... ...
</code>
Comment: Interesting. I'll look into this method more. It seems to give the correct final result which im after, just gotta modify it to a function form. (So the function ans(A) would return that final index matrix, with A being the big matrix). I wonder why the task recommends a for loop system.


Exponential function in C using recursion function

Question: I am trying to CALCULATE the  Exponential function of x   with recursion function .the  Exponential function is calculated from this equation .
I divided the Exponential function for two part the first part which is  Fracture
(i calculated it with the recursion function at the bottom and then put this part in while loop at the main function to find the sum from 0 to N
AS i am beginner in c and my English is not   perfect please explain my Mistake in a SIMPLE WAY .
THANK IN ADVANCE .....
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>

double faktoriyel(double x,double N);

int main(){
    double N, x, a;
    double s = 0;
    scanf("%lf", &x);
    scanf("%lf", &N);
    a = N;
    do
    {
        s += faktoriyel(x, N);
        --a;
    }while (a > 0);
    printf("\n%lf\n", s);
}

double faktoriyel(double x, double N)
{
    if (N < 0)
        return -1;
    else if (N < 2)
        return pow(x, N) / 1;
    else
        return (pow(x, N) / N * faktoriyel(x, N - 1));
}

Comment: The necessary images are not visible. Please post your question properly.
Comment: @GAURANGVYAS: Newcomers to the site can't post images.  In general, images are not really encouraged anyway, but it isn't entirely fair to blame newcomers for not making them visible.
Comment: Note that there's a bug in the equation you post (the x-squared term has the wrong divisor; it should be 2! and not 1!).  Someone (maybe that was you; given the use of the function name `faktoriyel` in both, it was probably you) posted the same (buggy) equation yesterday too.
Answer: Your base case is not right.
It should be
if(N == 0)
    return 1;

Why because anything raised to the power 0 is one.So returning 0.
Your method is not proper way of using recursion.
Check this code.
#include <stdio.h>
int power(int n1, int n2);
int main()
{
int base, powerRaised, result;
`printf("Enter base number: ");`
`scanf("%d",&base);`

`printf("Enter power number(positive integer): ");`
`scanf("%d",&powerRaised);`

`result = power(base, powerRaised);`

`printf("%d^%d = %d", base, powerRaised, result);`
`return 0;`

}
int power(int base, int powerRaised)
{
if (powerRaised != 0)
    `return (base*power(base, powerRaised-1));`
`else`
    `return 1;`

}
Answer: I changed it a bit here:
double faktoriyel(double x,double N)
{
if (N == 0) return 1;
else return (x/N * faktoriyel(x,N-1));
}

why? because you wrote
return (pow(x, N) / N * faktoriyel(x, N - 1));

which results in caculating
(x^(N+(N-1)+.....+1))/(N!)
instead of x^N/N!.
that is because you recalculate x^N every call to the function
and then multiply it :
(x^N)(x^(N-1))....*1
and here:
do
{
s+=faktoriyel(x,N);
--N;
}while (N>=0);

instead of this:
do
{
    s += faktoriyel(x, N);
    --a;
}while (a > 0);

because you actually calculated
x^N/N! + x^N/N! +.....+x^N/N!
instead of :
x^N/N! + x^(N-1)/(N-1)! +.....+1;
decrementing 'a' does not decrement N, resulting
in an incorrect calculation of e^x.
it should work btw.
Comment: Thank you very much for helping ,the result is more accurate but it still not correct , if i entered x=1.23 and N=23 i should  have exp(1.23)=3.41229536     but it is giving me 2.42312
Comment: I wrote down N!=0 instead of N>=0; my bad. it caused the result to be less by 1 from the required result


Which probability distribution function applies to my problem?

Question: OK the problem came from an AI course that I attended this year. You can find the problem description here
In short we have a number of birds in the sky that we need to shoot down.
In the main problem there are 90 white birds, 23 yellow, 22 blue, 22 green, 22 red and 1 black for a total of 180 birds.
My question is: How can I find the probability that I will have killed at least one of each species after X kills?
I know it is somehow connected to the hypergeometric distribution because that can tell you what is, for example, the probability that you will have hit the black bird after X number of kills, since we can treat each kill as sampling without replacement.
But how do I do this for all the species?
I'm asking this because one of my strategies required at least one killed bird from each species to use as example data, and I'm not sure how I could get a number that would say:
"After X kills you have P probability that you have hit at least one bird from each species".
Comment: The multivariate hypergometric distribution ( http://en.wikipedia.org/wiki/Hypergeometric_distribution#Multivariate_hypergeometric_distribution) is what you're looking for
Answer: If you want to find the probability that a uniformly random subset of size $X$ contains at least one of each species, then instead of using the multivariate hypergeometric distribution, I think you want to use inclusion-exclusion.
To be concrete, assume that $X = 50.$ The multivariate hypergeometric distribution tells you the probability that in a random subset of size $50$, you get exactly $12$ white, $2$ yellow, $5$ blue, $11$ green, $19$ red, and $1$ black bird. The problem is that you need to add these up over all possibilities with at least one of each type, and there are $137,083$ terms to add up. You could add up the complementary terms and subtract from $1$, but there are $244,692$ of those.
It is much simpler to use inclusion-exclusion. For each subset $S$ of the species, it is easy to calculate the probability $p(S)$ that no birds of that species were included in the $50$ birds. If $c(S)$ is the number of birds of species in $S$, then $p(S) = {180-c(S) \choose 50}/{180\choose 50} $. By inclusion-exclusion, the probability that you get at least one of each is
$$ \sum_S (-1)^{|S|} p(S) = \sum_S (-1)^{|S|} \frac{180 - c(S) \choose X}{180 \choose X}.$$
There are $6$ species, so this sum is over the $2^6 = 64$ subsets of the set of species. That's a lot smaller than $137,083$, and the terms are simpler.
Comment: +1 Very good! It looks to me that we had the same idea, you finished your answer while I was still working on mine.
Comment: Well I will have to study this a bit more to fully understand it, but after reading the wiki pages on both subjects I think I have a better understanding. Thanks!
Answer: The annoying part here is that you have to sum the probabilities of the multivariate hypergeometric over all the 6-tuples that add up to $X$ and for which all 6 numbers are positive.
It is tempting to use an approximation which is much easier to calculate and that relies on the Poincaré formula
$$P(A_1 \cup ... \cup A_6) = P(A_1) + ... + P(A_6) - P(A_1 \cap A_2) - ...$$
in which all subsequent terms combine 2, 3, 4, 5 and 6 events. If we neglect those terms we end up with
$$P(A_1 \cup ... \cup A_6) \approx P(A_1) + ... + P(A_6)$$
The event $A_i$ "bird of color $i$ was not drawn" has probability $(1-\pi_i)^X$, where $\pi$ is the proportion of bird of color $i$. In the end you can approximate your probability by
$$(1-90/180)^X + (1-23/180)^X + 3 \times (1-22/180)^X + (1-1/180)^X.$$
However, this approximation is bad because it is higher than 1 for small $X$ and very far from 1 for $X=180$. As shown in this numeric example in R
X <- seq(from=10, to=180, by=10)
(1-90/180)^X + (1-23/180)^X + 3 * (1-22/180)^X + (1-1/180)^X

I think you are left with Monte Carlo simulations or with painful term-by-term computations.
Here is quick way to get it by simulation (takes about 1 second on my laptop).
birds <- c(rep(1,90), rep(2, 23), rep(3:5, each=22), 6)
X <- 20
got_them_all <- rep(NA, 10000)
set.seed(123)
for (i in 1:10000) {
   got_them_all[i] <- length(unique(sample(x=birds, size=X, replace=FALSE))) == 6
}
mean(got_them_all) # answer: 0.0773

And here is a way that uses the full Poincaré formula
pi <- c(90, 23, rep(22,3), 1)/180
X <- 20
p <- 0
for (i in 1:6) {
    p <- p + (-1)^(i+1) * sum((1-colSums(combn(pi,i)))^X)
}
1 - p # answer: 0.07403239


Combinatorics with different set and restrictions

Question: I'm having two sets like
$S_1 = \{ A, B, C \}$
$S_2 = \{ D, E\}$
Within each Set I can form all possible combinations, so A,B,C,AB,AC,BC,ABC in the first case, which sums up to $2^n-1$ possibilities if I leave out zero (7 for $S_1$ and 3 for $S_2$).
However, now I'm looking for a formula to compute the number of different combinations for two (or several sets), but where I'm only allowed to take at most 1 (so 0 or 1) elements from each set.
So in the example above I could take AD or CE as well as A or just D, but no AB, ABD or ADE - only no more than 1 element from the different sets.
What's a universal formula for this?
Any help is appreciated! Thanks!
Answer:
How many ways can you take precisely 1 element from $S_1$ and none from $S_2$?
How many ways can you take precisely 1 element from $S_2$ and none from $S_1$?
How many ways can you take precisely 1 element from $S_1$ and 1 from $S_2$ too?

Add these three numbers together for the total count.
Comment: Ok, so it'a a quick an easy  n+m+n*m
Thanks a lot for your help! This was not so hard, sometimes it just takes while.
Answer: There are $(n_1+1)$ choices from $S_1$ since you might choose nothing and similarly $(n_2+1)$ from $S_2$, but you have to exclude the $1$ possibility of choosing none at all, so overall $$(n_1+1)(n_2+1)-1.$$
Comment: A formula which generalizes easily to the case of $k$ sets, for every $k\geqslant1$.


How to efficiently enumerate a Restricted Gray Code?

Question: I'm looking for an algorithm which enumeration all binary strings of length n in a Gray code manner, with the restriction that all strings have at most hamming weight <= k. For example n=4,k=2:
0000
0001
0011
0010
0110
---- skipped
0101
0100
1100
---- skipped
---- skipped
---- skipped
1010
---- skipped
1001
1000

n and k are known constants. The classic Gray code has two very important features: One can simply compute the i-th element a as i ^ (i >> 1) and given the i-th element a one can compute the next one as a ^ ctz(i+1), where ctz returns the number of trailing zeros (gcc buildin function).
So im looking for something like a "restricted" Gray code, with this features, which should be easy and fast computable.
The most straight forward solution would be to insert a popcount into the loop, which branches if a code word has the wrong weight. Sadly this is far to expensive in my setting: n = 45-50 and k = 15-18.
Comment: You mentioned `n = 45-50` and `k = 15-18`. Are those absolute [maximums]? (i.e.) The gray codes you're interested in will always fit in 64 bits? Do you have working C code [that uses `popcount`] and a test program? For another project, I came up with an alternate way to generate gray codes. It used decimal (or _any_ base) digits. Think: odometer than only changes one digit at a time. It could eliminate the repeated use of `popcount`. But, to see if it's applicable, and to see if it's any faster, it would help to have a working code from you that I could compare it against.
Answer: I'm not sure this is what you're looking for but let's give it a try...
The ith element of the code is calculated using the formula you mentioned:
G[i] = i ^ (i >> 1). Another feature of the Gray code is that any element is different from the previous one in a single place, therefore the bitwise xor operation between an element G[i] and its predecessor G[i-1], will result in a single bit being equal to one, at the position d at which the two element are different from each other. For instance G[i] ^ G[i-1] = 0101 ^ 0111 = 0010. Now the bitwise and operation between this result and the element G[i], will give 0 only if G[i] has a 0 at position d, otherwise the result will be equal to 2 ^ d, with d starting from 0. So, if (G[i] ^ G[i-1]) & G[i] == 0 it means that at the only place the two elements differ, G[i] has a 0 instead of a 1 and therefore its Hamming weight is 1 less than the one of G[i-1]. On the other hand if (G[i] ^ G[i-1]) & G[i] != 0, the Hamming weight of G[i] is 1 more than the one of G[i-1]. In order to know the Hamming weight of an element you just have to keep track of the weight of the previous elements. Starting from 0 and adding or subtracting 1 each time based on the result of (G[i] ^ G[i-1]) & G[i]. Hopefully this is somewhat comprehensible...
At a first glance I would say that this should perform better than the version using popcount but it may also depend on how operations are implemented both in software and hardware. I'm not particularly expert in this regard.
Here is the code:
#include <stdio.h>
#include <stdint.h>

void printBinary(uint64_t number);   // function for printing the variable in binary

int main()
{
    int k = 18;       // max Hamming weight
    int iter = 1000;  // number of codes to check

    uint64_t Gnew = 0;
    uint64_t Gold = 0;

    int i = 0;
    int count = 0;   // counter holding the Hamming weight of the current element

    printBinary(Gold);   // print the first element (0)

    for (i = 1; i < iter; i++){

        Gnew = i ^ (i >> 1);   // generate the ith element of the Gray code

        if (((Gnew ^ Gold) & Gnew) != 0){   // checks if the new element has one 1 more than the previous
            count++;                        // and increases the counter
        }else{          // or has one 1 less
            count--;    // and decreases the counter
        }
        if(count <= k){    // if element has weight smaller or equal to k print the element
            printBinary(Gnew);
        }

        Gold = Gnew;
    }

    return 0;
}

void printBinary(uint64_t number)    // from https://stackoverflow.com/questions/47326588/c-print-unsigned-int-in-a-binary-base
                                     // with some modifications
{
    int i;

    for(i = 63; i >= 0; i--){
        if(number >> i & 0x1){
                putchar('1');
        }else{
            putchar('0');
        }
    }

    putchar('\n');

    return;
}


como passar um valor de um input com ajax e receber em php com o metodo post?

Question: Precisava passar um valor de um campo html com o ajax e receber ele numa variável em php em outra pagina

<form>
    <input type="button" class="btn btn-primary" value="Configurar" onClick="webcam.configure()">

    <input type="button" id="botao" class="btn btn-warning" value="Tirar Foto" onClick="take_snapshot()">

    <input type="button" class="btn btn-danger" value="Reset" onClick="webcam.reset()">

    <input type="text" placeholder="Digite o codigo" class="input-medium" id="codigo" name="codigo" value="" style="height: 35px; border-radius: 5px;" />
</form>

PHP
$foto = @$_POST['acao'];

$uploadDir = 'paciente';

if(!is_dir($uploadDir)){
    if (!mkdir($structure, 0777, true)) {
        print "ERRO: Não foi possível criar o diretório [paciente]";
    }
}

if(!is_writable($uploadDir)){
    chmod($uploadDir, 0777);
}

$name = $uploadDir.'/image_'.$foto.'.jpg';
$file = file_put_contents($name, file_get_contents('php://input'));
if (!$file) {
    print "ERRO: Falha de escrita para o arquivo [$name], É necessário dar permissão de escrita na pasta [$uploadDir]\n";
    exit();
}

print 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).'/'.$name;

Answer: Você deve pegar o campo e enviar para a página, porém você pode enviar dinamicamente ou com um formulário pronto
Digamos que tenha um formulário pronto basta armazenar ele em uma variável e lançar a requisição com o seguinte método.
var data = $("#id_do_form").serialize();

se ele estiver em um input separado, terá de enviar dinamicamente.
var valor = $(".input").val();

                        var formulario = document.createElement('form');
                        formulario.id = 'sendFormFunc';

                        var input1 = document.createElement('input');
                        input1.value = valor;
                        input1.name = 'cod';

                        formulario.appendChild(input1);

                        document.body.appendChild(formulario);

                        var data = $('#sendFormFunc').serialize();

                        document.body.removeChild(formulario);

Após isso a requisição
$.ajax({
            type : "POST",
            url  : "seuarquivo.php",
            data : data,
            dataType: "json",
            success :  function(response){

            if(response.codigo == 0){alert("sucesso")}else{alert("erro")}

}

})

PHP
    $cod = (isset($_POST['cod'])) ? $_POST['cod'] : '';

    if(empty($cod)){
      $retorno = array('codigo' => 1);
    echo json_encode($retorno);
    exit();
    }
    else{
      $retorno = array('codigo' => 0);
    echo json_encode($retorno);
    exit();
    }


How to config SharedPreferences for the first run activity in the Android?

Question: I have 3 Activity:
1- SplashScreensActivity
2- IntroActivity
3- MainActivity
I need to do, At First launch appliation start IntroActivity else MainActivity after SplashScreenActivity .
Edited:
I wrote this code but did not work and after showing Splash Screen, MainActivity Started and IntroActivity never start.
Plese let me to know where is the problem.
Intro.Java:
<code>    SharedPreferences settings=getSharedPreferences("prefs", 0);
    final boolean firstRun=settings.getBoolean("firstRun",false);
    if(firstRun==false)
    {
        SharedPreferences.Editor editor=settings.edit();
        editor.putBoolean("firstRun",true);
        editor.commit();
        Intent i=new Intent(Intro.this,Intro.class);
        startActivity(i);
        finish();
    }
    else
    {
        Intent a=new Intent(Intro.this,MainActivity.class);
        startActivity(a);
        finish();
    }
</code>
SplashScreeActivity.Java:
<code>public class SplashScreensActivity extends Activity {

private ImageView mLogo;
private TextView welcomeText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_splash_screen);

    Typeface roboto_s = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");
    mLogo = (ImageView) findViewById(R.id.logo_sp);
    welcomeText = (TextView) findViewById(R.id.welcome_text);
    welcomeText.setTypeface(roboto_s);

    Animation animation2;{
        mLogo.setAlpha(1.0F);
        Animation anim = AnimationUtils.loadAnimation(this, R.anim.translate_top_to_center);
        mLogo.startAnimation(anim);
    }
    Animation animation3; {
        ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(welcomeText, "alpha", 0.0F, 1.0F);
        alphaAnimation.setStartDelay(700);
        alphaAnimation.setDuration(1200);
        alphaAnimation.start();
    }

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        finish();
        Intent next = new Intent(getBaseContext(), Intro.class);//
        startActivity(next);
        }
    }, 2000);
}
</code>
}
Comment: can you add log output?
Comment: Yes, Please wait for a minute
Comment: btw. is this code in the SplashScreensActivity?
Comment: post logcat and splash activity code and the other activity code which are you calling in splash activity using intent.
Comment: i have 1 mistake in the splashActivity and after solved that, app isnt close but intro activity never starting Even in the first run.
Comment: Did you uninstall the app/cleared cache?
Comment: Yes, Uninstall and Clear Cache and Data
Comment: `Intent i=new Intent(Intro.this,Intro.class);`  -> shouldn't this be `Intent i=new Intent(Intro.this,IntroActivity.class);`

Or did you get it to work already?
Comment: Did you find the solution?
Comment: no, it's not worked!
Answer: The problem was solved with a change in SplashScreenActivity.
So I 've edited the Handler codes in the SplashScreenActivity:
<code>        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
        public void run() {
            if (settings.getBoolean("isFirstRun", true)) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("isFirstRun", false);
                editor.commit();
                Intent next = new Intent(SplashScreensActivity.this, Intro.class);
                startActivity(next);
            } else {
                Intent next2 = new Intent(SplashScreensActivity.this, MainActivity.class);
                startActivity(next2);
                finish();
            }
        }
    }, 2000);
}
</code>
and remove firstRun method from Intro.Java
I hope to be useful


Main navigiation layout bugs after adding a cart block

Question: I have a question about some layout problems that I'm having since I installed commerce 2.x on my school project website. I'm using Drupal 8 for this.

You can see that one of the dots between each menu item are gone and another dot is slightly misplaced. Is there a way to restore this or remove all the dots maybe? The domain of my website is designmuseum.vansompel.be
I have been changing some of the css in the most upper sidebar to get the cart block next to the user account menu. Even when I revert these changes, the problem on the main navigation seems to remain.
Could it be that my website is doing some automatic layout tweaks because of the new cart block? For example there is also a 10px padding above the cart block that I didn't specify myself and can't seem to find it in the code also.
<code>.header-top-highlighted__section .block + .block {
  padding: 10px 0 0 0;
}
</code>
I'm still pretty nooby at theming so if someone could point me in the right direction, that would be great! Thanks!
Answer: Looks like those dots are a content on :before of the anchor tag, to remove them you could add this to your CSS files.
<code>.header-container ul.menu li a:before {
    display: none;
}
</code>
This looks like it have been added by Drupal or maybe the theme you are using, i am not really sure, I recommend you read this https://www.w3schools.com/cssref/sel_before.asp to understand more about the before selector.
Comment: Thanks! The dots are gone indeed by adding the css you proposed. Still weird why the dots were misplaced though.


Weird return javascript regex without flag 'g'

Question: code = DAK~ 800 SUB~10/21/2015 CAK~10/21/2015
i just want to get 800
wheh i use this regex:
code_fix = match(/([0-9]){3}/g)
It returns = [ '800', '201', '201' ]
but when i try use the regex without flag g why is what my result looks like:
[ '800',
  '0',
  index: 21,
  input: 'DAK~ 800 SUB~10/21/2015 CAK~10/21/2015' ]

Comment: you just use [0], because it is first match in your expression, others are extra info you can ignore if you don't need.
Comment: try this `code_fix=match([0-9]{3})`
Comment: @YOU sorry, but I want to make the code look clean so I don't like to use [0]
Comment: @jamesjelo4kul I got this from it
`'800',
  index: 21,
  input: 'DAK~ 800 SUB~10/21/2015 CAK~10/21/2015'`
Answer: You need a word-boundary. Try this:
/\b([0-9]){3}\b/g

See this reference for more on word boundaries.
Comment: actually I don't want to use flag g, but your code help me solve to the problem, thank you :)
Answer: If use ([0-9]){3}, it also two matched,800 is all match,
and 0 is group match by ([0-9]), it match the last 0 in 800


Distinct Mersenne numbers are relatively prime specific proof verification

Question: As the title states, I'm supposed to prove for distinct primes $p_1,p_2 >2$ the primes dividing $2^{p_1}-1$ and $2^{p_2}-1$ are distinct.
The Wikipedia page on Theorems about Mersenne Numbers states that #6: if $m$ and $n$ are natural numbers then $m$ and $n$ are coprime if and only if $2^m-1$ and $2^n-1$ are coprime, the only one without proof. I believe I have to prove the forward $(\Longrightarrow)$ direction.

edit: this was my own work for a homework question, and I was mainly wondering if the proof was okay. there is no proof directly provided on Wikipedia, and I didn't find the links to the proof the clearest either. this was the clearest proof to me at the time and wanted someone else's feedback because I couldn't believe my proof was right.

My attempt at a proof (I use $a,b$ instead of $p_1,p_2$ or $m,n$):
Suppose $(a,b)=1$ and $(2^a - 1, 2^b -1) = d$.
Since $(a,b)=1$ there exist $x,y \in \mathbb{Z}$ s.t. $ax+by=1$.
Since $a,b > 2$, $x$ and $y$ cannot both be greater than zero, otherwise $ax+by > 2+2 >1$. Neither can $x$ or $y$ be equal to zero, otherwise $x$ or $y$ would $\not\in\mathbb{Z}$, or $ax+by=0\not=1$. Neither can $x$ and $y$ be less than zero, otherwise then $ax+by <0<1$.
Thus one of $x$ or $y$ must be positive, while the other negative.
Suppose $ax>0$ then $by<0$, then $d|2^{ax}-1$ and $d|2^{-by}-1$ since
$$2^{ax}-1 = (2^a -1)((2^a)^{x-1}+(2^a)^{x-2}+\cdots+1)$$
$$2^{-by}-1 = (2^b -1)((2^b)^{-y-1}+(2^b)^{-y-2}+\cdots+1)$$
and $d|2^a -1$ and $d|2^b -1$ by definition. Then $2^{ax} - 1 = d\alpha$ and  $2^{-by} -1 = d\beta$ and then $2^{ax}-2^{-by} = 2^{-by}(2^{ax+by}-1)=2^{-by}(2^1-1)=2^{-by}  = d(\alpha -\beta)$ thus $d|2^{-by}$ and $d$ must be a power of $2$. But $d|2^a-1$ where $2^a-1$ is odd, and the only odd power of $2$ is $2^0=1$, hence $d=1$. If $(a,b)=1$ then $(2^a -1 ,2^b-1)=d=1$.
Is my proof rigorous or am I missing something?
Comment: Looks good to me. You have a typo in the line "Suppose $ax>0$ then $bx<0$...." which should say "... then $by<0$...".
Comment: On re-reading it, I think you can say that the case $1=\min(a,b)$ is trivial as it implies $\min(2^a-1,2^b-1)=1$. If  $1<\min(a,b)$ then WLOG $by<0$ to $\geq$ in $a,b>2$ and $ax+by>2+2>1$? Thus the question I'm asked to solve might be over specific or a typo, and we could include $2$ as well? Sweet catch btw thx
Comment: @DanielWainfleet thanks
Comment: As you probably know, it is unknown whether there are infinitely many Mersenne $primes$, but quite a few Mersenne numbers are known to be prime, including the largest explicitly known primes. Prior to the computer era, (& prior to many advances in modern  Number Theory) the largest explicitly known prime was $2^{127}-1.$
Comment: And $ 7$ is made by the Mersenne prime $3=2^2-1!.$ I never noticed any of that. So the next one at the top should be $2^{2^{127}-1}-1\;??$ :).
Comment: that would blow out the largest known Mersenne prime by far! $2^{127} > 10^{38}$ how could the ancients know $2^{127}-1$ was prime?
Comment: @BillDubuque I meant to close the question yesterday, but hastily pressed no, I voted yesterday to close yesterday, I was vote #2
Answer: Your proof is fine, though you might also need to mention the case $ax < 0$ and $by > 0$ (though immediate).
By Wikipedia standards, most theorems are accompanied by a proof, or if not possible, a reference to the proof would be provided. In this case, the statement of this theorem is accompanied with a "[20]", which links to an archived version of Will Edgington's Mersenne Page. The various Lemmas in the section Mersenne Number Proofs supplies a proof to the claim.
Discussions on MSE that are also useful include:

Distinct Mersenne numbers are coprime

Prove that $\gcd(a^n - 1, a^m - 1) = a^{\gcd(n, m)} - 1$
Comment: +1. In the proof I would have said "WLOG $ax>0$"
Comment: Please strive not to add more dupe answers to dupes of FAQs, cf. recent site policy announcement [here.](https://math.meta.stackexchange.com/q/33508/242)
Answer: Looks rigorous enough. But there's a more elementary proof with a slightly more general definition of Mersenne numbers( where exponents are natural numbers):
$$2(2^n-1)+1=2^{n+1}-1$$ since $$2^1-1=1$$ is a sequence member, iteration produces the general recurrence :$$2^{n+m}-1=2^m(2^n-1)+(2^m-1)$$ This means for two Mersennes to share a factor, the Mersenne with exponent their difference in exponent must share it.
Euclidean gcd is based on taking the difference of two values, and saying the gcd must be a factor.  But, applying that in the exponent repeatedly, gives us the fact that two coprime exponent Mersenne numbers, can only share a factor if: $$2^1-1=1$$ shares it. Therefore they can only share the factor 1.


command: cabal build all, falling back to older state

Question: i am trying to install cardano-wallet by following this doc https://developers.cardano.org/docs/get-started/installing-cardano-wallet/
and getting this error while performing cabal build all
here is error that I am getting,
HEAD is now at 00ebe72 Added support for aeson-2.0, text-2.0, and GHC 9.2
Warning: The package list for 'hackage.haskell.org' is 146 days old.
Run 'cabal update' to get the latest list of available packages.
Warning: Requested index-state 2022-05-18T00:00:00Z is newer than
'hackage.haskell.org'! Falling back to older state (2022-03-02T05:17:47Z).
Resolving dependencies...
cabal: Could not resolve dependencies:
[__0] trying: cardano-wallet-2022.7.1 (user goal)
[__1] next goal: blockfrost-client-core (dependency of cardano-wallet)
[__1] rejecting: blockfrost-client-core-0.2.0.0 (conflict: cardano-wallet =>
blockfrost-client-core>=0.4 && <0.5)
[__1] skipping: blockfrost-client-core-0.1.0.0 (has the same characteristics
that caused the previous version to fail: excluded by constraint '>=0.4 &&
<0.5' from 'cardano-wallet')
[__1] fail (backjumping, conflict set: blockfrost-client-core, cardano-wallet)
After searching the rest of the dependency tree exhaustively, these were the
goals I've had most trouble fulfilling: cardano-wallet, blockfrost-client-core

Using cardano-node version 1.35.0 and and trying to install cardano-wallet v2022-7-1
Comment: Could you try `cabal update` before  `cabal build all`?
Comment: yeah I tried it but got error in ```cabal update```, anyways now its done.

thanks
Answer: This is almost certainly due to an out-of-date cache of the list of packages (and their versions) available from Hackage. You can use
cabal update

to fetch the latest list; then try again.
Comment: I did cabal update but it is resulting with 416 status response

```$ cabal update

Downloading the latest package list from hackage.haskell.org
Unexpected response 416 for http://objects-us-east-1.dream.io/hackage-mirror/01-index.tar.gz```
Comment: ```cabal update``` worked.
Answer: error solved by performing cabal update command


JavaScript Date set not working as expected. How to resolve?

Question: My code returning Sat

Jan 25 2020 15:06:45 GMT+0530 (India Standard Time)

anyone, please tell me why is it not working as my expectation?
Code:

let date1 = new Date(2019, 12, 25);
console.log(date1);
Comment: Javascript does not have months starting from 1 through 12 instead they start from 0 and end with 11. For your case you should use 11 for December.
Comment: You should check the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Answer: In JavaScript, the month of a Date is similar to an index of an array, in the aspect that it starts from 0 and goes to 12.
So you should do:

let date1 = new Date(2019, 11, 25);
console.log(date1);

Keep in mind that console.log(date) will return the date in UTC format so it might be off by a few hours (which might also change the date by 1), do console.log(date.toString()) instead.
Answer: Use format like this,
let date1 = new Date("2019-12-25");
console.log(date1);

And you will get a response like this,
Wed Dec 25 2019 06:00:00 GMT+0600


Adding controller with Entity Framework failed - DbContext Error

Question: I have a .Net Core app with EntityFramework.
I wanted to add controller with CRUD operations.
But I got this error

I don't get any error while performing add-migration. It finds only one DbContext.
These are all the places where I have WebApplication8Context
WEBAPPLICATION8CONTEXT.CS
    namespace WebApplication8.Data
{
    public class WebApplication8Context : IdentityDbContext<ApplicationUser>
    {
        public WebApplication8Context(DbContextOptions<WebApplication8Context> options)
            : base(options)
        {
        }

        public DbSet<Tasks> Tasks { get; set; }
        public DbSet<TaskGroups> TaskGroups { get; set; }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);

        }
    }

IDENTITYHOSTINGSTARTUP.CS
    [assembly: HostingStartup(typeof(WebApplication8.Areas.Identity.IdentityHostingStartup))]
namespace WebApplication8.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {
                services.AddDbContext<WebApplication8Context>(options =>
                    options.UseSqlServer(
                        context.Configuration.GetConnectionString("WebApplication8ContextConnection")));

                services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                    .AddEntityFrameworkStores<WebApplication8Context>();
            });
        }
    }
}

APPSETTINGS.JSON
    {
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "WebApplication8ContextConnection": "Server=CREATIVESM\\SQLEXPRESS;Database=MarApplication;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

BEGGINING OF MY WEBAPPLICATION8MODELSNAPSHOT
    namespace WebApplication8.Migrations
{
    [DbContext(typeof(WebApplication8Context))]
    partial class WebApplication8ContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.10")
                .HasAnnotation("Relational:MaxIdentifierLength", 128)
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

My Startup.cs
    namespace WebApplication8
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}

Other places where I can find WebApplication8Context are my migrations.
What am I doing wrong?
Answer: It looks like there is a conflict between IdentityHostingStartup and Startup.
Although I don't know the specific reason, you can use the following methods to solve it:
You can delete the code in your IdentityHostingStartup,then add it to your Startup like this:
    services.AddDbContext<WebApplication8Context>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("WebApplication8ContextConnection")));
    services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<WebApplication8Context>();
    services.AddControllersWithViews();
    services.AddRazorPages();

Re-migration and update database,then you will add the controller successful.
Comment: Adding code to startup instead of identityhostingstartup worked :) thank you!


Unable to run a Python code with Exscript - ImportError: No module named resource (CentOS 6.9)

Question: I'm trying to install and run a python script for logging into my network devices. I have installed it in one of our instances (CentOS release 6.9). But when I try to run the script, i get an error. Here's what I see:
Traceback (most recent call last):
  File "connect.py", line 1, in <module>
    from Exscript.util.interact import read_login
  File "/usr/local/lib/python2.7/site-packages/Exscript/__init__.py", line 34, in <module>
    from Exscript.Queue       import Queue
  File "/usr/local/lib/python2.7/site-packages/Exscript/Queue.py", line 40, in <module>
    from Exscript.util.decorator import get_label
  File "/usr/local/lib/python2.7/site-packages/Exscript/util/decorator.py", line 28, in <module>
    from Exscript.protocols.Exception import LoginFailure
  File "/usr/local/lib/python2.7/site-packages/Exscript/protocols/__init__.py", line 28, in <module>
    from Exscript.protocols.SSH2 import SSH2
  File "/usr/local/lib/python2.7/site-packages/Exscript/protocols/SSH2.py", line 34, in <module>
    from paramiko.resource      import ResourceManager
ImportError: No module named resource

Not sure what I'm doing wrong here to be honest. Here's the script:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('x.x.x.x')
conn.login(account)
conn.execute('terminal pager 0')
conn.execute(show IP)
print conn.response
conn.close

Can someone help?
Answer: I'm seeing the same issue after installing Exscript v2.3.2 with "pip install Exscript"
In the original source code on github the file Exscript/protocols/SSH2.py for v2.3.2 does not contain this line so have you tried commenting it out?  That worked for me ..
Another option is to install Exscript from github and do make install
Comment out line 34 in /usr/local/lib/python2.7/site-packages/Exscript/protocols/SSH2.py:

#from paramiko.resource      import ResourceManager


Getting both group size and min of column B grouping by column A

Question: Given a DataFrame df, I can obtain the size of groups by column A with
df.groupby(['columnA']).size()

and the mimimun value of column B within each group with
df.groupby(['columnA']).agg({'columnB':min})

or (syntactic sugar I guess)
df.groupby(['columnA'])['columnB'].min()

but how can I obtain directly a DataFrame with such 2 columns?
In SQL, if you comfortable with it, this would be as simple as
SELECT count(columnA), min(columnB) FROM table GROUP BY columnA

Thanks in advance for any clue.
Answer: Placing both of them in agg should work, since agg permits a list of functions.
>>> df
  columnA  columnB  columnC
0    cat1        3      400
1    cat1        2       20
2    cat1        5     3029
3    cat2        1      492
4    cat2        4       30
5    cat3        2      203
6    cat3        6      402
7    cat3        4      391

>>> df.groupby(['columnA']).columnB.agg(['size', 'min'])
         size  min
columnA
cat1        3    2
cat2        2    1
cat3        3    2

>>> df.groupby(['columnA']).agg(['size', 'min'])
        columnB     columnC
           size min    size  min
columnA
cat1          3   2       3   20
cat2          2   1       2   30
cat3          3   2       3  203

agg also accepts a dict of columns -> functions, and so were you to want to map a function to each column individually you could do so with something (not necessary here) like
df.groupby(['columnA']).agg({'columnA':'size','columnB':'min'})

Comment: I think that your first answer `df.groupby(['columnA']).agg({'columnA':'size','columnB':'min'})` was more general and useful in real world. I would suggest to add it back.
Comment: @mmj Sure, I can add a blurb about using dicts.
Comment: You might be interested in tackling the follow up of this question: http://stackoverflow.com/q/42399574/694360


Xcode / React Native - "Transform Error - unknown plugin 'module-resolver' "

Question: I am running a build on Xcode for my React Native project and for some reason, when running the build in debug mode, this error appears:
'TransformError: [my directory] : Unknown plugin "module-resolver" ' inside my babelrc file.
I tried to npm install the module-resolver to see if that would get rid of the error however the simulator still has as red screen with that same TransformError.
Any help/guidance on this would be really helpful.
Thanks
Answer: You must install the 'babel-plugin-module-resolver'.
You should run:
npm install babel-plugin-module-resolver --save-dev
https://www.npmjs.com/package/babel-plugin-module-resolver


How do I add a subtitle for menu items in Nice menu?

Question: I'm using the Nice menu module. I need to show a subtitle for each menu item.
How can this be done?
Answer: Try OM Maximenu module

"Maximize your main navigation by adding text, images, videos,
  slideshow, tabs, menu blocks, user info ..."
That is now possible by using OM Maximenu which can create menus with
  all other module blocks you want as attachments, modules like views,
  slideshow, menu, user, nice menus, quicktabs, and custom blocks with
  tables, lists, images, videos, etc.

Here a great list of menu 7 Mega Menu modules for Drupal


Is this way of finding $\lim\limits_{x\to +\infty}(x-\ln(x^2+1))$ valid?

Question: I needed to find: $$\lim\limits_{x\to +\infty}(x-\ln(x^2+1))$$
So here are the steps I took:
Step 1: Replace $x$ with $\ln(e^x)$:
$$\lim\limits_{x\to +\infty}\left(\ln(e^x)-\ln(x^2+1)\right)$$
$$\lim\limits_{x\to +\infty}\ln\left(\frac{e^x}{x^2+1}\right)$$
Step 2: Bring the limit inside of the natural log function since it is continuous on the required interval.
$$\ln\left(\lim_{x\to +\infty}\frac{e^x}{x^2+1}\right)$$
Step 3: Apply L'Hospital's rule twice and evaluate:
$$\ln\left(\lim_{x\to +\infty}e^x\right)$$
$$\ln(+\infty) = +\infty$$
My question is whether step 2 is valid here because $\lim\limits_{x\to \infty}\frac{e^x}{x^2 + 1}$ doesn't exist (its $+\infty$), and in order to move the limit operator inside the function the limit $\lim\limits_{x\to \infty}\frac{e^x}{x^2 + 1}$ must exist according to this theorem in a book about Calculus (ISBN 978-0-470-64769-1):
If it's not valid, what would be a valid way to find the limit?
Comment: Your step is valid. The book deals with the theorem where the limit does exist. Similar result holds if the limit does not exist. See the theorem mentioned at the end of this answer: https://math.stackexchange.com/a/1073047/72031
Answer: Let $M>0$ be given. Since $\ln(u)\to \infty$ as $u\to\infty$, there exists $K$ such that
for all $x$ with $\frac{e^x}{x^2+1}>K$ it follows that $\ln\left(\frac{e^x}{x^2+1}\right)>M$. Since $\frac{e^x}{x^2+1}\to \infty$ as $x\to \infty$, there exists $N$ such that
$$
x>N\implies \frac{e^x}{x^2+1}>K\implies \ln\left(\frac{e^x}{x^2+1}\right)>M.
$$
By definition of a limit it follows that
$$
\lim_{x\to\infty}\frac{e^x}{x^2+1}=\infty.
$$
Note we can mimic  the same argument to conclude that if $f(x)\to \infty$ as $x\to \infty$ and $g(x)\to \infty$ as $x\to \infty$, then $g(f(x))\to \infty$ as $x\to \infty$.
Comment: That's a nice clean way, thanks! Can you please explicitly answer the first question: whether the way I did it is mathematically valid or invalid?
Answer: In step 2 all you need is the fact that $\ln (y) \to \infty$ as $y\to \infty$. Since $\frac {e^{x}} {x^{2}+1} \to \infty$ it follows that $\ln (\frac {e^{x}} {x^{2}+1}) \to \infty$. To prove that $\ln (y) \to \infty$ as $y\to \infty$ assume that this is false. Since $\ln \, x$is an increasing function, if it doesn't not tend to infinity, it would be bounded for $x>1$, say $\ln\, x <C$ for all $x>1$. You get a contradiction from this if you take $x=e^{C}$.
Comment: Thank you! Can you please explicitly answer the first question: whether the way I did it is mathematically valid or invalid?
Comment: @user3071028 Everything you have done is right if you use that fact that $\ln \, y\to \infty$ as $ y \to \infty$.


Como formatar um Double trocando o ponto por vírgula e mantendo 2 casas decimais em VB.NET

Question: Preciso transformar o resultado de um valor de As Double para o padrão numérico brasileiro que usa vírgula ao invés de ponto (e também manter somente 2 casas decimais), Assim:
' variaveis de teste                       ' valores esperados de saida
Dim t1 as double = 123                     ' ~> 123,00
Dim t2 as double = 123.123                 ' ~> 123,12
Dim t3 as double = 123123132112321321.123  ' ~> 123123132112321321,12
Dim t4 as double = 0.123                   ' ~> 0,12
Dim t4 as double = 0.158123                ' ~> 0,16

Answer: O método ToString tem uma sobrecarga que aceita um CultureInfo como parâmetro. Passe este parâmetro usando a cultura que desejas.
Dim valor = 5.89d
valor.ToString(new CultureInfo("pt-br"))

Veja funcionando no .NET Fiddle
Comment: Isso mesmo! Muito obrigado! Já estava pensando em umas coisas doidas do tipo `ToString().Replace()` rs
Answer: Um valor Double é só um número, ele não possui formatação, só é possível transformá-lo em String aplicando uma formatação. Esta formatação deve usar uma cultura, no caso a brasileira.
Imports System
Imports System.Globalization

Public Module Module1
    Public Sub Main()
        Dim ptbr = new CultureInfo("pt-br")
        Console.WriteLine("{0}", 123.ToString("N2", ptbr))
        Console.WriteLine("{0}", 123.123.ToString("N2", ptbr))
        Console.WriteLine("{0}", 123123132112321321.123d.ToString("N2", ptbr))
        Console.WriteLine("{0}", 0.123.ToString("N2", ptbr))
        Console.WriteLine("{0}", 0.158123.ToString("N2", ptbr))
    End Sub
End Module

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Só note que se isto for dinheiro o Double não é o tipo adequado.
Comment: Embora não faça exatamente o que você pediu
Comment: sim o @LINQ acabou passando a resposta acima, e da forma que ele colocou ficou mais simples, mesmo assim obrigado.
Comment: na verdade faz sim, o que preciso é só trocar o ponto por virgula e não formatar como dinheiro ou moeda =D
Comment: Então sua pergunta foi mal formulada porque ela mostra claramente que precisa ter apenas 2 casas decimais em todos os casos.
Comment: alterei a pergunta para ficar mais clara então
Comment: Portanto a minha está correta conforme a sua pergunta, e a do LINQ, apesar da boa intenção, não: https://dotnetfiddle.net/qy7Ids