tableview cell value

Question: I am making an iphone application. In one of the view of the application I have implemented the table view. On each table view cell I have put one or two buttons. Now I want that whenever I click the button it give me the value of cell. How can I do it if anybody has an idea about this please let me know.
The code which I have implemented to display the button is:
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [rangetime objectAtIndex:indexPath.row];
    NSString *checkstatus = [finalstatusarray objectAtIndex:indexPath.row];
    if ([checkstatus isEqualToString:@"YES" ])
    {
        UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton1.tag=1;
        submitbutton1.frame = CGRectMake(200, 4, 28, 29);
        UIImage * btnImage1 = [UIImage imageNamed:@"yes.png"];
        [submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
        cell.accessoryView = submitbutton1;
        [submitbutton1 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([checkstatus isEqualToString:@"NO" ])
    {
        UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton2.tag = 2;
        submitbutton2.frame = CGRectMake(200, 4, 28, 29);
        UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
        [submitbutton2 setImage:btnImage1 forState:UIControlStateNormal];
        [submitbutton2 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = submitbutton2;

    }
    else if ([checkstatus isEqualToString:@"s" ])
    {
        UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton1.tag = 1;
        submitbutton1.frame = CGRectMake(255, 5, 28, 29);
        UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
        [submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
        [cell  addSubview:submitbutton1];// = submitbutton1;
        [submitbutton1 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];

        UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton2.tag = 2;
        submitbutton2.frame = CGRectMake(285, 5, 28, 29);
        UIImage * btnImage2 = [UIImage imageNamed:@"yes.png"];
        [submitbutton2 setImage:btnImage2 forState:UIControlStateNormal];
        [cell  addSubview:submitbutton2];
        [submitbutton2 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}
</code>

Thanku very much.
Answer: You can do with the help of following code.
I had edited your answer in target method of UIButton and added event as argument so you can get indexPath of the row.
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    cell.textLabel.text = [rangetime objectAtIndex:indexPath.row];
    NSString *checkstatus = [finalstatusarray objectAtIndex:indexPath.row];
    if ([checkstatus isEqualToString:@"YES" ])
    {
        UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton1.tag=1;
        submitbutton1.frame = CGRectMake(200, 4, 28, 29);
        UIImage * btnImage1 = [UIImage imageNamed:@"yes.png"];
        [submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
        cell.accessoryView = submitbutton1;
        [submitbutton1 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([checkstatus isEqualToString:@"NO" ])
    {
        UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton2.tag = 2;
        submitbutton2.frame = CGRectMake(200, 4, 28, 29);
        UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
        [submitbutton2 setImage:btnImage1 forState:UIControlStateNormal];
        [submitbutton2 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = submitbutton2;

    }
    else if ([checkstatus isEqualToString:@"s" ])
    {
        UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton1.tag = 1;
        submitbutton1.frame = CGRectMake(255, 5, 28, 29);
        UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
        [submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
        [cell  addSubview:submitbutton1];// = submitbutton1;
        [submitbutton1 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];

        UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
        submitbutton2.tag = 2;
        submitbutton2.frame = CGRectMake(285, 5, 28, 29);
        UIImage * btnImage2 = [UIImage imageNamed:@"yes.png"];
        [submitbutton2 setImage:btnImage2 forState:UIControlStateNormal];
        [cell  addSubview:submitbutton2];
        [submitbutton2 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
}

- (void)updatestatus:(id)sender event:(UIEvent *)event
{

   NSIndexPath *indexPath = [tblCityList indexPathForRowAtPoint:[[[event
      touchesForView:sender] anyObject] locationInView:YourTableName]];

   **Now You can access the row value with the help of indexPath.row**
}
</code>
Answer: First of all, you have to modify the below code...
<code>    [submitbutton1 addTarget:self action:@selector(updatestatus:) forControlEvents:UIControlEventTouchUpInside];
</code>
Instead of,
<code>    [submitbutton1 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
</code>
And write the following code in updatestatus:
<code>    - (IBAction) updatestatus:(id)sender
    {
        UIButton *btn = (UIButton*) sender;
        UITableViewCell *cellSelected = (UITableViewCell*) [btn superview];
        NSIndexPath *idxPath = [tableView indexPathForCell:cell];
        // Your code...
    }
</code>
Answer: Have the following code
<code> -(void)showCellValue:(UIControl *)button{

UITableViewCell *cell = (UITableViewCell*)button.superview;
NSIndexPath *indexPath =[aTableView indexPathForCell:cell];
NSLog(@"The cell value is %@",[tableData objectAtIndex:indexPath.row]);
</code>
}
Assign this method showCellValue to the selector of the button. tableData is the array from which u load the data to the table. And in ur case it s rangeTime array
Hope this helps.

tableview cell value


Standard Deviation vs Standard Error

Question: I am confused about the difference between standard deviation and error. When do I use which? From my lecture:

Standard deviation quantifies spread of data about mean
Standard error measures spread of all means

I actually learn this from my physics data analysis lesson. So suppose I have a set of measurements of distance ($D$) verses time ($t$) and I want to compute avg velocity:

$t_{avg}$ is calculated as $(t_1 + t_2 + t_3)/3$ (of course I used excel's AVERAGE here). Then avg velocity was $t_{avg}/D$.
Then I was asked which measurement #1-10 I think is the closest approximate the the actual velocity. So I was thinking I find the standard error and the one with the lowest is the closest approximate? Is this the reasonable thing to do? I found standard error by STDEV(t_1, t_2, t_3)/SQRT(3). Is this correct?
Heres my confusion: STDERR is defined as the spread of all means. I am calculating the spread of all measured data? Not the mean?
Answer: In the context of your example: Does it really make a difference which you use? If standard deviation is 's'. The standard error is just s/SQRT(n). This is a linear transformation; therefore for the purpose of comparison it makes no difference which you use.
Now, for the purpose of making a statistical test. If you calculate a group of 'sample means' all independent and identically distributed. Then that sample of 'sample means' would have standard deviation given by s/SQRT(n).
Its intuitive that using a sample mean would give more information of the data, therefore s/SQRT(n) < s; that is to say the variability in the sample of 'sample means' is less than the variability in the individual sample.
TL;DR
-use 's' for the sake of comparison.
-For statistical tests use 's/SQRT(n)' when say finding the distribution or confidence interval for the sample means.
-For statistical tests use 's' when say finding the distribution or confidence interval for individual samples.
Comment: In other words, the above excel image seems right to you?
Comment: Also to find the closest approximate to actual velocity, is it right to conclude that #10 (D is smallest) is the closest approximate as STDERR is smallest?
Comment: I should add that I'm a student myself- and therefore not a reliable expert! my name gives it away :). Whether you use STDEV or STDERR, #10 will always be the smallest. In fact the order of highest to lowest STDEV is the same as the order for highest to lowest STDERR (explained in paragraph 1). So u can use either 's' or 's/SQRT(n)' for comparing as you are.
Comment: Your assumption '# 10 is the closest estimate...since STDERR is smallest,'... is difficult for me to conclude on as I'm unsure of what the data represents. But prima facie yes, your statement is correct since low STDEV or STDERR generally indicates more reliable data- so #10 is reliable.
Comment: Just checked some of the excell calculations for STDERR of time, they seem right.

Standard Deviation vs Standard Error


How do i show given sequence is 'rearrangement'?

Question: Let $\{a_n\}$ be a real-values sequence which is convergent but not absolutely.
Let $P_n$ enumerate nonnegative terms and $Q_n$ enumerate negative terms.
It's clear that the set of $P_n$ and that of  $Q_n$ are infinite.
Let $I(n) = n, \forall n\in \mathbb{N}$.
Let $\{m_n\}$ and $\{k_n\}$ be subsequences of $I$.
Expand like follows;
$P_1, ... , P_{m_1} , Q_1 , ... , Q_{k_1} , P_{m_1 +1} , ...$
It's clear that this is a rearrangement of $\{a_n\}$, but how do i show this enumerates $\{a_n\}$ in meta language?
Answer: All you need to do is say that since each element in your expanded sequence corresponds to exactly one element of the original series, you have that:
$$P_1, \dots , P_{m_1} , Q_1 , \dots , Q_{k_1} , P_{m_1 +1} , \dots=a_{\varphi(1)},a_{\varphi(2)},\dots$$
where $\varphi$ is a permutation of $\Bbb N$.


Little white box in Unity

Question: I'm new to unity, and i made a game, But it doesn't work with diffrent resolutions.
When i edit a button it shows me a little box at the center of the canvas.
i've tried many things, but nothing helped me, and buttons are still half on screen half not.
Can someone help me?
Answer: There are two things you needed for UI to work with multiple resolution :
First : RectTransform
Second : Canvas Scaler
RectTransform is a position that when you change resolution, the distance between the rect's position to the UI is consistent, by default it is in the center of the screen. You can adjust it by the RectTransform component in your UI
Canvas Scaler : You can use it in the canvas which contain your UI. You can choose the default resolution to scale from, for example, 1920*1080 and then the UI will scale base on the width or height
Comment: Hello, I have both, but when i want to move the RectTransform it limits its position with this box, that so i can't move it to the right bottom corner.
Comment: hmm, is your box contained by another gameobj ?
Answer: i found the problem.
the button had a parent that limited the RectTransform.
I've changed the parent into a completly diffrent canvas, and it worked.
I found the answer on this tutorial: https://www.youtube.com/watch?v=FeheZqu85WI.
Comment: Can I request some upvote for my answer ,:+()

Little white box in Unity


Eigenvalues of matrix based on submatrices

Question: If I have the eigenvalues of matrix A, is there anything I can say about the eigenvalues of the following matrix:
\begin{bmatrix}A_{11}+w&A_{12}&A_{13}&x\\A_{21}&A_{22}&A_{23}&0\\A_{31}&A_{32}&A_{33}&0\\y&0&0&z\end{bmatrix}
Comment: Is A symmetric ?
Comment: No, I think the only special property is that its eigenvalues are always positive
Comment: then I doubt that there is a general result...
Answer: The study can be split into two tractable cases

if $w=0$: you are in the case of "matrix bordering". In this case, see the Cauchy interlacing theorem ("Sandwich theorem" for eigenvalues of symmetric matrices) which assumes the symmetry of the matrix.
if $w > 0$, you can write the new matrix as the following sum, the second matrix being a rank-one matrix:

$$\begin{bmatrix}A_{11}&A_{12}&A_{13}&0\\A_{21}&A_{22}&A_{23}&0\\A_{31}&A_{32}&A_{33}&0\\0&0&0&(z-\dfrac{xy}{w})\end{bmatrix}+\begin{bmatrix}w&0&0&x\\0&0&0&0\\0&0&0&0\\y&0&0&\dfrac{xy}{w}\end{bmatrix}$$
Explanation : the 2nd matrix is a rank one matrix because it has the form:
$$\tag{*} \begin{bmatrix}\sqrt{w}\\0\\0\\ \dfrac{y}{\sqrt{w}}\end{bmatrix}*\begin{bmatrix}\sqrt{w}&0&0&\dfrac{x}{\sqrt{w}}\end{bmatrix}$$
Now, you can apply a theorem on the determinant of a matrix updated by the addition of a rank one matrix (Determinant of rank-one perturbations of (invertible) matrices), not by taking the numerical determinant but the determinant giving the characteristic polynomial.
Remark: We have assumed $w>0$. If $w<0$, replace every $\sqrt{w}$ by $\sqrt{-w}$, and take the opposite of the column vector in (*).
Comment: Have a look at the recent article "The_bounds_of_the_eigenvalues_for_rank-one_modification_of_Hermitian_matrix" by Guanghui_Cheng that you will find on Researchgate (you have to assume that $x=y$, i.e., the new matrix is still symmetrical.
Comment: In the case $w>0$, how exactly are the eigenvalues determined? Using the relation $\det(X + \mathbf{c}\mathbf{d}^T) = \det(X)(1 + \mathbf{d}^T X^{-1}\mathbf{c})$ and replacing $X$ with $X-\lambda I$ results in a characteristic polynomial involving finding $(X-\lambda I)^{-1}$


How to show that remainder $\beta X \setminus \beta(X)$ is an $F_\sigma$-set in $\beta X$.

Question: The $\beta \mathbb N$ be the Stone-Čech compactification of $\mathbb N$.
I have seen in Engelking - General topology that the remainder $\beta X \setminus \beta(X)$ is an $F_\sigma$-set in $\beta X$.
Can anyone explain why?
Thank you!
Answer: Consider $X$ (assumed to be Tychonoff, so $\beta X$ exists) to be a subset of its compactification $\beta X$. Then the remainder $\beta X \setminus X$ is an $F_\sigma$ in $\beta X$ iff $X$ is a $G_\delta$ in $\beta X$. This condition is known as $X$ being "topology complete", and for metrisable spaces it turns out to be equivalent to being completely metrisable.
Also, it's easy to see that the remainder is closed iff $X$ is open in $\beta X$, which means exactly that $X$ is locally compact. (So note that all locally compact Tychonoff spaces are topologically complete.)
As $\mathbb{N}$ is locally compact, the remainder is thus even closed. But e.g. for $X = \mathbb{R}$, or $X = \mathbb{R}\setminus\mathbb{Q}$ we also have $F_\sigma$ remainders, while for $X = \mathbb{Q}$ we do not, as the latter is not topology complete (not completely metrisable).
So it depends on $X$.
Comment: Yes, this is true.. thank you!
Answer: The remainder $β\mathbb{N} \setminus \mathbb{N}$ is even closed in $β\mathbb{N}$ since any point of $\mathbb{N}$ is isolated.


definition of an epoch in the fit method in keras

Question: I understand that one epoch is one pass through the training data. I'm training a CNN using the following lines of code
cnn = tf.keras.models.Sequential()
# ... code to define network layers ..
cnn.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
cnn.fit(x = training_set, validation_data = test_set, epochs = 2)

training_set was generated using
train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)
training_set = train_datagen.flow_from_directory('dataset/training_set_cut',
                                                 target_size = (64, 64),
                                                 batch_size = 32,
                                                 class_mode = 'binary')

And test_set was generated using similar code. training_set and test_set seem to be generators which never stop yielding or raise StopIteration. If that is the case, then how does cnn.fit know that one epoch has been completed?
Answer: In Keras, generators generate infinitely many elements. In order to define what an epoch is, you have to tell the generator when it should yield. This can be done with steps_per_epochand epochs in the model.fit call. From the Keras documentation, here is an example how you train a model with generators:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = utils.to_categorical(y_train, num_classes)
y_test = utils.to_categorical(y_test, num_classes)
datagen = ImageDataGenerator(
    featurewise_center=True,
    featurewise_std_normalization=True,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)
# compute quantities required for featurewise normalization
# (std, mean, and principal components if ZCA whitening is applied)
datagen.fit(x_train)
# fits the model on batches with real-time data augmentation:
model.fit(datagen.flow(x_train, y_train, batch_size=32),
          steps_per_epoch=len(x_train) / 32, epochs=epochs)

Manually, you only generate as many images as you want per generator (using e.g. zip if you have multiple generators) and from the same source we get:
for e in range(epochs):
    print('Epoch', e)
    batches = 0
    for x_batch, y_batch in datagen.flow(x_train, y_train, batch_size=32):
        model.fit(x_batch, y_batch)
        batches += 1
        if batches >= len(x_train) / 32:
            # we need to break the loop by hand because
            # the generator loops indefinitely
            break

Both examples are taken verbatim from here
Comment: I think it depends on the Keras version you use. If you're using an older version, you can use (now deprecated) `fit_generator` . Check out the tensorflow documentation https://www.tensorflow.org/versions/r2.1/api_docs/python/tf/keras/Model#fit_generator which has both fit functions.
Comment: Thanks. The code I am using does not define `steps_per_epoch` in the call to `fit` and from the documentation of `fit` it is hard to determine what the `steps_to_epoch` is set to in that case.


Jackson Data binding model unmarshalling array of objects

Question: Okay I have a JSON file and it has a set of objects that I wish to unmarshal into array of objects.
An example of how the JSON file is laid out is:
{
"data":{
  "name":{
     "fName":"John",
     "lName":"Doe"
  },
  "name":{
     "fName":"James",
     "lName":"Dokes"
  }
 }
}

The full JSON file is a lot more complex than this, this is just a example of how it is laid out.
What I want to do is to take those names, and unmarshall them into an array of name objects so I can access each name object whenever I want.
The classes are set up as
Test Class
 private Data data;

public void setData(Data d) {
    data = d;
}

public Data getData() {
    return data;
}

public String toString() {
    return "" + data;
}

Data Class
 private Name name;

public void setName(Name n){
    name = n;
}

public Name getName(){
    return name;
}

public String toString(){
    return "Names " + name;
}

Then the Name class is just
public class Name {

private String fName;
private String lName;

 //Getter setters here

    public String toString(){
    return "\nFirstName: " + fName + "\nLastName: " + lName;
}

Then in the main class, I just do
 ObjectMapper mapper = new ObjectMapper();

    Test test = mapper.readValue(new File("C:\\JSON\\test.json"),
            Test.class);
    System.out.println(test);

Now this will print out
Names
FirstName: James
LastName: Dokes

But it ignores the first name object, i.e. John Doe. What I want is to take each of these name objects and place them in an ArrayList, that way I can access the information, and display it whenever I want.
What am I doing wrong here? I tried changing the JSON file and making the names into an array, and then changing the code in the Data class and making Names an Array of object Names, but got an error saying
 Can not deserialize instance of Data out of START_ARRAY token

Would anyone be able to point me in the right direction here, as have tried many different solutions, but no success.
Thanks in advance for any help
EDIT:
Should my JSON look like this then
 {
"data":{
   "name":[
      {
         "fName":"John",
         "lName":"Doe"
      },
      {
        "fName":"test",
        "lName":"test2"
     }
   ]
 }
}

Answer: What you posted isn't really valid JSON as the data object has two keys with the same value name. Or rather, this JSON doesn't represent an array of names as your title suggests it should.
If the JSON data is meant to be a true JSON object, meaning that it is similar to a hashtable of names to values, then you should represent than in your Java class as a Map. But your Test class has a single Data field, which has a single Name field. One instance of Test cannot have more than one Name in this structure.
Comment: that JSON looks more logical. To map this to a Java POJO, you'd want to represent the `name` array as a `List` in your Data class.
Comment: Okay, I updated my post quickly. Should my JSON instead look like the one I updated my post with?


Fair Play award and team performances in IPL

Question: In IPL fair play award seem to resemble points table except few outliers.
Does fair play award has to do anything with who won the match also?
Answer: No, this is obviously not the case.
Of the 58 final points table positions after pool play in the IPL seasons 2012-2018, only twelve (12) matched the fair play rank for that team, and only three of these were the award winners.
If final points table positions and fair play award ranks are plotted with a linear regression model, there is almost zero dependence on the points table position (moving one place up or down has an effect of moving about ~0.11 places in the fair play ranking), with the starting position being almost exactly the mean final points table position (the fair play ranks are almost uniformly random rather than being biased to one side), and the data has a correlation coefficient of just 0.0131 (the points table position has as close to zero effect as it probably could!).
If the distance between fair play rank and final points table position is checked instead, the mean absolute difference is 2.48 ranks with an approximately Poisson distribution (a vast majority of ranks are not the same as positions, with many being very different). The actual differences have approximately a normal distribution with a standard deviation of 2.02 (which, given the range of ~7.3, again suggests that fair play ranks are almost perfectly random and separated from table positions).
This should also make perfect sense, since most teams will most often receive most of the fair play points they are eligible for, barring unlikely and extreme events, and teams may show high sportsmanship despite losing or conversely demonstrate poor spirit despite playing very well.


how to display 4-1 as month and date in php

Question: I Am developing a php web application. Here I have date in a variable in the format 'm/d'
$var='04/25'

I have stored this value as strtotime with in my table
$var2=strtotime($var);

Then I need to display this value as 4-25 i.e. remove 0 from 04.
If the date is 1 I need to display 1 not 01
Does anyone know this?
Comment: You'll need a year, whether it's this year (2012) or another arbitrary year; PHP can't work with generic month/day strings like this.
Comment: @MartinBean try it - works fine ... uses the current year
Comment: From [`date`](http://php.net/manual/en/function.date.php) manual  use `j`:Day of the month without leading zeros
Comment: @MartinBean If you don't specify a year, it'll take current year by default
Comment: @Aleks G Surely PHP will be assuming a year, though?
Comment: @MartinBean Yes, it'll assume current year.  If the OP doesn't care about the year, then there's no difference anyway.
Comment: @AleksG What about leap years?
Comment: What about it?  PHP is smart enough to deal with all of this.  Just read the docs on `strtotime` and `date` functions.
Answer: Use the PHP date function. In your case I would say date("n-j", $var2);
Answer: Too many ways to do this, so let's go with one of them:
ltrim( $var, '0' );

Answer: I always store timestamps, that way they can easily be used with date() function to convert them to any format I need.
$now = time();
print date("n-d",$now);

Comment: As Mads pointed out, you may also use "n-j" if 04/08 should be displayed as 4-8 instead of 4-08.
Answer: Just use date function: http://php.net/manual/en/function.date.php
echo date('n-j', $var2);

Answer: try this :
   copy below code and past in test.php and after run you get the out put : 4-25
   <?php

        $date = "04/25";
        $temp = strtotime($date);
        echo date('n-j',$temp);

   ?>


Zero count in a multinomial experiment

Question: I have the following problem: n balls are dropped, independently, in n different urns and we want to calculate $\mathbb{E}V_{n}$, where $V_{n}$ is the number of urns with zero balls.
I know that the zero count problem is generally difficult, but I think that this case can be simple because the distribution of the number of balls in the urns is multinomial with the same $p$ for each urn, which is $1/n$. So the probability that a given urn is empty, after dropping the balls, is $ q=(n-1)^{n} / n^{n} $.
My first thought was that the distribution of $V_n$ is binomial$(n-1,q)$, and thus $\mathbb{E}V_n = (n-1)q$. I did a lot of computational simulations of this problem to check my hunch and got a numerical value very very close to $np$ as if its distribution were binomial$(n,p)$.
This has me very confused becasuse $V_n$ can not be $n$. So I want to know if the distribution of $V_n$ is in fact some of the familiar distributions like the binomial or on the other hand, if there is some way to calculate $ \mathbb {E} V_n $ without worrying about its distribution.
Thank you very much.
Answer: For each of the urns $i = 1,2,...,n,$ let $X_i$ be the random variable which takes the value 1 if urn $i$ is empty, and 0 otherwise. Then
$$\sum_{i=1}^n X_i = V_n$$
By linearity of expectation,
$$\mathbb{E}[V_n] = \sum_{i=1}^n \mathbb{E}[X_i].$$
As you point out in your problem description, the probability that a particular urn is empty is $\frac{(n-1)^n}{n^n}.$ Therefore, for all $i \in \{1,2,...,n\},$ $\mathbb{E}[X_i] = \frac{(n-1)^n}{n^n}.$ It follows that
$$\mathbb{E}[V_n] = n \frac{(n-1)^n}{n^n} = \frac{(n-1)^n}{n^{n-1}}.$$
Comment: Thank you! It was easier than I thought

Zero count in a multinomial experiment


How to fix SalesForce authentication errors on localhost?

Question: I am fairly new to developing with Drupal, and new to this forum, so any help would be greatly appreciated.
While trying to authorize SalesForce with a local install I get the following two errors with when going to the oauth_callback.
Note: I have not included the entire path to save space but the reference points are accurate for the doc and line the error references.

Notice: Undefined property: stdClass::$data in Salesforce->requestToken() (line 338 of salesforce.inc)
SalesforceException: Error opening socket ssl://login.salesforce.com:443 in Salesforce->requestToken() (line 342 of salesforce.inc)

Local Environment: Mac OS Mavericks with XAMPP 5.6.3, SSL enabled on port 443 in httpd-vhosts.conf with certs created using OpenSSL.
Extension: php_openssl.dll uncommented in php.ini
Also to note the Drupal install was pulled from a live site that has SF module enabled and working.
I created a new connected app with the proper oauth_callback to the local site which is https://secure.localhost/salesforce/oauth_callback
I have both HTTPS and HTTP enabled, I have noticed that in the Status Report when using HTTPS I do get a HTTP Failure error in the status report.
The request url from salesforce is passing a code EX: https://secure.localhost/salesforce/oauth_callback?code=aPrxMZkm7lCkgfR3...
With a Status code of 500 Service unavailable.
I have looked all over online and on this site, and can't seem to find anything that works. I have tried a few patches to the common.inc file, but none of them seemed to work.
Like I said any help would be greatly appreciated, I am just not sure if it is Drupal, Salesforce, or my local setup.
Comment: Have you created an app in Salesforce with URL Callback to your local: `https://secure.localhost/` and you're using the right auth keys of that app?
Comment: Are you trying to use live Salesforce or sandbox? It seems you're trying to use live. So if you're trying to use sandbox, your endpoints are wrong.
Comment: Do you still get 'HTTP Failure error' in the Status Report, or you're talking about the past?
Comment: Kenorb, thank you for your replies: Yes I have the right auth keys, I am using a live site in salesforce not sandbox, I created a second connected app for my local site and am using an endpoint that links to my local site. And yes I still get the http failure error in the status report.
Comment: Are you using Secure Site or Secure Pages? If yes, disable them to see if that helps. If you go to `https://secure.localhost/salesforce/oauth_callback` (without any query), what page do you get (or which error)?
Comment: I am using neither Secure Site or Secure Pages just setup https via apache configurations. When I go to the oauth_callback url you posted above, I get access denied, I get this also when I am logged in.
Comment: Your problem is when salesforce module is requesting authorization token from Salesforce and it fails when doing httpRequest. `500` is coming from Salesforce, so I think you should check why it can't connect to it and fix your HTTP Failure error (try disabling firewall and anti-virus if any). Then check if  you're not overriding any curl settings (e.g. `~/.curlrc`) or you're not behind the proxy. Please also add `$conf['https'] = TRUE;` to your setting file (if you don't have it). Check if `curl login.salesforce.com:443` shell command doesn't give you any errors.
Comment: Kenorb, thank you again for helping me troubleshoot this. I do have $conf['https'] = TRUE; in settings file, no antivirus or firewall, curl does not give me any errors when I login into salesforce, and from what I can tell nothing is being overwritten. I will continue to try to figure out the HTTP failure error, but have yet to find any answers after hours of searching.
Comment: Can you also check if your PHP is not in Safe mode, and you didn't [disabled PHP functions](http://php.net/manual/en/ini.core.php#ini.disable-functions) (such as `stream_socket_client`).
Answer: In general, to make SalesForce authentication to work on localhost, you need to:

Create an app in Salesforce with URL Callback to your local (https://localhost/salesforce/oauth_callback) with appropriate permissions.

In Salesforce go to Your Name > Setup > Create > Apps then create a new Connected App. (Depending on your Salesforce instance, you may need to go to Your Name > Setup > Develop > Remote Access.)

Your site needs to be SSL enabled to authorize the remote application using OAUTH.
If using the SOAP API, PHP must be compiled with SOAP web services and OpenSSL support.
Use the right auth key and secret to Authorize your app (Configuration » Salesforce).
Make sure you're connecting to the right endpoints (live or sandbox).
For more help, check Help » Salesforce API in Drupal, or SalesForce documentation.
Add $conf['https'] = TRUE; to your setting file.

The error in Salesforce->requestToken() indicates that there is a problem exchanging an authorization code for an access token.
Further more, the error:

Error opening socket ssl://login.salesforce.com:443 in Salesforce->requestToken()

indicates the problem connecting to Salesforce endpoint it-self (check requestToken() in includes/salesforce.inc for more details).
To diagnose the problem, please check Reports » Status report if you've got HTTP Failure error and that your localhost can connect to Salesforce end point via curl:
$ curl login.salesforce.com:443

If your curl is connecting fine and you've still HTTP Failure error in your Status report, then try to:

Temporary disable Secure Site or Secure Pages modules if present.
Make sure you've firewall (e.g. iptables) and antivirus is switched off (for testing purposes).
Make sure you're not behind the proxy.
Make sure you're not running LAMP in a chroot/jail/VM environment.
Make sure you some network functions aren't disabled PHP functions (e.g. stream_socket_client).
Make sure your PHP is not in Safe mode (safe_mode = On) by:
php -r "var_dump(ini_get('safe_mode'));"

Double check your /etc/hosts or ~/.curlrc doesn't have anything suspicious (you can add insecure to your .curlrc for testing purposes).
Check is there is no any problem with certificates (e.g. your system date is incorrect, you added the certificate and your PHP openssl sees your certificates correctly).
In PHP 5.6 you can specify openssl.cafile and openssl.capath,
e.g. openssl.cafile=/usr/local/etc/openssl/cert.pem

If none of above work, please check below simple PHP script which can check if your PHP can connect to external host:
<?php
fsockopen('ssl://login.salesforce.com',443,$errno,$errstr) ? print("UP") : print("DOWN:".$errstr);
?>

Save it to the file (test.php) and place it inside your web root and open via web browser.
If it fails, it's either problem with your PHP configuration or your network. You can debug it further more by using system call tracer (debugger) as below (install it if required):
$ strace -f -e network php test.php # For Linux
$ truss -f php test.php # For BSD
$ sudo dtruss php test.php # For OSX
# For Windows, you may look for StraceNT.

Then you've to analyse the log for any issues.
Or the following perl script:
use strict;
use warnings;

use LWP::UserAgent;
use Mozilla::CA;
my $ua = LWP::UserAgent->new(
        ssl_opts => {
                verify_hostname => 1,
                SSL_ca_file => Mozilla::CA::SSL_ca_file()
        }) or die;
my $url = $ARGV[0] || 'https://login.salesforce.com/';
my $res = $ua->get($url);
print $res->code . "\n";

exit;

See also:

Using cURL in PHP to access HTTPS (SSL/TLS) protected sites.
SSL Certificate Verification
Using Curl to login to Salesforce API at Salesforce Developers
token failed with status 0! at Salesforce Developers
How to fix Curl Error Ssl Certificate Problem Verify That The Ca Error?
Comment: Kenorb thank you again for all of your help. I finally managed to fix it by adding the following to my php.ini file openssl.cafile=/usr/local/etc/openssl/cert.pem
Comment: Kenorb, thank you. The php fsockopen does fail, so I will try to determine why. I have gone through the check list you provided and so far nothing is setup that would mess up the connection, or at least not based on the list provided above under "If your curl is connecting fine and you've HTTP Failure error, then:" I will continue to troubleshoot
Comment: @jtrenton Added additional info how to debug `fsockopen()` further more.
Comment: Here are the errors I get back FYI:                    Warning: fsockopen(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /Applications/XAMPP/xamppfiles/htdocs/mysites/huawei/web/test.php on line 2

Warning: fsockopen(): Failed to enable crypto in /Applications/XAMPP/xamppfiles/htdocs/mysites/huawei/web/test.php on line 2

Warning: fsockopen(): unable to connect to ssl://login.salesforce.com:443 (Unknown error) in /Applications/XAMPP/xamppfiles/htdocs/mysites/huawei/web/test.php on line 2
DOWN:
Comment: @jtrenton So it's a problem with the certificate, verify that your system date is correct and try adding `insecure` to your `~/.curlrc`. Otherwise try google it.
Comment: Kenorb, thank you again for your continued help. I have tried googling, alot, but still can't determine the issue. If I have set the paths to the certificates in my httpd-ssl.conf & httpd-vhost.conf are those the certs that would be getting picked up? Or does Openssl use a different path when using fsockopen? I also ran sudo dtruss php test.php but to be honest I was not sure what I needed to look for.
Comment: @jtrenton Your main error that you should google for is 'Failed to enable crypto' or 'SSL3_GET_SERVER_CERTIFICATE', one is suggesting to [enable SSL3 as described on SO](http://stackoverflow.com/questions/14078182/openssl-file-get-contents-failed-to-enable-crypto) or [to accept that certificate](http://stackoverflow.com/questions/6400300/https-and-ssl3-get-server-certificatecertificate-verify-failed-ca-is-ok), so you may try to ask another question, as it's specific error about certificate, similar to [this one](http://drupal.stackexchange.com/q/48404/1908).
Comment: So I have googled till my fingers bleed, and still keep getting errors. One thing did which may be part of the problem is I created another php test page and put the following into it:  The info it returns points to the generic openssl directories and not any actual certs. Could this be part of the problem? Do I have to adjust the openssl.cnf file in order for this to work?
Comment: Also is there a conflict with my Mac Openssl and the Openssl provided by XAMPP? I have changed the openssl.cnf file but the paths stay the same.
Comment: @jtrenton Added few links which can be useful. Try somehow to force curl to use `insecure` flag, this could solve the problem I think. Or add this certificate to your system somehow to be permanently accepted.


Django doubling values in queryDict

Question: I create some cascade models, double forms, and set of HTML-s with double views.py in Django. When I want to save data I get a doubling of data that has hidden input attributes.
This is from my forms.py
class TaskContentForm(forms.ModelForm):

    task = forms.ModelChoiceField(
        queryset=Task.objects.all(),
        label="Task",
        widget=forms.HiddenInput(),
        required=True,
    )
    position_label = forms.CharField(
        label="Position Label",
        widget=forms.TextInput(attrs={"class": "form-control task_content"}),
        required=True,
    )
    position_name = forms.CharField(
        label="Position Name",
        widget=forms.TextInput(attrs={"class": "form-control task"}),
        required=True,
    )

Models.py
class TaskContent(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    position_label = models.CharField(max_length=100)
    position_name = models.CharField(max_length=100)

edit_content.html

Transaction information

      <form action="{% url 'task_contents' task=task.id pk=task_content.id %}" method="post"> {% csrf_token %} {% if task.id %} <input type="hidden" name="task" value="{{ task.id }}"> {% endif %}
 {% for field in form %}

{{ field.label_tag }}{{ field }}

 {% endfor %}

          Delete
          <button type="submit" class="btn btn-primary">Save</button>

      </form>

When I press submit, I get terminal output:
`{'_state': <django.db.models.base.ModelState object at 0x00000203DFEC5A20>, 'id': 8, 'task_id': 4, 'position_label': '1032', 'position_name': 'Kvaka', 'material': 'Silumin', 'material_supplier': '', 'request_date': datetime.date
(2023, 5, 6), 'realization_deadline': None, 'construction_tool': '', 'tool_request_date': None, 'tool_realization_deadline': None, 'tool_creation': '', 'tool_creation_request_date': None, 'price': None}
Task: 4
Form data: <QueryDict: {'csrfmiddlewaretoken': ['tZ4zbHs5HeRhQHB1T4vuo66DwK5FMl7gcHyFjy3EzegHE4DsNjktlLnW9DQkDX1T'], 'task': ['4', ''], 'position_label': ['1032'], 'position_name': ['Kvaka'], 'material': ['Silumin'], 'material_s
upplier': [''], 'request_date': ['2023-05-06'], 'realization_deadline': [''], 'construction_tool': [''], 'tool_request_date': [''], 'tool_realization_deadline': [''], 'tool_creation': [''], 'tool_creation_request_date': [''], 'p
rice': ['']}>`

This is views.py class TaskContentView, method Update_instance responsible for rendering.
def update_instance(self, request, task, pk, is_urlencode=False):
    task_content = self.get_object(pk)

    print("Before form submission:")
    print(task_content.__dict__)

    task_obj = get_object_or_404(Task, id=task)
    form_data = QueryDict(request.body) if is_urlencode else request.POST

    print("Task:", task)
    print("Form data:", form_data)

    form = TaskContentForm(form_data, instance=task_content)
    if form.is_valid():
        task_content_instance = form.save(commit=False)
        task_content_instance.task = task_obj
        task_content_instance.save()

        if not is_urlencode:
            messages.success(request, "Transaction saved successfully")
        return True, "Transaction saved successfully", form

    if not is_urlencode:
        messages.warning(
            request, "Error UpdateURL Occurred. Please try again."
        )
        print(
            form.errors
        )  # Add this line to display form errors in the console
    return False, "Error Update Occurred. Please try again.", form

Where could be my mistake?
I wanted to make it work, but I am getting a browser error:

Error UpdateURL Occurred. Please try again.
Answer: I found the issue here. I just excluded task variable from for loop.

                        {% for field in form %}
                            {% if field.name != 'task' %}

{{ field.label_tag }}{{ field }

                            {% endif %}
                        {% endfor %}

Django doubling values in queryDict


Winforms Designer errors when changing accessibility of a control

Question: I decided to change a listBox1 item in my form1 designer to public static instead of private to access it on another form. And once I had done that It had errored and not allowed me to changed things on the form itself and just tells me this error at the top
  The variable 'listBox1' is either undeclared or was never assigned.

The error is shown on the following line
this.panel1.Controls.Add(listBox1);

My Designer for my form below:
  namespace Mercury.Forms
  {
partial class Inside
{
    ///
    /// Required designer variable.
    ///
    private System.ComponentModel.IContainer components = null;

    ///
    /// Clean up any resources being used.
    ///
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
        this.pictureBox1 = new System.Windows.Forms.PictureBox();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.panel1 = new System.Windows.Forms.Panel();
        Inside.listBox1 = new System.Windows.Forms.ListBox();
        this.label3 = new System.Windows.Forms.Label();
        this.panel2 = new System.Windows.Forms.Panel();
        this.button1 = new System.Windows.Forms.Button();
        ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
        this.panel1.SuspendLayout();
        this.SuspendLayout();
        //
        // pictureBox1
        //
        this.pictureBox1.BackColor = System.Drawing.Color.White;
        this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
        this.pictureBox1.Image = global::Mercury.Properties.Resources.pooltablegodass_500x750;
        this.pictureBox1.Location = new System.Drawing.Point(12, 11);
        this.pictureBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(54, 48);
        this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
        this.pictureBox1.TabIndex = 0;
        this.pictureBox1.TabStop = false;
        this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.label1.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
        this.label1.Location = new System.Drawing.Point(74, 15);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(82, 20);
        this.label1.TabIndex = 1;
        this.label1.Text = "Ash Smith";
        this.label1.Click += new System.EventHandler(this.label1_Click);
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
        this.label2.Location = new System.Drawing.Point(76, 37);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(66, 13);
        this.label2.TabIndex = 2;
        this.label2.Text = "ashleytechie";
        this.label2.Click += new System.EventHandler(this.label2_Click);
        //
        // panel1
        //
        this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
        this.panel1.Controls.Add(this.button1);
        this.panel1.Controls.Add(this.label3);
        this.panel1.Controls.Add(listBox1);
        this.panel1.Controls.Add(this.label2);
        this.panel1.Controls.Add(this.label1);
        this.panel1.Controls.Add(this.pictureBox1);
        this.panel1.Location = new System.Drawing.Point(0, 0);
        this.panel1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.panel1.Name = "panel1";
        this.panel1.Size = new System.Drawing.Size(200, 348);
        this.panel1.TabIndex = 3;
        //
        // listBox1
        //
        listBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
        listBox1.BorderStyle = System.Windows.Forms.BorderStyle.None;
        listBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        listBox1.ForeColor = System.Drawing.SystemColors.Window;
        listBox1.FormattingEnabled = true;
        listBox1.ItemHeight = 15;
        listBox1.Items.AddRange(new object[] {
        "Jake Simpson",
        "Adam Jones",
        "Jane Peters",
        "Ashley Smith",
        "Sam Smith",
        "Joe Phelan",
        "Peter Black",
        "Tracy Bratford",
        "Jamie Harrison",
        "Peter Slims"});
        listBox1.Location = new System.Drawing.Point(16, 107);
        listBox1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        listBox1.Name = "listBox1";
        listBox1.Size = new System.Drawing.Size(144, 180);
        listBox1.TabIndex = 3;
        listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
        //
        // label3
        //
        this.label3.AutoSize = true;
        this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.label3.ForeColor = System.Drawing.SystemColors.Window;
        this.label3.Location = new System.Drawing.Point(12, 79);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(105, 24);
        this.label3.TabIndex = 4;
        this.label3.Text = "Contact List";
        //
        // panel2
        //
        this.panel2.Location = new System.Drawing.Point(205, 7);
        this.panel2.Name = "panel2";
        this.panel2.Size = new System.Drawing.Size(518, 335);
        this.panel2.TabIndex = 4;
        //
        // button1
        //
        this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.button1.ForeColor = System.Drawing.SystemColors.ButtonHighlight;
        this.button1.Location = new System.Drawing.Point(16, 304);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(170, 31);
        this.button1.TabIndex = 5;
        this.button1.Text = "Edit Profile";
        this.button1.UseVisualStyleBackColor = true;
        //
        // Inside
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.BackColor = System.Drawing.SystemColors.ButtonHighlight;
        this.ClientSize = new System.Drawing.Size(730, 347);
        this.Controls.Add(this.panel2);
        this.Controls.Add(this.panel1);
        this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
        this.Name = "Inside";
        this.Text = "Inside";
        this.Load += new System.EventHandler(this.Inside_Load);
        ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
        this.panel1.ResumeLayout(false);
        this.panel1.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.PictureBox pictureBox1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Panel panel1;
    public static System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Panel panel2;
    private System.Windows.Forms.Button button1;

}
}

Comment: If you find yourself ever needing to change the designer file, then its a 100% guarantee you are doing something wrong.
Comment: `do not modify the contents of this method with the code editor.`  why not create a method to allow the data to be passed and leave the forms alone?
Comment: I agree with @icemanind on this one, but change it to be 99.9%. There have been times that the designer gets messed up and I've had to manually clean up some code in there for the designer to be happy and start working with it again.
Comment: Can you tell me how I could do this please?
Comment: I'd even lower what @icemanind said down to 90%. I've had *many* controls not serializing as properly as they should (specially when doing visual form inheritance with collection properties) and had to fix .Designer.cs files manually way more times than I wished.
Answer: Change this back to what it was previously: (public to private, remove static)
public static System.Windows.Forms.ListBox listBox1;

Add this in the code-behind in your Form: (you don't need a setter since you won't be creating a new ListBox from the other Forms... I hope)
public ListBox MyListBox
{
    get { return listBox1; }
}

Now in other Forms (assuming they're being created by some process in your first Form), you'll pass a reference to the current instance of your Form with the ListBox on it, so you can actually access the public property you just created:
public class SecondForm : Form
{
    public SecondForm(FirstForm firstForm)
    {
        // do something with firstForm.MyListBox
    }
}

Lastly, I'd say be careful how much you do this. Forms being able to access each other's controls seems messy to me. If you added more details about exactly what you're trying to accomplish with this, we might be able to provide a better alternative.
Comment: `public MyListBox` is invalid code (no type defined, should be `public ListBox MyListBox`)... but even if it wasn't, what'd be the problem on having the original `listbox1` public if he is to access it via the instance? No need to create extra properties for that (if anything, I'd create a property for the listbox property you want to access, but definitely but not for the listbox itself).
Comment: Well, except for the fact that in the example it'd be named `listBox1`, I don't see why there should be a greater reason to rename a control than there would be to rename a property (one must assume that controls are generally members of the class you are defining, and follow the same method you'd follow with any other class members). And yes: the second part of your comment is definitely the way to go
Answer: Your issue is that you changed the code in the designer file so that listBox1 is now static. You can't do this because the designer must be able to instantiate an instance of ListBox.
What it sounds like you are trying to do is you are trying to modify the listbox from another form. The proper way you should do this is through properties. In your code (not the designer code, but the code behind code), have something like this:
public ListBox MyListBox
{
    get
    {
        return listBox1;
    }
}

Answer: You shouldn't change anything in the .Designer.cs file. If you want to change access modifiers you should do so through the Properties window.
That being said, your public change was fine, you just can't make it static. For the designer to function all the controls in the form must be independent to each instantiation.
// what the code will look like when you change it from the Properties window
public System.Windows.Forms.ListBox listBox1;

If you were to make the ListBox static, you would access it like
ListBox listbox = Inside.listBox1;

which doesn't make much sense if you have more than one Inside form floating around. If you make it non-static you can still access it from wherever you want as long as you have an instance of the Inside class.
Inside inside = new Inside();
ListBox listbox = inside.listBox1;

Comment: @AshSmith Yes, but you have to access it from an instance of your form.
Comment: I still can't access it in other forms with just public, should I be able to?
Comment: No, you should never touch the .Designer.cs file.
Comment: I said don't touch the file - I didn't say don't touch the Property grid.


How to publish custom artifacts to Artifactory from TeamCity?

Question: I am using Artifactory and TeamCity and have a C++ project that generates binary packages (zip). Using Artifactory TeamCity plugin I am able to publish this artifact but the problem is that it does not end up in the correct tree (organization.module.version.artifact). Next to the zip file I have also an ivy.xml file that contains information about the artifact.
<code><ivy-module version="2.0">
    <info organisation="com.myorg" module="MyModule"/>
    <publications>
        <artifact name="MyModule" type="zip" ext="zip"/>
    </publications>
</ivy-module>
</code>
When I look in Artifactory at the Artifact browser the uploaded zip has even no Module-Id.
Any ideas how to tell the TC plugin to make use of this configuration file so that my zip is deployed correctly?
Regards,
Martin
Answer: One solution for your problem:

Make sure that your file is in the right layout after the build, for example
workspace..\..com\myorg\MyModule\2.0\MyModule.zip
Use the Ant pattern in the Artifactory plugin, in your case 'workspace.../*.zip=>
If the right side of the pattern is left empty, the plugin will
deploy the artifacts maintaining the relative path for each file.
So in your case, the file will be stored in the Artifactory repository:
repository:com->myorg->MyModule->2.0->somefile.zip


Lagrange formula for solving linear differential equations

Question: I am studying control systems, and my textbook uses "Lagrange's formula" for solving time-continuous linear systems in "state-space". Below are the equations presented:
$$\dot{x}(t) = Ax(t) + Bu(t)$$
$$y(t) = Cx(t) + Du(t)$$
where A,B,C and D are matrices of coefficients, but let's assume they are all singular to make things simpler.
Assuming that $t > t_0$ and $x(t_0) = x_{t_0}$,the formula used to calculate $x(t)$ is the following:
$$x(t) = e^{A(t-t_0)}x_{t_0} + \int_{t_0}^t e^{A(t-\tau)}Bu(\tau) d\tau $$
This formula is very similar to another formula I learned in calc 2 for an identical purpose, albeit this next formula is defined for all values of t and contains an indefinite integral in place of the definite integral in the formula above
$$ x(t) = e^{-At} \int Bu(t)e^{At} dt $$
It is obvious to me that these formulas are strongly connected, but whereas I understand how the second one is derived, I cannot say the same about the first one. And what is up with using $\tau$ as the variable for intergration? I've been told it is a "dummy variable", but it was presented as a fact, rather than a proven result of calculus.
I've also tried to google this so-called "Lagrange formula", but unfortunately I haven't had any success with it. Can anybody please help me understand this?
Comment: The indefinite integral can be written as follows:
$$ \int f(t) \, dt = \int_{t_0}^t f(\tau) \, d\tau + C ,$$
where $C$ is some constant.
Comment: What book is it ?
Comment: @StephenMontgomery-Smith Ok, but why? I thought definite integrals had only one solution, rather than a family of solutions that vary based on the $C$ parameter. And also why do we use $\tau$ as the variable of intergration? I would like to read more about this topic, can you tell me what it is called so I can do my own research?
Answer: It is simply notation.  The indefinite integral is computed using the anti-derivative:
$$ \int f(t) \, dt = F(t) + C $$
where $F'(t) = f(t)$, and $C$ is a constant.  Then the definite integral is
$$ \int_a^b f(t) \, dt = F(b) - F(a) .$$
In this second equation, the $t$ is a 'dummy variable.'  I could just as well write
$$ \int_a^b f(\tau) \, d\tau = F(b) - F(a) .$$
In particular, to avoid confusion, we make sure that the dummy variable is not the same as the variables we use in the limits (or anywhere else).  So if I want to write
$$ \int_{t_0}^t f(\tau) \, d\tau = F(t) - F(t_0) $$
it would be confusing if I used the letter $t$ as the dummy variable.
And look
$$ \int f(t) \, dt = \int_{t_0}^t f(\tau) \, d\tau + C_1 $$
where $C_1 = C + F(t_0)$.
Finally, we have this formula:
$$ g(t) \int f(t) \, dt = g(t) \left(\int_{t_0}^t f(\tau) \, d\tau + C_1\right)
= \int_{t_0}^t g(t) f(\tau) \, d\tau + C_1 g(t) .$$
This last formula would be nonsense if we didn't change the dummy variable to something other than $t$.
Comment: That's it! Thank you so much
Answer: The first formula is obtained by applying the Lagrange method of constant variation:
First, the ODE is linear so it can be solved as
$$
\cases{
\dot x_h = A x_h\\
\dot x_p = A x_p + B u\\
x = x_h + x_p
}
$$
The homogeneous has as solution $x_h(t) = e^{A t}C_0$ (here $C_0$ is a constant array) now making $x_p = e^{A t}C_0(t)$ (note that in the method "variation of constants" due to Lagrange, we assume now that $C_0=C_0(t)$ is an array of functions $t$ dependent) and substituting we have
$$
Ae^{At}C_0(t)+e^{At}C_0'(t) = Ae^{At}C_0(t) + B u(t)\Rightarrow C_0'(t) = e^{-A t}B u(t)
$$
and then
$$
C_0(t) = \int_0^t e^{-A\tau}B u(\tau) d\tau
$$
and finally
$$
x = x_h+x_p = e^{A t}C_0 + e^{A t}\int_0^t e^{-A\tau}B u(\tau) d\tau = e^{A t}C_0 + \int_0^t e^{A(t-\tau)}B u(\tau) d\tau = e^{At}\int e^{-A \tau}B u(\tau) d\tau
$$
note that here $C_0$ is a constant array
Comment: If $C_0$ is a function of time, why do you integrate for $\tau$ in order to "cancel out" the derivation? And what theorem/property allows you to do so? I realize there are several steps to get to the formula I want to understand, but I would like to understand why we _can_ take each of these steps.

I also don't understand why you end up with $-B\tau$ as an exponent in your formula for $C_0(t)$
Comment: The only typo was fixed. $e^{-A\tau}$ instead of $e^{-B\tau}$.
Comment: Can you help me answer my follow up questions?
Comment: I introduced some additional comments in order to better explain the method. I hope it helps.
Comment: Now I think I get most of what you are saying, but I still can't wrap my head around why you integrate with respect to $\tau$
Comment: Think that $\sum_{i=0}^n a_i = \sum_{k=0}^n a_k $ and $\int a(t) dt = \int a(\tau) d\tau$


Split up $n \in \mathbb{N}$ into sum of naturals with maximum LCM

Question: Question:
Given some natural number, we can of course split it up into various sums of other naturals (e.g. $7 = 6 + 1 = 1 + 4 + 2 = \ldots$)
More precisely, for $n \in \mathbb{N}$, we can a find distribution sequence (or partition) $s_0,\ldots,s_u \in \mathbb{N}$ with
$$\sum_{i=0}^{u}s_i = n$$
Now how can I find the partition $s$ for which the overall least common multiple of all elements is maximal.
Or differently formulated the maximum product of distinct prime factors of all elements.
Example:
$$ 7 \mapsto (3, 4); \Pi_{lcm} = 12 $$
$$ 7 \mapsto (1, 2, 4); \Pi_{lcm} = 4$$
$$ \ldots $$
Here, the first solution is the desired one.
Background:
The background of my question is: How can I split up a sequence/string into contiguous subsequences that, when repeated and zipped together, will yield the longest possible resulting sequence.
For the above example, I could split up a string of length $7$ in the following way:
<code>7: abcdefg 7:  abcdefg

    I              II
1: aaaa    3: abcabcabcabc
2: bcbc    4: defgdefgdefg
4: defg
</code>
Of course, using the second distribution, the resulting sequence has a much greater period.
So:
What algorithm/approach can I use to solve this problem and maximize the product? Is this some known problem and how complex would calculating a solution be? It's not NP, I hope?!
Edit: Partial solution
As @KennyTM pointed out in the comments, Landau's function $g$ describes the maximum LCM, i.e. $g(7) = 12$.
So this actually becomes: How to actually produce the partition? Does knowledge of $g(x)$ help here, maybe for a dynamic programming solution?
Comment: The LCM values seems to follow [A000793](http://www.research.att.com/~njas/sequences/A000793). Edit: Well the definition *is* [Landau's function](http://en.wikipedia.org/wiki/Landau%27s_function).
Comment: @KennyTM: Cool, thanks - Landau's function. Edited the question from this ...
Answer: The blog post here describes somebody else's efforts at coding this up. He gets an improvement over the naive approach by using some nice internal structure of the problem.
Comment: Perfect, that was the kind of solution I was looking for. Nice dynamic programming.


Como mascarar um input no HTML5?

Question: Por exemplo... Quero um input exclusivo para números de telefone. Ao digitar o DDD ele automaticamente recebe os parênteses: (xx). Ao digitar o restante dos números ele divida com um hífen, por exemplo: (xx)abcd-efgh. E nos casos de estados que receberam o nono dígito, (xx)9abcd-efgh.
Como posso fazer isso?
Comment: Pelo que entendi você quer mascarar o que o usuário digita é isso?
Comment: Mais ou menos, tipo... Quando ele clicar no input já aparece os parenteses para colocar o ddd por exemplo, tem um type padrão para isso?
Comment: @Everton No caso você está querendo mascarar um `input`. Fiz uma edição na sua pergunta, alterando o título. Você pode [revertê-la](http://pt.stackoverflow.com/posts/51109/revisions) caso não apresente melhorias.
Answer: Você pode mascarar um campo utilizando:

JQuery Mask Plugin
Documentação

Exemplo de uso:
$(document).ready(function(){
    $('#telefone').mask('(00) 0000-0000');
});

Ou no próprio html:
<input type="text" name="telefone" data-mask="(00) 0000-0000" data-mask-selectonfocus="true" />

Você também pode aplicar callback, em fim... há vários exemplos na documentação que se encaixam a sua necessidade..

Para casos em que o estado possua o nono dígito, você pode utilizar a
  mudança On-the-fly: Exemplo retirado da documentação, necessita apenas
  a adaptação a sua necessidade:

var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00000-000', '0-00-00-00'];
    mask = (cep.length>7) ? masks[1] : masks[0];
  $('.crazy_cep').mask(mask, options);
}};

$('.crazy_cep').mask('00000-000', options);

Ou a solução que o @Wallace forneceu nos comentários que seria assim:
$(document).ready(function(){
    $('#telefone').mask('(00) 0000-0000#');
});

Ou também a seguinte expressão:
$(document).ready(function(){
    $('#telefone').mask('(00) 0000-00009');
});

Onde o 0 seria obrigatório e o 9 opcional;
@Wallace também citou a validação utilizando HTML5.
Comment: Para os casos onde existem o tal do "nono dígito", creio que se possa usar a expressão `(00) 0000-0000#`
Comment: Ou também a atualização da máscara On-the-fly, existe um exemplo da documentação fornecida; Vou editar a resposta para fornecer a solução também;
Answer: O que você está querendo pode ser feito facilmente com jQuery Mask.
O seu uso se dá exatamente como o @RafaelWithoeft descrever em sua resposta.
$(document).ready(function(){
    $('[name=telefone]').mask('(00) 0000-0000');
});

Quanto a fazer isso somente com o HTML5, o que você vai conseguir fazer no máximo é utilizar o atributo pattern. Porém este atributo não vai servir para o autopreenchimento, mas apenas para a validação do campo conforme o formato desejado.
Por exemplo, no caso de uma validação de um telefone:
<input type="text" pattern="\(\d{2}\)\d{4}-\d{4}" />
#exige que o campo seja preenchido com "(99)9999-9999"

Answer: Para quem quiser uma solução que não utiliza JQuery:

const tel = document.getElementById('tel') // Seletor do campo de telefone

tel.addEventListener('keypress', (e) => mascaraTelefone(e.target.value)) // Dispara quando digitado no campo
tel.addEventListener('change', (e) => mascaraTelefone(e.target.value)) // Dispara quando autocompletado o campo

const mascaraTelefone = (valor) => {
    valor = valor.replace(/\D/g, "")
    valor = valor.replace(/^(\d{2})(\d)/g, "($1) $2")
    valor = valor.replace(/(\d)(\d{4})$/, "$1-$2")
    tel.value = valor // Insere o(s) valor(es) no campo
}
<input type="tel" class="form-control" id="tel" name="tel" maxlength="15" pattern="\(\d{2}\)\s*\d{5}-\d{4}" required>

Como mascarar um input no HTML5?


Switching from piano to harpsichord

Question: I have been playing the piano for the most part of my life, but I am becoming increasingly interested in the harpsichord. Has anyone made this "transition" before? Are there some pitfalls which one should be especially aware of? Assuming I have rather extensively played Bach before on piano (and with decent technique), would it generally be a lot of work invested in order to be able to play Bach fugues on the harpsichord at a satisfactory (or even comparable) level?
Note: I am using the term "transition" only for lack of a better word. I do not intend to give up on playing the piano. Perhaps someone has experience with playing both instruments?
Comment: Excellent question, by the by! Unfortunately, there doesn't seem to be much interest in harpsichords anymore.
Answer: I hope someone with actual harpsichord experience chimes in, since most of what I'm writing here is hear-say.
As you no-doubt already know, the two main things that you lack on a harpsichord, compared to a piano, is a long sustain, and any appreciable dynamics. I've heard that one way to compensate for the lack of dynamics is to vary the duration of the note. If you hold a note for it's full duration, then it is perceived as being louder than if you play with in a more disconnected articulation. Thus articulation is not used so much a means of phrasing, as it is a means of conveying accent and meter.
This emphasis on articulation is addressed, for example, in the following PDF: Elementary Harpsichord Technique, by Roy Truby, originally published in The English Harpsichord Magazine (1975), and reproduced (with many other articles) at http://www.harpsichord.org.uk/EH/ehm.htm. It stresses playing with a more detached (non-legato) articulation, and taking care to not slur from a weak beat to a stronger beat (unless specified by the composer). OTOH, it also warns against hyper-correcting, and playing everything staccato.
Another technique for accenting notes is to use ornamentation (trills, mordents, and the like), which was a very important aspect of Baroque keyboard music, about which, much has been written. Trills can also help with sustained notes, since you'll often find a trill placed over a long note, so as to sustain the sound from that note.
For larger sections of dynamic (and tonal) contrast, some harpsichord are endowed with alternate stops or registers -- differing sets of strings, with different tonal qualities, which can be played, either individually, or sometimes coupled. Perhaps the most recognizable of these is "Lute Stop", which has a very thin, veiled sound, like a lute (hence the name). By some accounts, this affect was much-loved by Bach.
Another effect, which you probably can't get on a digital piano (unless it has fairly sophisticated acoustic modelling), is sympathetic vibration. That is, if you continue to hold a key down, even after it's sound has died away, the string will still be able to vibrate whenever it shares a common overtone with another string that's being played. This can lead to a fuller, more resonant sound. This effect happens on pianos as well, but (at least without the sustain pedal) it can be less noticeable, given the piano's greater ability to sustain notes. This is also a reason why playing in justly-tuned keys (rather than Equal Temperament) sounds better -- there are more shared overtones, leading to more resonance.
You may also want to check out the classic period text on the topic: Essay on the True Art of Playing Keyboard Instruments by C.P.E. Bach (perhaps the most famous of J.S.'s numerous children).
Comment: No variation in dynamics, to be sure, Caleb, but actually a good harpsichord has sustain comparable to most pianos, despite the softer tone. Check out these two rather good renditions of Scarlatti's K208: [piano](https://www.youtube.com/watch?v=3H93fMF2f7c)
[harpsichord](https://www.youtube.com/watch?v=eGg7tZ_0Rq0)

The melody is being played slightly _perlé_, but listen to the held notes at the section cadences.
Answer: I played piano for 10 years before starting harpsichord.  I largely play harpsichord now, although I do a lot of pinch-hitting on piano for church services, etc.
Learning to play harpsichord well will expand your mind as a pianist and  open up new performance opportunities.  Additionally, there are many fantastic Baroque composers that are rarely heard because their harpsichord pieces do not transfer well to piano.
It is a mistake to think of a harpsichord as a piano without x (without dynamics, without sustain, without pedals, etc.)   Harpsichordists create dynamics and sustain sound differently. For example, a harpsichordist might create dynamics through how long they hold notes, overholding notes, arpeggiating chords, how quickly they "attack" the notes, and other tricks.    Similarly, there are ways to sustain sound on the harpsichord.
In addition, fingerings on the harpsichord are somewhat different.  Articulations, rarely specified in Baroque pieces, are not absent but instead must be chosen.  Many composers had ornament tables: composer-specific signs for different trills and mordents.  In repeated sections it is typical to add ornamentation, and what kind of ornamentation should be added depends on the composer and time period of the piece.
If you are serious about this endeavor, it worth having a lesson with a professional harpsichordist to demonstrate some of these techniques.  If you read French (or can find a reasonable English translation), this is a great treatise on French harpsichord playing that touches on the mindset and considerations of performers and composers of the time.
Answer: As a harpsichordist and pianist, I can say switching from piano to harpsichord should not pose any significant challenges. I started playing keys on an 88 key keyboard, and then went on to transition to harpsichord, and then a grand piano. As Tim mentions, dynamics do not exist on a harpsichord.
Anything that you can play on a piano you'll be able to play on the harpsichord sans the dynamics, of course. So the Bach fugues that you play on the piano will translate well to the harpsichord. I find it a little easier to play the harpsichord, but I also feel that the lack of dynamics makes the instrument a little less forgiving. Your playing becomes very transparent.
The action on a harpsichord is quite different from a grand piano, or even an electric 88 key keyboard. Unfortunately, the actions on harpsichords in general vary greatly between harpsichords. It may take you a little bit of time to get used to the action. I have played several harpsichords, and I find that most of them have a much lighter action than any piano I've ever played, excluding 61-76 key keyboards.
You should have no issues transitioning from piano to harpsichord.
Answer: I think everyone has touched upon the "aural" feel of a harpsichord and the lack of a real sustain. I'll address the physical aspect of playing a harpsichord. In the piano, you have a hammer striking the strings, whereas in a harpsichord, the strings are plucked. In the case of the plucking, you need to have a certain amount of force (usually same across all keys) to make the keys sound. I had many instances in where, like a pianist, I would "soften" my touch in the more quiet parts but then the harpsichord wouldn't sound! The piano has a low force threshold to produce any sound, but the harpsichord's threshold is much higher. To summarize, on the harpsichord, you need a higher average / more even force and a quicker attack especially if the keys are deep.
Second, the keys are also narrower on the harpsichord, so it may be a good idea to do some arpeggios or scales before each practice session to acclimate your fingers and hand position.
Answer: There are many preconceptions about switching from piano to harpsichord, as many people assume, since the keyboard is similar, that the techniques associated with piano are transferable.
It is possible for pianists to thrash out pieces on the harpsichord, but it's a huge mistake to assume that piano playing and harpsichord playing are the same thing.
An easy way to spot a pianist vs someone trained in harpsichord is the hand shape and use of the arm. Also, the fingerings are quite different, but more important is the hand shape.  For harpsichord, the fingers are not stretched out but curl under the hand, not protruding outward when passages are played, and the arm is never needed to deliver force, it all comes from the finger joints.
Pianists automatically attack the keyboard making a harsh tone and loud banging; the force needed for the plectrum to pass through is minimal.
To take the instrument seriously means changing your entire way of touching the instrument if you have been playing pianos beforehand. This means going back to learning all scales and fingerings anew.  This takes years until the old habits are gone and the new ones set in.
Very few piano pieces sound well on the harpsichord either, only serving as a very short novelty. It's an instrument you should commit to if taking it up -- or it will always be a novelty.
As a commenter pointed out, playing Bach's fugues on a harpsichord as you would on a piano will have a bad effect. Don't make the mistake that years of training on piano makes an able harpsichordist, The touch, theory of harmony and spirit should be given the respect they deserve.
Any pianist should try a harpsichord; but give yourself a few years and think honestly about your touch/style/understanding vs what's stated in the actual treatises written before the 1800s, not what your piano teacher says.
Answer: No experience on a proper harpsichord, but my piano (electronic) has a harpsichord setting. Obviously the sound is fine, but it also disables the touch sensitivity. So from that aspect, it's possibly easier to play stuff, as dynamics don't exist! Since I play fairly percussively and dynamically on piano, it feels odd that nothing happens! Action wise - don't know about a real harpsichord. Are new ones still available to buy?
Comment: Apparently, check e.g. http://harpsichord.com. There's even a digital version http://www.roland.com/classic/c30/meet/.
Comment: New ones are still available to buy. There are several well known builders who still make new ones. Zuckermann is one of the most popular harpsichord makers.
Answer: I recently bought a Dolmetsch spinet harpsicord after playing piano my entire life.  As I just retired I was going to build a harpsicord but found the spinet.  I have found the touch to be very different.  Of course, there are no dynamic changes or pedals so there is an interpretive learning curve.  However the greater difference is the care the harpsicord needs in terms of tuning, dealing with temperature and humidity as the effect the action.  So the switch is from being a musician to being a musician/caretaker.  I use Kortick's book the harpsicord owners guide and recommend it as essential to a new Harpsicord caretaker/owner.  As he lives within 2 hours I did have him give my instrument a fine tune up and so have a great little instrument but it takes some adjustments almost every day.  It is well worth the time as it us a different and somehow more rewarding experience than the piano.  Best wishes.
Answer: I recently started a degree in harpsichord after playing the piano. You do need a different set of techniques for the harpsichord, especially if your goal is to always produce the best quality sound. On the harpsichord, the slightest motion will make a difference so a good way to practice is to experiment with the sound by using different touches. Of course, the key is listening, your fingers will follow the sound that your brain tries to projects. Some say you should only finger movements given the light touches of harpsichord keys. It is not always case. I find that small wrist/arm movements can be conductive to producing better sound in certain instances. You should also be aware of the fact that most harpsichords are one of kind, which means you need to constantly adjust (more than you would on different pianos). Again, if you know what you want to hear, the fingers will naturally follow.

Switching from piano to harpsichord


Linear function in normed vector space (Folland, Real Analysis Exercise)

Question:
$\textbf{Exercise12}$ Let $X$ be a normed vector space and $M$ be a proper closed subspace of $X$.
(1)  $\Vert x+M\Vert = \inf\{\Vert x+y \Vert : y\in M \} $ is a norm on $X/M$.
(2) For any $\epsilon>0$, there exists $x\in X $ such that $\Vert x \Vert =1 $ and $\Vert x+m \Vert \geq 1-\epsilon$.
(3) The projection map $\pi(x)=x+M$ from $X$ to $X/M$ has norm 1.
(4) If $X$ is complete, so is $X/M$.

I already proved Exercise 12. I stuck the following problem -(b).

$\textbf{Problem}$ Suppose that $X$ and $Y$ are normed vector spaces and $T \in L(X,Y)$ where $L(X,Y)$ be the space of all bounded linear maps from $X$ to $Y$. Let $N(T)=\{x\in X: Tx=0\}$. (Actually, $N(T)=\ker(T)$).
a. $N(T)$ is a closed subspace of $X$.
b. There is a unique $S \in L(X/N(T),Y) $ such that $T=S \circ \pi$ where $\pi :X \rightarrow X/N(T)$ is a projecion. Moreover, $\Vert S \Vert = \Vert T \Vert$ .

Firstly, I proved (a) in problem. Thus, I want to use the Exercise 12 for proving (b). However, I couldn't prove the uniqueness.

$\textbf{Attempt}$ Suppose $S_1,S_2 \in L(X/N(T),Y)$ such that $T=S_1\circ \pi$ and $T=S_2\circ \pi$. Then, $(S_1-S_2)\circ \pi =  0$. And, I have $\Vert \pi \Vert =1 $  ....

Any help is appreciated...
Thank you!
Answer: Your proof is almost complete. If $S_1\neq S_2$, then there is a $0\neq y \in X/N$ such that $S_1(y)\neq S_2(y)$. There is also $x\in X\setminus N$ such that $\pi (x)=y$. Then $S_1\circ \pi (x)\neq S_2\circ \pi (x)$ and thus the two operators $S_i\circ \pi$ are not equal (and thus not both equal to $T$), so $S$ is indeed unique.
Comment: Thank you!! I clearly understand. But, how to know $\Vert T \Vert = \Vert S \Vert$???
Comment: I get $\Vert T \Vert \leq \Vert S \Vert  \Vert \pi \Vert = \Vert S \Vert$. How to get $\Vert T \Vert \geq \Vert S \Vert$??
Comment: My attempt: $ S = T \circ \pi^{-1}$. Then, $\Vert S \Vert \leq \Vert T \Vert \Vert \pi ^{-1} \Vert = \Vert T \Vert \Vert \pi \Vert ^{-1}= \Vert T \Vert$. Could you see that my attempt is right??
Comment: I'm afraid your attempt is wrong - to take the inverse of any function, it has to be an injection. Consider, however, the following: let $x\in X$ such that $||T(x)||>(||T||-\epsilon)||x||$. Then $||S(\pi (x))||>(||T||-\epsilon)||x||\geq (||T||-\epsilon)||\pi (x)||$, and so we deduce that $||S||=||T||$.
Answer: The condition $T = S \circ \pi$ uniquely determines $S$:
$$S([x]) = S(\pi(x)) = Tx, \quad\forall x \in X$$
and this is indeed well-defined because $[x] = [y] \implies x-y \in N(T) \implies Tx = Ty$.
$S$ is clearly linear.
For the norm we have
$$\|T\| = \|S \circ \pi\| \le \|S\| \underbrace{\|\pi\|}_{= 1} = \|S\|$$
Conversely, for $x \in X$ we have $$\|S([x])\| = \|Tx\| = \|T(x+y)\| \le \|T\|\|x+y\|, \quad\forall y \in N(T)$$
so taking the infimum over $y \in N(T)$ gives
$$\|S([x])\| \le \|T\| \|[x]\|,\quad \forall x \in X \implies \|S\| \le \|T\|$$
We conclude $\|S\| = \|T\|$.


c# ListView Column and items different alignment

Question: Is these possible that in listview column header will be align center and the item of that column will be align right.
For example
<code>Column1 | Column2
item11 | item12
item21 | item22
</code>
I want the Column2 will align center and the (item12 and item22) will align right.
Answer: In a HeaderColumns or in Items in this colums you can try use ItemStyle-HorizontalAlign and ItemStyle-VerticalAlign.
Comment:

as

You can try do something like that.
Comment: hehe. btw is not asp is just C# windows form.
Comment: This code will set your item in your Columns will be "MiddleCenter"
This is code in Forms Designer when you create a DatagridView and you change DataGridViewCellStyle.
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
this.Columns1.DefaultCellStyle = dataGridViewCellStyle1;
this.Columns1.HeaderText = "Column1";

Btw you can do this with your headercolumns with DefaultHeaderCellType
I`m so sorry, I can't find how to design view my code in this. It always in a line.
Comment: It is not also "datagridview" it is "ListView"
Comment: OMG :)) I nerver use ListView in C# WindownForm.
Btw I see in Properties of this ListView have "TextAlign" when you Edit a Columns. Have you try to do that ?
Sr about my English. Itn't good


Why won't this increment and store the value?

Question: If I want to increment a value and then store it in another variable, why is it not possible to do it on one line of code?
This works
var count = 0;
count++;
var printer = count;
alert(printer); //Prints 1

But this doesn't
var count = 0;
var printer = count++;
alert(printer); //Prints 0

Answer: You're using the post-incrementing operator. The increment happens after the assignment expression is complete.
Use the pre-incrementing version instead...
++count;

Or use the += operator...
count += 1;

MDN Operators documentation
Answer: You need to do
var count = 0;
var printer = ++count;
alert(printer);

The JavaScript Arithmetic Operators section of the w3schools page has a decent breakdown with a Try Me lab.  In short, if you do the increment/decrement operation before the variable, it will occur before it is used in the current operation.  If you include it afterwards, it will occur after the current operation.
Answer: It can be done in one line.
//Example 1
var count = 0;
count++;
var printer = count;
alert(printer); //Prints 1

//Example 2
var count2 = 0;
var printer2 = count2++;
alert(printer2);   //Prints 0
printer2 = count2++;
alert(printer2);   //Prints 1

// Example 3, in one line
var count2 = 0;
var printer2 = count2 + 1;
alert(printer2);   //Prints 1

// Example 4, in one line
var count2 = 0;
var printer2 = ++count2;
alert(printer2);   //Prints 1

Answer: ++ changes the results depending on where you use it:
 y = 0;
 x = y++; // post-increment

is equivalent to
 y = 0;
 x = y;
 y = y + 1;

and
 x = ++y; // pre-increment

is equivalent to
 y = 0;
 y = y + 1;
 x = y;


Reducing to regular cardinals in c.c.c. implies same cardinals and cofinalities

Question: In Chapter 14 of Jech's Set Theory, he asserts the following:

Definition 14.33. A forcing notion $P$ satisfies the countable chain condition (c.c.c.) if every antichain in $P$ is at most countable.

Theorem 14.34. If $P$ satisfies the countable chain condition then $V$ and $V[G]$ have the same cardinals and cofinalities.

The proof begins with

It suffices to show that if $\kappa$ is a regular cardinal then $\kappa$ remains regular in $V[G]$.

The proof continues, but my main point of confusion lies at the very beginning. Why is it sufficient to prove that regular cardinals remain regular? How does it follow from this that all cardinals and cofinalities are preserved?
Comment: Doesn't it follow from that fact that any limit cardinal is the union of a cofinal set of successor cardinals?
Comment: Please do not use images to convey information not otherwise available in your post. [Here is an explanation why](https://math.meta.stackexchange.com/a/34123/742).
Comment: @ArturoMagidin Sorry about that—I was not aware. The question has been edited.
Answer: If $\mu$ has cofinality $\kappa<\mu$, and we changed the cofinality of $\mu$, then we had to have changed the cofinality of $\kappa$ as well, since the new cofinal sequence will define a cofinal sequence in $\kappa$.
This means that $\kappa$ is no longer a regular cardinal, as it was in the ground model, being the cofinality of $\mu$. And quite often, it might be that $\kappa$ is not a cardinal at all in $V[G]$.
So if a forcing preserves regularity, then it preserves cofinalities as well.


Prod CentOS core-only site work fine but local Ubuntu backup has no css loaded

Question: I made a backup of my prod CentOS site to local Ubuntu. The site is all core --- Both by means of templates or modules; No contribs whatsoever. No customizations.
Yet the CSS won't load for whatever theme.
These are the only errors in drush ws --full
 128377  file      File temporary://filedOb2TA could not be moved/copied because the destination directory public://js is not configured correctly.   notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128376  file      The file permissions could not be set on public://js.                                                                              error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128375  file      File temporary://fileEzTm0r could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128374  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128373  file      File temporary://fileBagPhj could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128372  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128371  file      File temporary://fileII1wDa could not be moved/copied because the destination directory public://css is not configured correctly.  notice    http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128370  file      The file permissions could not be set on public://css.                                                                             error     http://localhost/benia/  127.0.0.1  19/Aug 22:15
 128369  file      File temporary://fileYPV93p could not be moved/copied because the destination directory public://js is not configured correctly.   notice    http://localhost/benia/  127.0.0.1  19/Aug 22:06
 128368  file      The file permissions could not be set on public://js.

Trying to fix it, I made sure that under admin/config/media/file-system the tmp folder is /tmp and then created a directory named tmp folder in root and gave it 755. I also gave 755 to sites/default/files

Tried 777 for both (including sudo chmod 777 files/ -R).
Tried sudo chgrp www-data files -R

While reading on how to fix these in D.O but it wasn't quite clear from what I've read; Most solutions included patches and I don't think its valid for my case. Maybe a Linux expert could shed some light why it happens.
Answer: Did you try the 777 recursively inside the files folder? (so it applies on files/css and files/js subfolders)
Also I would check if SELinux is enabled on your CentOS server to discard you downloaded an incomplete copy of your website due to lack of permissions. Use the getenforce command to check if it's set to permissive.
In case of necessary you can use the following command to set the context of files folder to read/write:
chcon -R -t httpd_sys_rw_content_t files

Comment: Gave 777 -R to files, didn't help. Seems I need to check what you mention with the server.
Answer: A few thoughts:

Have you made sure that you have a /css and /js folder in your /sites/default/files directory?
Have you tried just deleting these folders and recreating them (I think you should be able to do this without any issues)?
Have you tried turning JS and CSS aggregation off in /admin/config/development/performance to see if that works?
Have you cleared your caches? You can go to /admin/config/development/performance or /rebuild.php to do that.


SQL query to get output from referring data in single table

Question: I have 3 tables and the expected result like this:
This is the example table:

This is the expected output from the table:

To get the result I must refer the id and parentid from table2.
How to write a SQL query based on the pictures above?
Comment: While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example):
(1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements.
(2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL.
(3) Desired output, based on the sample data in #1 above.
(4) Your SQL Server version (SELECT @@version;).
All within the question, no images.
Comment: Can you explain you get `City 3` in the expected output when it isn't in the supplied input?
Comment: @HABO Sorry my mistake it should be City C, thanks for noticing
Answer: You must join table1 to 2 copies of table2, the first is directly linked to the id of table1 and the 2nd is linked to the parentid of table2.
Then join to table3.
SELECT t1.*, t3.city
FROM table1 t1
INNER JOIN table2 c ON c.id = t1.id
INNER JOIN table2 p ON p.id = c.parentid
INNER JOIN table3 t3 ON t3.id = p.parentid


Why the inlet and outlet fluxes are different when I solve the Poisson equation by FEM over a trapezoidal domain?

Question: I solved the Poission equation which is given by
\begin{equation}
\Delta h = 0,
\end{equation}
where $h$, in my case, is the hydraulic pressure. Because I want to solve steady-state flow, the $\nabla h =[\frac{\partial h}{\partial x}, \frac{\partial h}{\partial y}]$ is the flux velocity.
I used the FEATOOL in MATLAB to solve the Poisson equation over a trapezpodal domain, with three-noded triangular elements. The left and right sides are Dirichlet boundary conditions ($h_L = 100$ and $h_R = 20$), and the top and bottom sides are Neumann boundary condition ($\nabla h \cdot \vec{n} = 0$, $\vec{n}$ is the normal vector of boundary). The solved pressure field is as follows:
pressure field
Then I wanted to determine the velocity of each element. Since the pressure value of each node is obtained, I used linear shape function $\vec{N}$ to get velocity:
\begin{equation}
\frac{\partial h}{\partial x} = \frac{\partial \vec{N}^T}{\partial x}\vec{h_e} \text{ and } \frac{\partial h}{\partial y} = \frac{\partial \vec{N}^T}{\partial y}\vec{h_e},
\end{equation}
where $\vec {h_e}$ is the three pressure values of an element, $T$ denotes transpose. The derivates of $\vec{N}$ are
\begin{equation}
\frac{\partial \vec{N}}{\partial x} = \left(b_1, b_2, b_3\right)^T, b_i = \frac{1}{2A}(y_j - y_k),
\end{equation}
where $A$ is the area of an element, and
\begin{equation}
\frac{\partial \vec{N}}{\partial y} = \left(c_1, c_2, c_3\right)^T, c_i = \frac{1}{2A}(x_k - x_j).
\end{equation}
Using the above formulas, the velocity vectors are as follows:
velocity vectors
Finally, I used the $\nabla h \cdot \vec{n} \cdot L_\Gamma$ ($L_\Gamma$ is the length of boundary edge of an boundary element) to calculate the inlet and outlet flux. I found the difference is around 10% (inlet = 10.1017, outlet = 8.9828, error = 0.1108). Why this happened? Is it due to the length difference between inlet and outlet (I found when they are equal, the fluxes are equal)?
I also used quadratic elements, but the same problem happened when the domain is irregular, particularly the lengths of inlet and outlet are different.
UPDATE
With RT0 elements, the inlet and outlet fluxes are the same now! If you are interested, download a matlab script from github (I just revised the original script a little and I still not very clear about mixed FEM).
Answer: This finite element basis (3-noded triangular element) satisfies no discrete conservation properties. In particular, the conservation properties present in the continuous formulation $\Delta h = 0$ do not carry over to the discrete formulation. Moreover, the boundary flux has a quite low convergence rate, if I recall correctly it's $O(h^{1/2})$ for linear elements.
There are other more exotic finite elements and variational formulations that may better satisfy discrete conservation properties. Search for information, e.g., about $H(div)$ conforming finite elements.
Comment: hi, did you mean high order elements like quadratic element? i also tried this and got the same problem.
Comment: No, all of these elements are $H^1$ conforming and have the same problem. Instead you can try, for example, the mixed formulation of the Poisson problem and the Brezzi-Douglas-Marini element.
Comment: thanks! I see a lot of paper use RT0 element to solve the mixed formulation of the poisson equation. I will study that.


Show that $n(2n + 1)(7n + 1)$ is divisible by 6 for all integers $n$ and find all integers $n$ such that $n(2n + 1)(7n + 1)$ is divisible by 12.

Question: a) Show that $n(2n + 1)(7n + 1)$ is divisible by 6 for all integers $n$.
b) Find all integers $n$ such that $n(2n + 1)(7n + 1)$ is divisible by 12.
I tried expanding but it doesn't really help much.  Thanks in advance!
Answer: $$n(2n+1)(7n+1)\equiv n(2n+1)(n+1)\equiv 0\pmod{2},$$
because exactly one of $n$, $n+1$ is even.
$$n(2n+1)(7n+1)\equiv n(-n+1)(n+1)\pmod{3}$$
$$\equiv n(-1)(n-1)(n+1)\equiv 0\pmod{3},$$
because exactly one of $n$, $n-1$, $n+1$ is divisible by $3$.
Therefore $2\cdot 3\mid n(2n+1)(7n+1)$ for all $n\in\mathbb Z$.
The condition $2^2\cdot 3\mid n(2n+1)(7n+1)$ is therefore equivalent to $2^2\mid n(2n+1)(7n+1)$.
Since $2n+1$ is odd for all $n\in\mathbb Z$, this is equivalent to $2^2\mid n(7n+1)$ (by common sense, or you can see Generalized Euclid's lemma. We have $\gcd\left(2^2,2n+1\right)=1$ for all $n\in\mathbb Z$).
$$n(7n+1)\equiv n(-n+1)\equiv -n(n-1)\pmod{2^2}$$
is equivalent to $0$ if and only if either $2^2\mid n$ or $2^2\mid n-1$ (because $n$, $n-1$ are coprime).
The answer is: all $n\in\mathbb Z$ such that $n\equiv \{0,1\}\pmod{4}$.
Comment: Thansk for answering, user236182!


Value of xml node returning as null

Question: I have an xml document that I am loading in my asp .net application. It is structured like this
-<Event>

    <Event_Name>Special Name</Event_Name>
    <Event_Date>5/27/2016 12:00:00 AM</Event_Date>
    <Event_Description>Event Description</Event_Description>

</Event>

I am loading it in my code behind like this
    XmlDocument doc = new XmlDocument();
    string path = Server.MapPath("~/NewsXMLNews.xml");
    doc.Load(path);

This loads properly. The problem is, I want to set the Event_Name as the text of a label on my aspx page. I do this using the following code
   string nameOfEvent = doc.SelectSingleNode("Event_Name").ToString();
   eventName.Text = nameOfEvent;

The problem is that nameOfEvent is coming back as null, so I get a nullReferenceException
I'm not exactly what I'm doing incorrectly here.
Comment:

-
Special Name
5/27/2016 12:00:00 AM
Event Description
Answer: Since you already checked the path is correct and the document is properly loaded I think you just need to change the following line:
    string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;

Edit: I check with following steps that xml loading process works:

I remove the minus before  in described xml file and saved
following lines as c:\temp\Event.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Event>
   <Event_Name>Special Name</Event_Name>
   <Event_Date>5/27/2016 12:00:00 AM</Event_Date>
   <Event_Description>Event Description</Event_Description>
</Event>

Then I succeeded in running:
   public Form1()
   {
       InitializeComponent();
       XmlDocument doc = new XmlDocument();
       string path = "c:\\temp\\Event.xml";
       doc.Load(path);
       string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;
       eventName.Text = nameOfEvent;
   }

In my window I see Label named eventName text is Special Name
as expected.
Comment: I thought this would work. It just sets 'System.Xml.XmlElement' as the text of the label
Comment: @TommasoCerutti - Please don't put lots of code in a comment.  Instead, edit your answer and add the code there.  If the code is already in your answer, then consider deleting your comment.
Comment: The only information in comment is "remove the minus before  in your xml file",
 @ChrisDunaway thank you, I'm deleting comment right now, it was my first one and I din't know code can't be formatted
Answer: This should work:
XmlNode nameOfEvent = doc.SelectSingleNode("/Event/Event_Name");
string text = nameOfEvent.InnerText;
eventName.Text = text;

Comment: This was it. So innerText is what I needed. Thank you Mike!

Value of xml node returning as null