Insert Page Break after n number of rows

Question: I am using html2pdf to export html to pdf in AngularJS the issue I have is that I need to insert a page break after n number of rows.. BDW I am using dir-paginate...
Here is my code:

`

I tried different solutions but nothing works
I have to insert a div with class="html2pdf__page-break and repeat the header for example every 10 rows.
Answer: Simply take the rest of the division and check if it is a multiplier of 10, like so:

You could do it using a function of something like that to keep it cleaner, but the ideia is the same.
Adapt it to your code, or add a codepen/jsfidle so we could help you better.
Happy coding :)
Comment: Yes but the issue is that I am using dir-paginate and not ng-repeat and the other is that I am printing a table and then have to split the table in n rows and repeat the header...
Comment: A simple way (and probably cleaner) why don't you create you custom object with the data that you want? Lets say `$scope.table`, then create a list of header and rows (`$scope.table.headers` and `$scope.table.rows`) and then you simply push 10 items for each row... then you can simply loop trough all rows and inside each row loop trough all 10 items... that way you could just control everything within a script
Comment: I am not clear.. can you show me an example of code.. thank you.
Comment: I just can't help you a lot only with that code... but what I'm trying to explain is that you can create your custom object to use... in my example I just used `ng-repeat`, because it is simple to create a fiddle... You need to create the logic somewhere into your script... [my jsfiddle](http://jsfiddle.net/1z7ohubk/2/)


How to use GLSLshader::operator[]

Question: I've been reading through a book on OpenGL that says you can use the GLSLshader::operator[] with the name of the attribute I want the location for to get that location. However when I use it (example below) the program crashes.
GLuint program_id;
...
glLinkProgram(program_id);
...
...
...
glEnableVertexAttribArray(program_id["position");
glVertexAttribPointer(program_id["position"], ... );

When I debug it returns 105 even though I expect it to return 0. I have specified that the location should be 0 and when I hard code it it works as expected:
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, ... );

This is the line from the vertex shader:
layout(location = 0) in vec3 position;

I'm not sure if I've misunderstood how to use this. Up until now I've always hard coded the attribute locations, but I'd like to be able to do it this way. I know I can also use
glGetAttribLocation(program_id, "position");

and that works (it returns the location I specify) but shader["position"] looks clearer to me and if using the [] operator is one way to do it I'd like to know how to do it rather that just finding a work around to make it work.
So my question is can you use the GLSLshader::operator[] such as shader["position"] to get the location of an attribute? If so can you think of what I might be doing that are making it not work?
Comment: I'm not sure what was unclear about this, it was asked and answered correctly in about 2 minutes. I was unsure about how to use the GLSLshader::operator[] and asked for clarification, and Martijn Courteaux understood the question and answered that GLSLshader would have been a class created by the book I was using and not the OpenGL program object as I originally thought. Anyway I have the answer now so I don't require any more information.
Answer: GLSLshader will be a class that is defined in the book you are reading. There will be an operator[] defined. This GLSLshader class is not default (also because OpenGL is actually a C library where classes do not exist).
FYI: GLuint is just a typedef to a fixed 32 bit unsigned number. (Eg in C++: uint32_t)
Comment: Not necessarily; `GLuint` is ***required*** to be 32-bit. "`unsigned integer`" does not imply anything about size. Where applicable it might be `typedef unsigned int GLuint` but for portability, do not ever assume that.
Comment: Actually `GLuint` is not *just* a typedef to `unsigned int`. The OpenGL specification explicitly states which size a `GLuint` is, in particular a `GLuint` always is 32 bits, even on systems on which a regular `unsigned int` would be just 16 bits, or maybe even 64 bits. `GLuint` is independent of this.
Comment: Oh, thanks guys! I didn't know that `int` was variable in size depending on the platform. Will update the answer! :D

How to use GLSLshader::operator[]


GUI automation with AppleScript - How to click a button in the script

Question: I'm trying to write an AppleScript that will use the Save as Pictures... function of PowerPoint, but I'm wrestling with AppleScript. This is what I have:
set p to "file.pptx"

tell application "Microsoft PowerPoint"
    launch
    open p
    delay 2
    click menu item "Save as Pictures..." of menu bar item "File" of menu bar 1
end tell

and it isn't doing what I want. The specific error I get is:
script error: Expected end of line, etc. but found class name. (-2741)
And I don't know what to do. I've tried all sorts of things but I can't seem to get the right menu item to click. I'm using OSX 10.9 and PowerPoint 2011 (Version 14.3.2)
UPDATE:
This is now the script I have:
set p to "file.pptx"

tell application "Microsoft PowerPoint"
    launch
    open p
end tell

delay 2

tell application "System Events"
    tell process "PowerPoint"
        click menu item "Save as Pictures..." of menu 1 of menu bar item "File" of menu bar 1
    end tell
end tell

And I'm getting an execution error: Microsoft PowerPoint got an error: Parameter error. (-50)
Comment: Good idea but this turned out to be incorrect. Thanks for the help though!
Answer: Gui automation is generally done through the "System Events" app.
Also you need to provide a full path to a file before trying to open it.
This is how you would begin your attack on PowerPoint correctly.
set p to POSIX file "/Users/drew/Desktop/file.pptx"

tell application "Microsoft PowerPoint"
    launch
    open p
end tell

delay 2

tell application "System Events"
    tell process "PowerPoint"
        click menu item "Save as Pictures..." of menu 1 of menu bar item "File" of menu bar 1
    end tell
end tell

Comment: Thanks for the help, but this is giving me a different error: `execution error: Microsoft PowerPoint got an error: Parameter error. (-50)`, I added the whole script I have now to the question. I tried a few variations (process/application, "PowerPoint"/"Microsoft PowerPoint", etc.) but always seem to get the same error. I don't even know which part of the script is wrong.
Comment: Perhaps you need to enable access for assistive devices, looks like it's changed in mavericks. Look at this http://www.tekrevue.com/how-to-enable-access-for-assistive-devices-in-os-x-mavericks/ and add power point.
Comment: @Drew Just noticed you were not using a full path to your pptx file, which is possibly the Parameter error. Have edited my answer to show this as well.
Comment: Turned out you were both right. Thanks for all the help!


Update a tensor using Scatter_Update

Question: I have a weights Tensor of shape (300,), which has binary data, some elements are 1's and others are 0's. I need to convert all the 1's except the first occurrence of 1 to 0's. I would love to know of a simple method to do so in Tensorflow.
But, this is how I'm currently trying to achieve this:
I get all the indices of where the tensor is 1 with this line of code:
indices = tf.squeeze(tf.where(tf.greater(weights, 0)))

Then, I build a tensor that will updated on corresponding indices:
updates = tf.constant(0., shape=indices[1:].eval(session=sess2).shape, dtype=tf.float32)

Then, I use scatter_update to update updates on corresponding indices, but since scatter_update only works on a Variable, I create a variable and assign the updatable tensor to this variable, like so:
 weights_var = tf.Variable(tf.zeros(weights.get_shape()), name="weights_var")
tf.assign(weights_var, weights)

Then, I call tf.scatter_update:
tf.scatter_update(weights_subset, indices[1:], updates).eval(session=sess2)

It's giving me following error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-211-c863dff9ffc7> in <module>()
     51 updates = tf.constant(0., shape=indices[1:].eval(session=sess2).shape, dtype=tf.float32)
     52
---> 53 tf.scatter_update(weights_subset, indices[1:], updates).eval(session=sess2)
     54
     55 # print(final_weights.eval(session=sess2))

~/anaconda2/envs/py36/lib/python3.6/site-packages/tensorflow/python/ops/state_ops.py in scatter_update(ref, indices, updates, use_locking, name)
    290     to use the updated values after the update is done.
    291   """
--> 292   if ref.dtype._is_ref_dtype:
    293     return gen_state_ops.scatter_update(ref, indices, updates,
    294                                         use_locking=use_locking, name=name)

AttributeError: 'numpy.dtype' object has no attribute '_is_ref_dtype'

I'd love to know solution to this and if possible an easier, vectorised one-liner in Tensorflow. Thanks :-)
Answer: If I have understood your problem then this code flow should work according to the first paragraph in your question. Don't know if it can be further shortened.
mask = tf.Variable([0, 1, 1, 0, 1, 1, 1, 1])

indices = tf.squeeze(tf.where(tf.greater(mask, 0)))
sess.run(tf.global_variables_initializer())

valuesofindices = np.delete(indices.eval(session=sess),
                            0)

update = tf.scatter_update(mask,
                           valuesofindices,
                           tf.tile(tf.constant([0],
                                   tf.int32),
                           valuesofindices.shape))

sess.run(tf.global_variables_initializer())
print(update.eval(session=sess))

Output :

[0 1 0 0 0 0 0 0]

Update a tensor using Scatter_Update


Multi Upload Widget

Question: Is there any widget that allows uploading zips or multiple files at once?
One possible module is Plupload integration; however, it seems to be unstable and is under heavy development.
Are there any well known stable multi upload widgets?
Answer: AFAIK, Plupload is your best option at the moment, now and for the future. If you're worried about its stability, you are invited to help with testing and bug fixing.
Answer: Multiupload Filefield Widget
Comment: check new URLs at http://drupal.org/project/1115362 and similar at  http://drupal.org/project/multiupload_imagefield_widget
Answer: If you are uploading images and on Drupal 6 (your post doesn't say) I have hade good results with Image FUpload
Answer: I've been using Plupload on a Drupal 7 site for about a year with no stability issues I can recall.
I chose it after testing most of the other options I could find and it was the most stable and simplest to use. As I say, that was a year ago and a lot may have happened since then, so others may have surpassed it or they may fit your use case better (some others were good, they just didn't meet my needs as well).
The only "issue" I have is that the form when you have 50 images with alt, title, etc in your form and in those cases things really bog down when you edit the page and on slow connections I have had timeouts when I save the page. I'm not really sure how you would get around this though unless the image manage/edit/upload actions were distinct and separate from the page edit/manage/create functions and possibly separate from each other (manage/edit  versus upload). Short of that, you're going to have pretty heavy forms no matter how you do it.

Multi Upload Widget


If any request failed how we can execute last request in jmeter

Question: I have 6 requests in my jmeter script
Request 1
Request 2
Request 3
Request 4
Request 5
Request 6
If request 3 is failed, directly how we can execute request 6
Please post the ans for this.
Answer:
Put your Request 6 under a Test Fragment

Add an If Controller after Request 3 and use the following __jexl3() function as the condition:
<code>${__jexl3(${JMeterThread.last_sample_ok} == false,)}
</code>

Add a Module Controller as a child of the If Controller and point it to the Test Fragment holding the Request 6


How to get fields from the child table in the result set

Question: I have join between two tables. Instruments is the parent table and Statuses are the child table. I am looking only to retrieve those instruments having the inst_status = 'Active' in the child Statuses table.
i = Instrument.joins(:statuses).where("statuses.inst_status='Active'")

The resulted query generated is:
SELECT "instruments".* FROM "instruments" INNER JOIN "statuses" ON "statuses"."instrument_id" = "instruments"."id" WHERE (statuses.inst_status='Active')

Which is OK it is returning only 55 instruments which are Active.
However, how can I get the fields from the Statuses (child) table in the result set along with the fields from the (parent) Instruments table?
Comment: got it2.1.5 :114 > i[0].attributes
 => {"id"=>3052, "inst_status"=>"Active"}
2.1.5 :115 > i[0].id
 => 3052
2.1.5 :116 > i[0].inst_status
 => "Active"
Comment: Is this an eager load question?
Comment: OK , I found some double quotes missing: here is the statement I run: i = Instrument.joins(:statuses).where("statuses.inst_status='Active'").select("instruments.*", "statuses.*")    However now I cannot execute count or first on the result set. Statements like i.count or i.first are failing. Also i[0] does not have the statuses fields in the result set.
Comment: I renounced to get all the fields, I want only the id from the parent table and the inst_status form the child table. Here is the statement: i = Instrument.joins(:statuses).where("statuses.inst_status='Active'").select("instruments.id", "statuses.inst_status")
Comment: Which generates the SQL: SELECT instruments.id, statuses.inst_status FROM "instruments" INNER JOIN "statuses" ON "statuses"."instrument_id" = "instruments"."id" WHERE (statuses.inst_status='Active')
Comment: do `i[0].attributes`, you will see all the columns from both tables..
Comment: But in the result set I am getting only the parent table field, the child table field inst_status is misising:
Comment: 2.1.5 :113 > i[0]
 => #
Comment: @L.D that's wrapped inside. You just do `i[0].attributes`
Comment: OK, i.count does not work anymore with the join. But i[0], i.first works and I can get also the wrapped inside fields. Also i[0].attributes and i[0].attributes works.
Answer: Well, You have to use select method for this :
Instrument.joins(:statuses)
          .where("statuses.inst_status='Active'")
          .select("instruments.*, statuses.*")

Comment: Does not work. The statements work without select. Once select is added no query is generated the prompt is returned like for an incomplete statement.
Comment: @L.D Just delete your _doesn't comment.._ for future readers. :D


What is difference between Minikube and built-in Kubernetes to Colima?

Question: I am exploring running Kubernetes cluster on developer environment (personal Mac M2 laptop). There are several ways to do that with different set of technologies (Minikube, Docker, Colima, Podman, Kind, etc).
For some reason I chose Colima as container runtime for Docker. Official Colima documentation says Colima has built-in Kubernetes, also it says following:

Yes, you can create a Kubernetes cluster with minikube (with Docker driver), Kind or K3d instead of enabling Kubernetes in Colima.
Those are better options if you need multiple clusters, or do not need Docker and Kubernetes to share the same images and runtime.
Colima with Docker runtime is fully compatible with Minikube (with Docker driver), Kind and K3d.

Therefor there are at least two options achieve my goal:

use built-in Kubernetes to Colima via colima start --kubernetes
run Minikube, using Colima under the hood.

I managed to configure and run successfully both ones. I am a bit confused and want to know pros/cons both setups. I noticed only different container set, that's all. Net surfing didn't help a lot.
What is difference between Minikube and built-in Kubernetes to Colima?
Comment: I can tell you more about Minkube. Minikube creates a kubernetes single node cluster for local development process. In windows you can install docker desktop and don't install kubernetes from the settings option given on docker desktop instead you next install Minkube and then you can work on kubernetes on your local pc for learning. In cloud llike azure their is no Minikube (reason already given). Azure has multi node kubernetes cluster. You communicate with the azure aks with azure cli commands.
Answer: In the specific setup you're asking, they've made slightly different decisions around the specific way they choose to bootstrap a Kubernetes cluster.
Poking at this myself, Colima appears to have gone with using K3S as it's means of spinning up a single node cluster and serve the cluster API vs. Minikube's Kubernetes In Docker approach, AKA Kind.
Take the following output from a fresh Minikube install:
NAMESPACE     NAME                               READY   STATUS    RESTARTS       AGE
kube-system   coredns-787d4945fb-mlb7b           0/1     Running   2 (57s ago)    4m32s
kube-system   etcd-minikube                      1/1     Running   0              4m47s
kube-system   kindnet-dhrg4                      1/1     Running   0              4m33s
kube-system   kube-apiserver-minikube            1/1     Running   0              4m48s
kube-system   kube-controller-manager-minikube   1/1     Running   0              4m47s
kube-system   kube-proxy-2btkt                   1/1     Running   0              4m33s
kube-system   kube-scheduler-minikube            1/1     Running   0              4m48s
kube-system   storage-provisioner                1/1     Running   1 (4m2s ago)   4m46s

vs. Colima:
NAMESPACE     NAME                                      READY   STATUS    RESTARTS   AGE
kube-system   coredns-6799fbcd5-s8wl4                   1/1     Running   0          12m
kube-system   local-path-provisioner-84db5d44d9-dlgtb   1/1     Running   0          12m
kube-system   metrics-server-67c658944b-bvpqj           1/1     Running   0          12m

in Minikube and Kind case, we see pods for the Kubernetes API server, scheduler, and controller manager along with ETCD among others whereas with Colima these pods are missing. The reason for this, paraphrasing the K3S docs, is that K3S encapsulates these into a single binary and makes use of a different storage provider than ETCD to serve the cluster API. Container networking is also different as well with Minikube by default using kindnet vs. K3S choice of flannel.
Now, what does that practically mean for you? Short answer, it depends. If you're looking to validate your app manifests are correct, both probably will be fine. Both get you started quickly enough. If you need to install certain things like am Ingress controller or a service mesh product, you may find certain choices from K3S or Kind that make it easier or harder. Only thing really to do is try both and see which gets you to where you want to be faster.


Delete selected checkbox items with select all validation

Question: I've a list of items which are generated as:
<input type="checkbox" name="sacb" onchange="selAll();" title="select all"/>
  <?php
  while($row = mysql_fetch_array($res)){
    echo "
<input type='checkbox' name='cb' value='$row[id]'>$row[item]
";
  }
?>

Script
function selAll(){
  var s = document.form.sacb;
  var t = document.form.cb;
  for(var i=0; i<t.length; i++){
    t[i].checked = s.checked;
  }
}

This is working well to select/deselect all checkboxes.
I want to submit this form where multiple/all selected items are to be deleted. But I'm not getting all selected checkboxes. I've searched and found that I need to replace my PHP code as:
<input type='checkbox' name='cb[]' value='$row[id]'>$row[item]

But as soon as I do this, the script fails to select all checkboxes. How to solve this problem? Any solution?
Answer: You can't use dot notation to access elements with brackets in name so you'll have to retrieve them using the elements collection
function selAll(){
    var s = document.form.sacb;
    var checkboxes = document.form.elements['cb[]'];
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = s.checked;
    }
}

Answer: you can get to update selected check box from below javascript
please add your code to select number of array selected by to get in simple javascript
i this example i have used jquery to just get array of checkbox and checking whether it is selected or not
var field, fields = $('.edit_user_notifi :checkbox'), i = fields.length;
        var notification_status = '';
        while (i--) {
            field = fields[i];
            if(notification_status == '')
            {
                if (field.checked) {
                    notification_status = field.id+'~1';

                } else {
                    notification_status = field.id+'~0';
                }
            }else{

                if (field.checked) {
                    notification_status = notification_status +','+ field.id+'~1';
                }else{
                    notification_status = notification_status +','+ field.id+'~0';
                }

            }
        }

just change little logic to get with simple javascript or if would be good to if you are using jquery.


Finding the area of a triangle, given the distance between center of incircle and circumscribed circle

Question: Consider the following depiction:

$ABC$ is an isosceles triangle ($AB=AC$), where the two angles opposite the equal sides are equal $\beta$ ($\beta>60$), and $AD$ perpendicular to $BC$.
$O$ is the center of the circumscribed circle of $ABC$, and $M$ is the center of the incircle of $ABC$.
I want to express the area of the triangle $BOM$ and the radius of the incircle of $ABC$, in terms of $k$ and $\beta$.
This is what I tried: I denoted the radius of the circumscribed circle as $R$, and the radius of the incircle as $r$.
The area of  $BOM$ can be obtained by: $\frac{k\cdot BD}{2}$, and $BD=\frac{BC}{2}$, I get that the area is actually:  $\frac{k\cdot BC}{4}$.
Now from Law of sines I get $BC=\sin(180-2\beta)\cdot 2 R$.
So this reduces to problem to expressing $R$ (which is $OA$) in terms of $\beta$ and $k$. This is where I'm stuck. I couldn't find a way to do that.
I know that $OA=OB=R$, and that $AOB$ is also isosceles triangle, and I have a feeling it is important, but I can't figure out what am I missing...
Hints and guidelines would be very appreciated.
Comment: hint: $d=\sqrt{R(R-2r)}$
Answer: Hint:-
Let the equal sides be $x$,
Distance of circumcenter from A, OA = circumradius, $R=\dfrac{abc}{4\triangle}$
Distance of incenter from A, MA = $r\csc{\dfrac{A}{2}}$
You will get MA - OA in terms of $x$ and $\beta$, but MA - OA = k
Then you can substitute the value of $x$ in terms of $k$ and $\beta$ in the formula for the area, i.e.
$\dfrac{1}{2}\cdot2x\cos\beta\cdot x\sin\beta$
Answer: Assuming $BD=1$, we have $AB=AC=\frac{1}{\cos\beta}$, $[ABC]=\tan\beta$,
$$ R = \frac{AB}{2\sin\beta} = \frac{1}{\sin(2\beta)}$$
and:
$$ r = \frac{2[ABC]}{AB+AC+BC} = \frac{\tan\beta}{1+\frac{1}{\cos\beta}}=\frac{\sin\beta}{1+\cos\beta}=\tan\frac{\beta}{2}. $$
Moreover, by Euler's theorem we have:
$$ k^2 = OM^2 = R^2-2Rr = \frac{1}{4\sin^2\beta\cos^2\beta}-\frac{1}{\cos\beta(1+\cos\beta)} $$
so:
$$ k^2 = \frac{(1-2\cos\beta)^2}{4\cos^2\beta(1-\cos^2\beta)} $$
and:
$$ k = \frac{1-2\cos\beta}{\sin(2\beta)}. $$
This gives, in general,
$$ BD = \frac{\sin(2\beta)}{1-2\cos\beta} k, $$
so:
$$ [BOM]=\frac{k}{2}BD = \frac{\sin\beta\cos\beta}{1-2\cos\beta} k^2,\tag{1} $$
and:
$$ r = \frac{\sin\beta}{1+\cos\beta} BD = \frac{2(1-\cos\beta)\cos\beta}{1-2\cos\beta} k.\tag{2}$$


What happens when switched from more aggregated to less aggregated unit in ecological regression

Question: Sample state data
State     Percent_ethnicity=1   Percent_voting=1
A         20%                   60%
B         56%                   65%

Sample city data
city   State     Percent_ethnicity=1   Percent_voting=1
1      A         77%                   70%
2      A         46%                   25%
1      B         56%                   67%

I have aggregated race and voting choice data at the state and city levels. Say, the ecological regression model looks like this at the state level (where j is states, Y is percent voting for 1 (only 2 options: 0, 1), X is the percent of race being 1 (only 2 options: 0, 1), E is the error term):
Yj = a + b*Xj + Ej

I would like to model a and b via a linear regression model.
After that say, I am switching to analyzing the ecological regression at city level (where p is cities, Y is percent voting for 1 (only 2 options: 0, 1), X is the percent of race being 1 (only 2 options: 0, 1), N is the error term):
Yp = a + b*Xp + Np

Would I be able to infer anything without seeing the results how the a, b, and E/N estimates compared/changed between the two ecological models?
Comment: You do not really want to model a binary outcome using linear regression.
Comment: Individual data is binary, but they are aggregated at the state and city levels as percentages
Comment: @Björn has a good point. If you know the numbers who voted (not just the percentages) then a [logistic model](http://stats.stackexchange.com/a/88052/28500) would be appropriate. Otherwise, you could consider [beta regression](http://stats.stackexchange.com/a/29042/28500). Note that your confidence in a percentage value will be higher in cases where more votes were cast. Standard linear regression is risky here. Also, do you have data on all cities (and towns and unincorporated areas etc) within each State so that a nested analysis (city within State) is possible?
Comment: I am not sure what it means by doing logistic regression, I have different data sets providing each of the data and only linkable through the area variables. I think I can only do logistic regression if I know both the voting decision and ethnicity of the same individual but I don't from the existing data.
Comment: You do know that a percentage cannot be >100% or <0%, so linear regression (that has no mechanism of avoiding such predictions) seems like it might well not be the right thing to do. If you always have 1000s of voters and the percentages you are interested are always around 50%, then of course a linear model might be an okay approximation. A vanilla flavor standard logistic regression for individual voter data will indeed not be possible, but that is not necessarily a reason to not consider the underlying distribution (and to e.g. model logit(p) accounting for the distribution of covariates).
Comment: OK, I see what you mean now, you want to use logistic regression as probabilistic output from 0 to 1 as continuous, not discrete binary classes. Let's say I do use logistic regression, I am interested in how the parameters and errors might change. Will the N > E because we have more cities and less n in each city?
Comment: And can we infer any things expected to change in terms of a and b? Or is it impossible to know?
Comment: I am also unable to find any papers or reference I could read up to learn about this specific topic.
Comment: Is there any information in your State data that is from sources other than your city data? Specifically, do your State data include results from towns or unincorporated localities that are not included in the city results? Without knowing that it's hard to provide an answer. Also, could you be a bit more specific about the hypothesis that you are trying to test here? Why do you expect that values of `a` and `b` would differ in the two types of models?
Comment: No the lowest level of data is at the city level, but each city has a corresponding state. I would like to run one regression analysis at the city level, and another another at the aggregated state level. I suspect they change because of the possible correlation within-cluster (aka cities are more alike within the same state than cities from other state due to geographic proximity). But I would like to know how to prove it mathematically.
Answer: The coefficients and error terms would almost certainly differ between the state and city level, but for reasons that you probably did not intend.
Coefficients. The way you have posed the problem, you would be taking averages of percentage voting 1 by city without taking population into account. An extreme example shows the danger. Say that there is no racial/ethnic* difference in voting, and that a State has 1000 cities. In the single large city, all 1,000,000 people vote for 1; all 1000 voters in each of the 999 other cities vote for 0. Averaged over people in the State, 1 wins with a bit over 50% of the vote, but 0 gets 99.9% averaged over the cities (without taking population into account).
Error terms. In a linear regression, error terms include everything that the linear model missed: non-linear effects, interactions, important variables missing from the model. So say that the influence of race/ethnicity on voting is different in a rural southern state than a northern urban state. If the model ignores that possibility, then you would expect different errors for within-state versus among-state comparisons. Much of statistics is trying to figure out what lurks within those error terms and to take them into account.
Two messages here. First, although I expect that you intended to take population size into account, the way you posed the model in your question did not. Whether you model your outcome variable as a percentage or as a number of votes, your analysis must include population size. A generalized linear model rather than a standard linear regression is called for.
Second, you need to be a good deal more specific in formulating your model. There are ways to take additional variables, interactions, the fact that each city has its own associated state, and so forth, into account. Even if you choose to develop a simpler model, forcing yourself to consider these additional possibilities will mean that you are at least doing so with your eyes open to them. A solid understanding of different statistical designs, as you might get from an advanced statistics course, would help. See this page as an example of what can be included in a voting/demographic model.

*In US bureaucratic terms, race and ethnicity are distinct concepts. If you conflate them as you do in this question, others reviewing your work will take you much less seriously.
Comment: Thanks, I have also come up with "proof"/rationale that they are likely change, but thanks very much for giving your reasoning so I can view it in a different angle. I also agree your point about the generalized than standard linear model in order to capture the within-cluster correlations.


EventGrid Webhook Scenario

Question: Team -
From the documentation provided it is clear that if you are using a webhook handler, in success scenarios you need to return 200 OK. But if I am not wrong the collection of events is posted to the webhook and not a single event - so are we saying 200 OK is to be returned inside for loop instead of outside? I mean what happens if out of 3 events received 1 fails and 2 passes?
Answer: Currently (api-version=2018-05-01-preview) subscribers received only a single event in the array (JArray) for DeliverySchema such as the EventGridSchema and InputEventSchema. Note, that the array is used for possible option in the future for delivering a batch of the events to the subscriber.
On the other side, the new delivery schema such as a CloudEventV01Schema allows to post only a single event to the subscriber (JObject).

EventGrid Webhook Scenario


Redhat 5 with Samba 3.6 leads System error 58 on Windows 7

Question: I'm currently trying to make an old Standalone Samba Share server running on Redhat 5 back to life! It was previously running version 3.0, due to a lot of issue I decided to upgrade to version 3.6 with the official package. Now, I'm correctly running samba 3.6 on Radhat 5
Red Hat Enterprise Linux Server release 5.11 (Tikanga)

Samba version 3.6.23-12.el5_11

Here is my testparm output:
Load smb config files from /etc/samba/smb.conf
rlimit_max: increasing rlimit_max (1024) to minimum Windows limit (16384)
Processing section "[diro]"
Processing section "[dirt]"
Processing section "[dire]"
Loaded services file OK.
Server role: ROLE_STANDALONE
Press enter to see a dump of your service definitions

[global]
        workgroup = DUMMY
        server string = Samba %v
        interfaces = 127.0.0.1, eth0
        bind interfaces only = Yes
        client ipc signing = auto
        printcap name = cups
        idmap config * : backend = tdb
        cups options = raw

[diro]
        path = /home/diro
        valid users = usero
        read only = No
        create mask = 0664
        directory mask = 0775

[dirt]
        path = /home/diro/t
        valid users = usero
        read only = No
        create mask = 0777
        directory mask = 0777

[dire]
        path = /home/diro/e
        valid users = usert
        read only = No
        create mask = 0777
        directory mask = 0777

the complete smb.conf:
[global]
        workgroup = DUMMY
        server string = Samba %v
        interfaces = 127.0.0.1 eth0
        bind interfaces only = true
        printing = cups
        printcap name = cups
        load printers = yes
        client ipc signing = auto
        client signing = auto
        log level = 3
        min protocol = core
        map to guest = Bad User
        security = user
        passdb backend = tdbsam
        load printers = yes
        cups options = raw
[diro]
        path = /home/diro
        valid users = usero
        read only = No
        create mask = 0664
        directory mask = 0775

[dirt]
        path = /home/diro/t
        valid users = usero
        read only = No
        create mask = 0777
        directory mask = 0777

[dire]
        path = /home/diro/e
        valid users = usert
        read only = No
        create mask = 0777
        directory mask = 0777

I'm able to connect to one of the shares from localhost:
>$ smbclient //DUMMYMO/diro -U usero usero
Domain=[DUMMY] OS=[Unix] Server=[Samba 3.6.23-12.el5_11]
smb: \>

Which is good, but I'm still wondering why it doesn't work on a Windows 7 machine:
>$ net use x: \\DUMMYMO\diro /user:usero usero
System error 58 has occurred.

The specified server cannot perform the requested operation.

By putting the log level to 3, I'm able to see these log lines during Windows connection attempt:
[2017/11/06 15:12:46.107877,  3] lib/access.c:338(allow_access)
  Allowed connection from XXX.XXX.XXX.XXX (XXX.XXX.XXX.XXX)
[2017/11/06 15:12:46.108026,  3] smbd/oplock.c:922(init_oplocks)
  init_oplocks: initializing messages.
[2017/11/06 15:12:46.108087,  3] smbd/oplock_linux.c:246(linux_init_kernel_oplocks)
  Linux kernel oplocks enabled
[2017/11/06 15:12:46.108167,  3] smbd/process.c:1609(process_smb)
  Transaction 0 of length 109 (0 toread)
[2017/11/06 15:12:46.108198,  3] smbd/process.c:1414(switch_message)
  switch message SMBnegprot (pid 13707) conn 0x0
[2017/11/06 15:12:46.108463,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [NotSmb]
[2017/11/06 15:12:46.108496,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [NotSmb]
[2017/11/06 15:12:46.108517,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [NotSmb]
[2017/11/06 15:12:46.108537,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [NotSmb]
[2017/11/06 15:12:46.108556,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [NotSmb]
[2017/11/06 15:12:46.108576,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [NotSmb]
[2017/11/06 15:12:46.108595,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [SMB 2.002]
[2017/11/06 15:12:46.108615,  3] smbd/negprot.c:598(reply_negprot)
  Requested protocol [SMB 2.???]
[2017/11/06 15:12:46.108669,  0] smbd/negprot.c:706(reply_negprot)
  No protocol supported !
[2017/11/06 15:12:46.110716,  1] smbd/process.c:457(receive_smb_talloc)
  receive_smb_raw_talloc failed for client XXX.XXX.XXX.XXX read error = NT_STATUS_CONNECTION_RESET.
[2017/11/06 15:12:46.110790,  3] smbd/server_exit.c:181(exit_server_common)
  Server exit (failed to receive smb request)

This is the network trace:
>$ sudo tcpdump -i eth0 -nn "tcp port 445"
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on eth0, link-type EN10MB (Ethernet), capture size 96 bytes
15:21:05.292627 IP XXX.XXX.XXX.XXX.54997 > YYY.YYY.YYY.YYY.445: S 946161236:946161236(0) win 8192 <mss 1380,nop,wscale 8,nop,nop,sackOK>
15:21:05.292732 IP YYY.YYY.YYY.YYY.445 > XXX.XXX.XXX.XXX.54997: S 2489729164:2489729164(0) ack 946161237 win 5840 <mss 1460,nop,nop,sackOK,nop,wscale 7>
15:21:05.294416 IP XXX.XXX.XXX.XXX.54997 > YYY.YYY.YYY.YYY.445: . ack 1 win 258
15:21:05.294748 IP XXX.XXX.XXX.XXX.54997 > YYY.YYY.YYY.YYY.445: P 1:110(109) ack 1 win 258
15:21:05.294772 IP YYY.YYY.YYY.YYY.445 > XXX.XXX.XXX.XXX.54997: . ack 110 win 46
15:21:05.298603 IP YYY.YYY.YYY.YYY.445 > XXX.XXX.XXX.XXX.54997: P 1:42(41) ack 110 win 46
15:21:05.300286 IP XXX.XXX.XXX.XXX.54997 > YYY.YYY.YYY.YYY.445: R 110:110(0) ack 42 win 0

As the log mentioned, the client send a RST flag directly after server's answer and I don't know why. I already have tried many solutions like min protocol, server signing without success.
I ran out of solutions.. Do you have any suggestions?
Note that I don't have admin access on my desktop and I guess many parameters are imposed by the domain.
Comment: Could you post the content of your smb.conf? might help to locate source of your issue
Comment: Has the Win7 client received the relevant registry changes to enable it to work with SaMBa 3?
Answer: Thanks to the hint of MadHatter, I was able to resolve the issue:
The client just requires SMB2 instead of SMB3. This trick can easily be applied in the configuration under the Global section:

max protocol = SMB2


Non-harmonic-like series that diverges even though $a_\infty=0$

Question: The only series that I can think of is the harmonic series or the harmonic series with primes, which are well known. Are there any other series of this type?
Comment: $a_n=\frac{3n+1}{n^2 +2}$ should satisfy your requirement.
Comment: As $n\to \infty$, $a_n =\frac{3n}{n^2}=\frac{3}{n}$
Comment: In general, series that diverge with a limit that go to 0 either go 0 slower than 1/n,  or to 0 "very slightly" faster than 1/n.   (That's a very loose term).   So you'll generally see things like 1/(something smaller than n)
Answer: $\sum_{n=2}^{\infty} \frac1{\ln n}$
Comment: Or, perhaps more surprisingly, $\sum_{n=2}^\infty \frac{1}{n\ln n}$, which has terms which go to zero more quickly than those of the harmonic series.
Answer: Let $y_j$ be any sequence of real numbers that does not have a finite limit as $j \to \infty$.  Let $x_j$ be an increasing sequence of positive integers that grows so rapidly that $x_{j+1} - x_{j} > j |y_{j+1} - y_{j}|$.  For $x_j \le n < x_{j+1}$ take
$a_n = (y_{j+1} - y_j)/(x_{j+1} - x_j)$.  Then $|a_n| < 1/j \to 0$ as $n \to \infty$, and $\sum_{x_1}^{x_M} a_n = y_M - y_1$ has no limit as $M \to \infty$.


Why is my web scraping returning nothing?

Question: I'm new to web scraping on python. I have problem when I run my code the return is just white blank but its not error. I just do the same code from my course but its not work for me
import urllib.request
from bs4 import BeautifulSoup

class Scraper:
    def __init__(self, site):
        self.site = site

    def scrape(self):
        r = urllib.request.urlopen(self.site)
        html = r.read()
        parser = 'html.parser'
        sp = BeautifulSoup(html, parser)
        for tag in sp.find_all('a'):
            url = tag.get('href')
            if url is None:
                continue
            if 'html' in url:
                print('\n' + url)

news = "https://news.google.com/"
Scraper(news).scrape()

I'm running on IDLE and pycharm and result its nothing. I have been added all modules, I don't know where the problem is. Maybe from my url to print all and make it a lot of line so can't return it or from my code or maybe from my desktop.
Can anyone help me?
Comment: some websites defend themselves from web scraping and return fake data or restrict, google already restricted it from web scraping so find sites that allow that
Comment: thanks for your suggest and I just did what you suggested but the result is the same
Comment: check web site that you scraping by turning off javascript in the browser if there any info displayed, you should be able to get something assuming that your code works correctly, if not first test it locally than try on websites
Answer: Most likely that the website you are trying to scrape is a dynamic website, meaning that  it is Javascript generated code and can't be scraped with only requests and beautifulsoup. You can learn more here. I recommend trying out selenium, which controls a browser so that you can retrieve the code directly from what is loaded in the browser.
Edit: as Arman mentioned, Google could also possibly be blocking possible web scraping activities. Selenium also possibly works with those. It's basically "emulating" a browser, as if you were actually using it but you're actually automating it with your python code.
Answer: Anyone still having this problem, I think there is a bug in the code. It's not printing anything because none of the urls have html in them
The example should be looking for http and not html
    def scrape(self):
        r = urllib.request.urlopen(self.site)
        html = r.read()
        parser = 'html.parser'
        sp = BeautifulSoup(html, parser)
        for tag in sp.find_all('a'):
            url = tag.get('href')
            if url is None:
                continue
            if 'http' in url:
                print('\n' + url)


asp.net - Use ascx as a layout template

Question: This is my layout template (ascx without code behind)
<%@ Control Language="C#" AutoEventWireup="true" Inherits="ws.helpers.LayoutUC" %>

blah blah blah

<ws:Panel runat="server" ID="left"></ws:Panel>
<ws:Panel runat="server" ID="main"></ws:Panel>
<ws:Panel runat="server" ID="right"></ws:Panel>

Modules will be added into ws:Panel later.
I also allow my user create their own ascx file to custom their page layout. And because of this i do a string replace all dangerous part like script tag (runat="server"), all asp.net html tag, <%, <%@, <#.... from their custom.
Im not worry about XSS, so dont comment on it, and ask why?
I want know your thinking about this. Is is safe? Is it scalable? Is it standard or a bad way?
Answer: Have a look at the INaminingContainer Interface http://msdn.microsoft.com/en-us/library/system.web.ui.inamingcontainer.aspx.
<asp:YourControl>
  <LeftColumn>
    <asp:Literal ID="literal1" runat="server" Text="User created literal" />
  </LeftColumn>
</asp:YourControl>

In the .ascx from the users, they register your control and insert asp.net code into properties. In the 'YourControl' class you create placeholders and insert the markup set to a specific property into these placeholders. (e.g. everything between <LeftColumn> and </LeftColumn> will the inserted into
<asp:Placeholder ID="PlaceholderLeftColumn" runat="server"/>

Edit: I summed some of the TemplateContainer issue up and posted it here: http://www.tomot.de/en-us/article/2/asp.net/how-to-create-an-asp.net-control-that-behaves-as-a-template-container-to-nest-content-via-markup
Comment: That link is dead.
Answer: You are allowing user-uploaded content; this is inherently unsafe and there are whole books dedicated to best practices.  Given that you are doing it anyway, as long as you make sure you scrub the input, is it scalable?  You are allowing creation of user-uploaded files on your site.  How many will there be?  How many users? What about load-balancing?  This solution will not scale for many users, files, or servers.
It sounds like you are trying to create a simple CMS.  Why not use one that exists currently, or adopt parts of an open source solution?
Comment: No they not upload any file, they just using my tool on website and create their own template and save it to their private folder on server. Of course i will limited number of templates.
Comment: I meant user created files.  They are creating files from your tool to save in a folder on your server, right?  So, is it safe? No, but you have the same problem as any user-generated content site, including this one.  Is it scalable?  Not simply, if you add more servers, but there are ways around that, too; cf. NoSQL movement.

Standard practice would be to store the input in a database, and reference it in your ascx file.

asp.net - Use ascx as a layout template


HAproxy mysql failover

Question: I try to set up a HA cluster with Percona xtraDB Cluster for MySQL replication and HAproxy for load balancing.
HAproxy works really good with apache, when apache crash or if it's not responding, HAproxy switch on another node.
My problem start with MySQL, I set up also MySQL in the same HAproxy but when when MySQL is not responding, HAproxy don't switch on another node. However HAproxy sees that MySQL does not respond cause when I check in HAproxy stats MySQL server is down.
My question is, is it possible to set up two resources in HAproxy ? Can he check if apache is up and switch on another node if not AND check if MySQL is up and switch on another node if not ?
HAproxy.conf:
[...]
frontend redmine
    bind 192.168.7.149:80
    reqadd X-Forwarded-Proto:\ http
    default_backend redmine

frontend redmineS
    bind 192.168.7.149:443 ssl crt /etc/ssl/private/quipment.fr.pem
    reqadd X-Forwarded-Proto:\ https
    default_backend redmine

backend redmine 192.168.7.149:80
    redirect scheme https if !{ ssl_fc }
    mode http
    balance roundrobin
    option http-server-close
    timeout http-keep-alive 3000
    option forwardfor
    cookie PHPSESSID prefix
    cookie SRVNAME insert
    server xtra1 192.168.7.151:80 cookie x1 check
    server xtra2 192.168.7.147:80 cookie x2 check
    server xtra3 192.168.7.152:80 cookie x3 check

listen mysql-cluster 192.168.7.149:3306
    mode tcp
    balance roundrobin
    option  httpchk
    server xtra1 192.168.7.151:3306 check port 9200 inter 1000 rise 3 fall 1
    server xtra2 192.168.7.147:3306 check port 9200 inter 1000 rise 3 fall 1
    server xtra3 192.168.7.152:3306 check port 9200 inter 1000 rise 3 fall 1
[...]

Comment: Can you also include your `haproxy stats` output (or `hatop` output if you prefer that) so we can see what haproxy thinks is going on?  Also there's at least one apparent error in your configuration (you're using `option httpchk` to check the admin page for your MySQL server - you probably want to use [`option mysqlchk`](https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#4-option%20mysql-check) on the MySQL port to check the *actual MySQL server*)
Comment: Is that your complete `HAproxy.conf`? You seem to be missing a `bind` statment in the `listen` section for MySQL
Comment: No, I did not put the section and global, defaults and stats. I try to add bind in Listen section but but it still does not work
Comment: Can you possible post your HAProxy config?
Answer: Your HAProxy is not testing for MySQL health as on your MySQL section you are telling to do tests for http (with the line option  httpchk), you should use option mysql-check so it should read as
listen mysql-cluster 192.168.7.149:3306
    mode tcp
    balance roundrobin
    option  mysql-check user a_test_user
    server xtra1 192.168.7.151:3306 check inter 1000 rise 3 fall 1
    server xtra2 192.168.7.147:3306 check inter 1000 rise 3 fall 1
    server xtra3 192.168.7.152:3306 check inter 1000 rise 3 fall 1

And you should have in your MySQL database the user a_test_user allowing connections from HAProxy.
Comment: Ok so i create 'mysqlcheck' user with all privileges in my database. I can connect to my database with this user from HAproxy server. I changed my HAproxy.conf accordingly but it still does not work :(
Comment: if the user is 'mysqlcheck' does your line read as 'option  mysql-check user mysqlcheck'?

Also I missed the port part when copying and pasting: please remove the port 9200 from the server, otherwise the check is done against port 9200 instead of 3306. I've edited my answer to remove that port paramenter.
Comment: Yes I had already deleted the port 9200. Yes mysql-check option looks like:  'option mysql-check user mysqlcheck'
Comment: it appear in HAproxy log : "Access denied for user 'mysqlcheck'@'haproxy.local'     Why mysqlcheck'@'haproxy.local ?
Comment: Probably haproxy.local is an entry in the /etc/hosts. Remember that in MySQL you have to specify the hostname when creating the user. so in your case probably the best option is "CREATE USER 'mysqlcheck'@'%';" . If that does not work you can check which user is trying to log in MySQL (e.g as described in https://www.percona.com/blog/2012/12/28/auditing-login-attempts-in-mysql/ )
Comment: Ok it works ! Thank you very much for your help! Really. Have a nice day / evening :)
Comment: Happy it works! Could you mark the answer as valid so people could find it in the future?

HAproxy mysql failover


Recursively sort levels within a multidimensional array of unknown depth by a column while preserving keys

Question: To sort an existing multidimensional array I tried to use usort, but it wont bring me any result. As I can not use nested sets or something like this because of the given structure, I have to sort it:
My array:
[
    2 => [
        'position' => 0,
        'children' => [
            3 => ['position' => "375"],
            5 => ['position' => "44"],
            6 => ['position' => "567"],
            9 => [
                'position' =>  "12",
                'children' => [
                    74 => ['position' => "2"],
                    76 => ['position' => "3"],
                    77 => ['position' => "1"],
                ]
            ],
            62 => ['position' => "34"],
            63 => ['position' => "11"],
            66 => ['position' => "114"],
            74 => ['position' => "912"],
            76 => ['position' => "4564"],
        ]
    ]
]

I would like to sort every level by its node named "children". Recursion should be no problem. It can be a variable structure where the node "children" can exist ... or not :)
Desired result after sorting by position column values:
[
    2 => [
        'position' => 0,
        'children' => [
            63 => ['position' => "11"],
            9 => [
                'position' =>  "12",
                'children' => [
                    77 => ['position' => "1"],
                    74 => ['position' => "2"],
                    76 => ['position' => "3"],
                ]
            ],
            62 => ['position' => "34"],
            5 => ['position' => "44"],
            66 => ['position' => "114"],
            3 => ['position' => "375"],
            6 => ['position' => "567"],
            74 => ['position' => "912"],
            76 => ['position' => "4564"],
        ]
    ]
]

I tried the following code unsuccessfully:
public function recur($data){
        // ...
        foreach($data as $key=>$value){
            if (array_key_exists('children', $value)) {
            usort($value, function ($a, $b): int {
                if ($a['position'] === $b['position']) {
                // ....
                }
                return $a['position'] <=> $b['position'];
            });
        }
    }
}

Answer: Your code does not return any data, so we must assume that your intention is to modify by reference.  To implement modification by reference in your recursive method, use the & symbol in the method's argument signature and the $value variable of the foreach().
The key-preserving sort on the position column data needs to be done outside of the loop to access the data properly.
After sorting the current row, you can recursively iterate any subset that contains children data.
Code: (Demo)
function recur(&$data): void
{
    uasort($data, fn($a, $b) => $a['position'] <=> $b['position']);
    foreach($data as &$value){
        if (isset($value['children'])) {
            recur($value['children']);
        }
    }
}
recur($array);
var_export($array);

Comment: First, of all, thank you for the time and work you invested to answer my question!
I accept your solution as brilliant and simple at once. Thank you.

It don't work < php 7.4 but for the reason of DDEV this is not a real prob. thanks for this solution
Comment: [this works](https://3v4l.org/1jW4N) all the way down to PHP7.0 which was when the spaceship operator was born.


contiguously space on hard disk - NTFS

Question: My question is about file allocation methods on NTFS Fs.
I have two main questions -

When i create a file on NTFS, is it stored contiguously on the physical hard disk?
if not - is there a way to create a file such that when i write to it  the data is stored contiguously (on the hard disk) in it? Something like extents in database.
if such a file exists - is there any way to read data from it (using C read system call) in
bunch/block. what is the maximum bunch size I can use.

I am trying to make a simple file based DB for small applications and would like to make my db in the file. for performance  reason i need to keep my data in contiguous order on the disk and read it in bunches. (I plan to mmap this file in my application).
Comment: Generally, if you specify the file size in one call the file system will allocate it quite well because it knows the final size. You don't need 0% fragmentation for excellent performance.
Answer: According to this superuser answer, you can call SetEndOfFile to provide the system with a file size hint, which will allow NTFS to allocate contiguous storage for the entire file.
Comment: Doing that *may* allow NTFS to attempt to allocate contiguous storage for the entire file. It should be obvious that such an attempt may fail for any number of reasons.
Comment: @NikBougalis "will *allow*" - because it will convey the necessary information to do so. No guarantee was expressed or implied.
Comment: I guess; I just see the "will allow" is introducing some ambiguity.
Answer: Another important point for multi-tasking or multi-user operating systems is that even if a file is stored contiguously, the drive might be called upon by another task to read or write in the middle of your file access. This will cause the drive to seek somewhere else entirely. On a busy system, this could be happening constantly.
The operating system drivers can use algorithms such as scatter-gather or an elevator algorithm that attempts to schedule reads or writes to or from the various tasks' buffers in the order the data appear on the disk, so the head can sweep sequentially from inner to outer tracks -- or vice-versa, picking up or dropping off data along the way.
Elevator algorithms are so named because real elevators have to choose the most efficient loading and unloading pattern based on requests from passengers on the various floors. They cannot afford to waste time and energy going up and down inefficiently. Disk drive head positioning is not much different.
Answer: OK, so let's answer point by point...
Question 1: When i create a file on NTFS, is it stored contiguously on the physical hard disk?
The question makes no sense. When you create a file, NTFS will allocate the space in the MFT for the metadata it needs to track things. Small files may actually fit inside the MFT record for the file - such resident files are, by definition, contiguous. If a file won't fit inside the MFT, then blocks of space are allocated as necessary and they may or may not be contiguous. Generally speaking, it doesn't know how big your file will be, or how much space to preallocate for it - so NTFS will just allocate space as necessary, although you can give it a hint by calling the SetEndOfFile function. But that provides only a hint and no guarantee that the file data will be stored in a contiguous area of the disk. In fact, it should be trivial to convince yourself that even if the filesystem performs real-time defragmentation, it can never *guarantee that the free space will be available as a single, contiguous block of disk addresses.

Question 2: if not - is there a way to create a file such that when i write to it the data is stored contiguously (on the hard disk) in it? Something like extents in database.
Why do you think this is an important concern? You generally shouldn't care how the filesystem stores your data; you should only care about the fact that it does store the data. You may think that accessing a file that's not stored continuously would be slower, but that may not, necessarily, be the case; advanced caching algorithms and prefetching by the O/S will often eliminate any slowdown completely. If your concern is performance, then do you have actual hard data that shows that fragmentation by the filesystem is an issue? If so, the correct approach is to either use a different filesystem or no filesystem at all.

Question 3: if such a file exists - is there any way to read data from it (using C read system call) in bunch/block. what is the maximum bunch size I can use.
The C system calls (like fread) don't know about NTFS, fragmentation, "bunches" and blocks. All they know is how to read the requested number of bytes from the specified file handle and put the data into a buffer that you supply. You can specify any size that you want, really, although the C library will call O/S and filesystem specific APIs to read data in multiples of the block size, which is implementation defined.
Comment: Re #2: Storing the file in a contiguous region *is* a valid concern, especially when implementing low-level systems, such as databases or storage for virtual machines. Modern filesystems support [extents](http://en.wikipedia.org/wiki/Extent_(file_systems)) for exactly this purpose.
Comment: True - there are some legitimate use cases for contiguous storage, but a general purpose filesystem (like NTFS) on a general purpose computer cannot guarantee you will ever get a contiguous storage block of the requested size for reasons that should be obvious.
Comment: And additionally, the performance benefits of contiguous files are, very often, exaggerated, especially when you consider the much improved filesystems we have available, the very good to excellent O/S read-ahead and caching facilities, plentiful RAM, fast disks with large caches, cheap SSDs and solutions like [Dataplex](http://www.nvelo.com/). Generally speaking, if contiguous allocation of data on a storage device is a serious concern (and you can *prove* it is with benchmark data) the solution will almost always be to bypass the filesystem entirely and work with raw block devices.
Comment: Thanks Nik for the explanation
Comment: @NikBougalis- Thanks for the explanation - It clarifies many things. But i just had one doubt about your statement - "The C system calls (like fread or underlying read) don't know about NTFS,". I dont understand this - surely fread must have some information about NTFS file alocation - other wise how will it increment the file position after reading some bytes (assuming the allocation is not always sequential on hard disk)? maybe I am wrong?
Comment: No. `fread` knows nothing about NTFS - all it knows is how to read `n` bytes from file `f` into a buffer at `p`. It ends up calling some other API (e.g. on Windows it might be `ReadFile`) that the operating system provides. You may want to think about why it would be bad for the C standard library to have to know about filesystems. Hint: what if I want to use `fread` on another O/S that doesn't use NTFS? Or what if Microsoft updates NTFS from version x to version y? What happens to programs compiled with the old `fread` then?
Answer:
It might be. But you cannot guarantee it is stored contiguously on the physical hard disk.
You can, with the low-level raw access to the harddisk. For some big database system, they do not use ANY file system, but directly write/read the harddisk. And the data formation in the harddisk is defined by the database system.
No mattter how the file is stored physically, you could read it in block in C. I do not think there is a "maximum bunch size". But there do exist a "good bunch size", as the (block size of file system) * N.

It is said the file system reiserfs is good for storing tons of small files. But I never tested it.
Comment: ReiserFS only exists on Linux, and is not considered good for any purpose.

contiguously space on hard disk - NTFS


Prove that this sequence is convergent by using the limit definition

Question: Suppose I have the following sequence:
$ a_n = \frac{2n -\sqrt (n^2+1)}{ n+cos(n)}$
The definition says that for each $\epsilon > 0 $ there exists a positive integer $n_0 $ such that for all n > $n_0 : |a_n - L | < \epsilon$
Before starting to prove this I try to find a value for $ n_0 $ in function of $ \epsilon $.
We can write that:
$ a_n = \frac{2n - \sqrt (n^2+1)}{ n+cos(n)} \leq \frac{2n}{ n+cos(n)} $
But then I am stuck with the $ cos(n) $ in the denominator.
My idea was to use the fact that the cosine is always between -1 and 1.
Thus, $ cos(n) \leq 1 $ and $ a_n = \frac{2n - \sqrt (n^2+1)}{ n+cos(n)} \leq \frac{2n}{ n+cos(n)} \leq \frac{2n}{ n+1} \leq \frac{2n}{ n} \leq 2 $
But then again I am stuck because this doesn't help me to find an $ n_0 $ in function of $ \epsilon $
EDIT:
@TheSilverDoe reminded me that I forgot the '-L' part in the definition.
I have to calculate the limit first:
Write:
$ \frac{2n - \sqrt (n^2+1)}{ n +1} \leq \frac{2n - \sqrt (n^2)}{ n+1} \leq \frac{2n - \sqrt (n^2+1)}{ n+cos(n)} \leq\frac{2n - \sqrt (n^2)}{ n-1} \leq\frac{2n - \sqrt (n^2+1)}{ n-1} $
or
$ \frac{n}{ n+1} \leq \frac{2n - \sqrt (n^2+1)}{ n+cos(n)}  \leq\frac{n}{ n-1} $
From that we can easily see that the limit is equal to 1.
Back to my original question we have:
$ a_n - L = \frac{2n - \sqrt (n^2+1)}{ n+cos(n)} - 1 \leq \frac{2n}{ n+cos(n)} - 1 \leq \frac{2n}{ n+1} - 1 \leq \frac{2n}{ n} - 1 \leq 2 - 1 = 1$
This brings me back to the same question I had originally
Comment: If you want to prove the convergence using the definition of the limit, you have to know what is the limit...
Comment: Right, I forgot the - L part. So I guess that would be the first step? Finding the limit?
Comment: Yes, you have to "guess" what the limit is. And then, prove that for this value of $L$, the definition of convergence is satisfied. (Actually in that case, it is quite weird because you can find the limit directly, and skip the use of the definition of the limit.)
Comment: Is the limit here equal to 2?
Comment: No. Roughly speaking, $\sqrt{n^2+1}$ is almost $\sqrt{n^2}=n$, so the numerator is almost $n$. And the denominator is also almost $n$ since the $\cos$ is bounded whereas the $n$ becomes very large. So the limit will be $n/n = 1$. If you know asymptotic expansions, you can solve this limit very quickly, just formalizing what I just said.
Comment: I don't know about asymptotic expansions but I solved the limit ( see my EDIT ) with the squeeze theorem
Comment: You've got the following chain the other way round, $$\frac{n}{ n-1} \leq \frac{2n - \sqrt (n^2+1)}{ n+cos(n)}  \leq\frac{n}{ n+1}$$ since $$\frac{n}{n-1} \ge \frac{n}{n+1}$$ because bigger denominator implies smaller fraction. The line before should thus change as $$n-1 \le n+\cos(n) \le n+1 \implies \dfrac1{n+1} \le \dfrac1{n+\cos(n)} \le \dfrac1{n-1}$$
Comment: That's right, thanks. My question still holds though
Comment: It doesn't help you to show that $a_n \le 2$ (or $\le 3$ or $\le 35436$) unless you can get *close* to the $2$.  And as $\sqrt{n^2 + 1} > n$ then $2n  -\sqrt{n^2 + 1} < 2n - n =n$ you cant really.  But we could do $\frac {n-1}{n+1}=\frac{2n-\sqrt{n^2 + 2n+1}}{n+1}< a_n < \frac{2n-\sqrt{n^2}}{n-1} = \frac {n}{n-1}$.  We also $\frac {n-1}{n+1} < 1 < \frac n{n-1}$ so $|1-a_n|< |\frac {n}{n-1}-\frac {n-1}{n+1}|=\frac {3n+1}{n^2-1}<\frac {3n+1}{n^2+\frac 13n}=\frac 3n$  so let $n_0 = \frac 3\epsilon$.
Comment: You can't really brush away $\sqrt{n^2 + 1} > n$ as "insignificant".  Yes, $2$ is an upper limit but but so is $57 \times 10^{google}$.  If we were comparing $\sqrt{n^2+1}$ to $n^2$ or if we were "brushing away" a constant compared to $n$ that'd be okay.  In terms of "brushing" away the $1$ compared to $n^2$ is insignificant and then $\cos n$ is insignificant to $n$ so $a_n =\frac {2n-\sqrt{n^2+1}}{n+\cos n} \approx \frac {2n-\sqrt{n^2}}n = \frac {2n-n}n =\frac nn =1$.  So the limit *ought* to be $1$. But "brushing off the insignificant" is not valid or rigorous enough for grown-ups.
Answer: It doesn't help you to show that $a_n \le 2$ (or $\le 3$ or $\le 35436$) unless you can get close to the $2$.  And as $\sqrt{n^2 + 1} > n$ then $2n  -\sqrt{n^2 + 1} < 2n - n =n$ you cant really get close to $2$.
But we could do $\frac {n-1}{n+1}=\frac {2n-(n+1)}{n+1} = \frac{2n-\sqrt{n^2 + 2n+1}}{n+1}<\frac {2n-\sqrt{n^2+1}}{n+\cos n}= a_n < \frac{2n-\sqrt{n^2}}{n-1} = \frac {n}{n-1}$.
We should just be able to look and $\frac {n-1}{n+1} \to 1$ and $\frac {n}{n-1}\to 1$ and use the squeeze theorem but... where's the fun in that?  Which is my tongue in check way of saying we'll never learn how to not fear delta epsilon proofs if we keep avoid them.
$\frac {n-1}{n+1} = 1-\frac 2{n+1} < 1 < 1 + \frac1{n-1} = \frac n{n-1}$.
So we have both $a_n$ and $1$ between the extremes of $\frac {n-1}{n+1}$ and $\frac n{n-1}$.
So $|1-a_n| < |\frac n{n-1} - \frac {n-1}{n+1}| = \frac 1{n-1} + \frac 2{n+1}< \frac 1{n-1} +\frac 2{n-1} = \frac 3{n-1}$.
So if we want $\frac 3{n-1} < \epsilon$ it is sufficient (more than sufficient) to have $\frac 3\epsilon < n-1$ so let $n_0 = \frac 3\epsilon +1$.


change color of javascript sentence

Question: I have the following code in javaScript, and it works fine.
But I need to know how can I change the appearance color to red or any other color besides black.
I'd appreciate if someone can help me.
Code:

Answer: How about wrapping the text in a span with red color

Comment: Simulpost with near-identical answers!
Answer:

Comment: @Andy Optional. Although I'd recommend including the `()`
Comment: `new Date` should be `new Date()` I think.
Answer: Then you have to put your code inside any (e.g. DIV) HTML element and style that element.
"
YOUR TEXT
"

don't forget that javascript is only something like "a  dynamic HTML support"... you usually  don't use .writeln() in the code. more like
document.getElementById('myDiv').innerHTML = "myBriliantText";

change color of javascript sentence


DeleteByQueryRequest socket timeout exception - java high level rest client api

Question: I'm a beginner to elasticsearch and I want to delete a huge amount of document which matches to the particular query. I'm using DeleteByQueryRequest for this purpose. I tried the code below.
String fileName="output2.log";
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest("_all");
deleteRequest.setQuery(QueryBuilders.termQuery("fileName.keyword",fileName));
deleteRequest.setTimeout(TimeValue.timeValueMinutes(10));
//deleteRequest.setRefresh(true);
BulkByScrollResponse bulkResponse = client.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
client.close();
System.out.println(bulkResponse.isTimedOut());
System.out.print("Deletion done");

When I run this code, the respective documents gets deleted but this code throws the below exception.
java.net.SocketTimeoutException: 30,000 milliseconds timeout on connection http-outgoing-0 [ACTIVE]

What can be done to get rid of this exception?
Thanks in advance.
Answer: After some research i found that the default socket timeout for RestHighLevelClient is 30000ms. I used the below code to extend the socket timeout duration.
RestHighLevelClient client = new RestHighLevelClient((RestClient.builder(new
      HttpHost(localhost,9200,"http"))).setRequestConfigCallback(requestConfigBuilder ->
     requestConfigBuilder
    .setConnectTimeout(10000)
    .setSocketTimeout(60000)
    .setConnectionRequestTimeout(0)
));

Now you can able to increase the timelimit in setSocketTimout() method.


How do you set "InstallShield Prerequisites Location"?

Question: I'm using InstallShield 2014 Pro and the C# automation to handle builds via TFS.  I can configure it to build as a setup.exe and extract the prereqs from setup.exe through the GUI but when I do it via code, it never sets the "InstallShield Prerequisites Location".  I'm fine with it being "Extract from Setup.exe" or "Follow Individual Selections".  It always defaults to "Copy From Source Media" even though its a web media format....
Here's the settings I set for the newly created release:
<code>m_Release.Compressed = true;
m_Release.MediaType = 4;
m_Release.SetupEXE = true;
m_Release.MSIEngineLocation = ISWiEngineLocation.eelSetupExe;
m_Release.MsiEngineVersion = ISWiMSIEngineVersion.eev31;
m_Release.DotNetVersion = ISWiDotNetVersion.env11;
m_Release.DotNetFrameworkLocation = ISWiDotNetFrameworkLocation.dnlSetupExe;
m_Release.WebType = ISWiWebType.ewtOneExe;
m_Release.DelayMSIEngineReboot = false;
</code>
Unless I'm missing it, there is no option for this in the help: http://helpnet.installshield.com/installshield21helplib/installshield21helplib.htm.
I believe I've at least narrowed it down to the ISSetupPrerequisiteLocation in ISRelease (in the Direct Editor).  It should be 1 but defaults to 0.  How to change it is still eluding me.
BTW, I have triple checked that all prereqs are set to extract from setup.exe.
Answer: As far as I can find, you cannot set this value through the api.
You can manually edit the xml or binary .ism file to set it but who wants to go through that trouble.  The easiest fix that I went with was to always reuse a release that has the field set.  We were originally creating a new release in install shield and thus needed to set the field.  Since the file is version controlled/tagged, its no big deal to go back to the older releases.


Linear independence of set in modules

Question:
Suppose $R$ be a commutative ring with unity and $N$ is a free $R$-module. m is a maximal ideal of $R$ and $m\in$ m. Then the set of elements $\{ x_1,x_2,...,x_{n-1}, m x_n \}$ which spans $N$ is not linearly independent.

My definition of free module is module with basis.
In case of integral domain, I proved it.
$$x_n=\alpha_1 x_1+...+\alpha_nmx_n$$
$$mx_n=m\alpha_1 x_1+...+m\alpha_nmx_n$$
Subtracting $mx_n$ gives,
$m(\alpha_nm-1)=0$. If $R$ is integral domain it forces either $m$ is unit or $0$. unit is not possible . So $m$ has to be 0. Showing that the last vector is redundant
But in general case i couldn't do. Please give a hint
Comment: This question arise while trying to prove rank of module is unique. I.e. number of basis elements is same for any basis
Comment: Is $N$ finite free?
Comment: Basically I was try to prove that if $x_i$ are basis of N . And m is maximal idea of R. Then $x_i$ are basis of $N/mN$ as R/m Vector space , so as to show rank of R-free module is unique . For that I want to prove that none of the $x_i$ belongs to **m**N
Comment: @shivering soldier  you can assume that
Answer: This is trivial.
Suppose it is linearly independent, then
$$x_n=\alpha_1 x_1+\dots+\alpha_nmx_n$$
Which shows $\alpha_nm-1=0$. So $m$ is unit. A contradiction to maximality of m
Comment: $x_1,..., mx_n$ are elements of $N$ which spans $N$ as R module. I use the same notation in my question
Comment: And where did you use the hypothesis that N is free?
Comment: I haven't use it here. It's not necessary but at first I thought that hypothesis would be necessary.  ( I thought if  $x_1,...mx_n$ for basis then $N$ is free but now since the last element is $mx_n$ this module is not isomorphic to $R^n$.  A contradiction for module being free)

Linear independence of set in modules


ASP.Net Gridview within Listview - how to access listview previous row data

Question: I've checked for hours on google but cannot find solution to my specific problem.
I'm new to ASP.NET & c# - I have a listview that contains rows of data (meeting dates), within each of these is a gridview showing any associated files to download. All works fine. Now I want to add another row with option to upload a file to that meeting. Upload works fine but I need to access the parent listview rows CRMID field (to pass through to stored proc to update database). I have tried so much but can't seem to access it.
Any help would be really appreciated thanks. I attach code but it's prob best shown with a screen shot (I'm new to this site so cant upload one but one can be viewed here: https://i.stack.imgur.com/NYf2o.jpg). When they click the upload button I want to access that CRMID from the previous row.
<asp:ListView ID="ListView1" runat="server" OnItemDataBound="ListView1_ItemDataBound" DataKeyNames="CRMID">
        <LayoutTemplate>

                     <%--"15px">--%>

                        CRMID

                        Period

                        Type

                        Planned Date

                        Actual Date

                        CRMNotes

        </LayoutTemplate>
        <ItemTemplate>

                            <%#Eval("CRMID") %>

                            <%#Eval("PeriodDescr") %>

                            <%#Eval("CRMType") %>

                            <%#Eval("CRMPlannedDate", "{0:dd/mm/yyyy}")%>

                            <%#Eval("CRMActualDate", "{0:dd/mm/yyyy}")%>

                            <%#Eval("CRMNotes")%>

                                <asp:GridView ID="GridView1" runat="server" class="MasterListView" AutoGenerateColumns="false" Width="100%"
                                            OnRowCommand="GridView1_RowCommand"
                                             >
                                    <Columns>
                                        <asp:BoundField HeaderText="File Name" DataField="ContractReviewMeetingFileName" ItemStyle-Width="80%"/>
                                        <asp:TemplateField HeaderText="Download" ItemStyle-Width="10%" >
                                            <ItemTemplate>
                                                <asp:LinkButton ID="lnkDownload" runat="server"
                                                    CommandArgument='<%# Eval("ContractReviewMeetingFileFullPath") %>' CommandName="cmdDownload">Download
                                                </asp:LinkButton>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:BoundField HeaderText="Upload Date" DataField="ContractReviewMeetingFileUploadDate"
                                        DataFormatString="{0:d}" ItemStyle-Width="10%" />
                                        <%--<asp:BoundField HeaderText="Description" DataField="ContractReviewMeetingFileDescr" />--%>
                                    </Columns>
                                </asp:GridView>

                                Upload File: <asp:FileUpload ID="FileUploader" runat="server"/>
                                <asp:Button ID="UploadButton" runat="server" Text="Upload" OnClick="UploadButton_Click" />

                                <asp:Label runat="server" id="StatusLabel" text="Upload status: " />

        </ItemTemplate>
    </asp:ListView>

And code behind (relevant function):
protected void UploadButton_Click(object sender, EventArgs e)
        {
            //FileUpload FileUploader = (FileUpload)ListView1.FindControl("FileUploader");
            var btn = (Button)sender;
            var item = (ListViewItem)btn.NamingContainer;

            var FileUploader = (FileUpload)item.FindControl("FileUploader");
            var StatusLabel = (Label)item.FindControl("StatusLabel");
            // I've tried various forms of below with no joy..
            //var itemParent = (ListViewItem)item.NamingContainer;
            //var CRMID = itemParent.FindControl("CRMID");

            string DefaultFileName = @"\\BCVSTORE03\PublicHealthStore$\CMS\Testing\";

            if (FileUploader.HasFile)
                try
                {
                    string filename = Path.GetFileName(FileUploader.FileName);
                    FileUploader.SaveAs(DefaultFileName + filename);//Server.MapPath(DefaultFileName) + filename);
                    //FileUploader.SaveAs(Server.MapPath(DefaultFileName) +
                    //     FileUploader.FileName);
                         StatusLabel.Text = "File name: " +
                         FileUploader.PostedFile.FileName + "
" +
                         FileUploader.PostedFile.ContentLength + " kb
" +
                         "Content type: " +
                         FileUploader.PostedFile.ContentType + "
Uploaded Successfully";

                }
                catch (Exception ex)
                {
                    StatusLabel.Text = "ERROR: " + ex.Message.ToString();
                }
            else
            {
                StatusLabel.Text = "You have not specified a file.";
            }

        }

Comment: I think you question shouldn't be an answer, it should be a comment really. Anyway, yes, i believe the right way is to use RowCommand for upload as well. You still should be able to get all infromation by `FindControl`, since RowCommand knows on which row it is triggered. But you also should be able to get row index, and use that to get the corresponding data key
Answer: Your FindControl call fails because there is no control to find. <%# %> does not output the control, just the string literal.
As a quick fix here is the suggestion. Have a hidden field nearby the upload control, that will provide you with the id:
Upload File: <asp:FileUpload ID="FileUploader" runat="server"/>
<asp:Button ID="UploadButton" runat="server" Text="Upload" OnClick="UploadButton_Click" />

<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
<asp:HiddenField runat="server" id="CRMIDHiddenField" Value='<%# Eval("CRMID") %>' />

And in the code behind use it:
var FileUploader = (FileUpload)item.FindControl("FileUploader");
var StatusLabel = (Label)item.FindControl("StatusLabel");
var CRMID = ((HiddenField)itemParent.FindControl("CRMIDHiddenField")).Value;

Other ways to fix that would be:

Use some control where you currently just output the CMDIR
[Proper way, in my opinion, but needs a lot of work] Refactor code to use list view commands instead of just individual controls events, and then use data keys.


Editable ListView

Question: I am looking to create an editable ListView in a C# winforms application where a user may double click on a cell in order to change its contents. It would be great if someone could provide my with some guidance and/or an example. I am not looking to use any commercial products.
Comment: Your question might be answered here: [C#: How do you edit items and subitems in a listview?][1]

  [1]: http://stackoverflow.com/questions/471859/c-how-do-you-edit-items-and-subitems-in-a-listview
Comment: I would disagree that we should not look at ListView alternatives like DataGridView, ObjectListView or even commercial solutions like [this](http://10tec.com/articles/editable-listview-replacement.aspx), which is cheap enough. Implementing the well-known approach with the textbox editor over ListView items/subitmes has many drawbacks you must solve yourself. For instance, you need to provide a good keyboard interface to edit subitems, the textbox should be scrolled together with the ListView, etc. Using a good 3rd-party solution may save hours of coding, and ultimately, you can even earn more.
Answer: You're asking the wrong question :)
A ListView is not the correct control. Use the DataGridView control. It can be configured to look just like a ListView, but it supports in-place editing of cells.
Comment: You can't do grouped views with the DataGridView. Plus a host of other features that only a ListView supports.
Comment: That's a matter of opinion. The DataGridView doesn't always fit the use scenario or provide the required look-and-feel. However, it is a possible alternative, depending on the goals of the OP.
Comment: Took me a minute, but, uh, yeah ... "List*VIEW*" ... view -not- edit. Funny thing, though, DataGridVIEW lets one *EDIT*. Hmmmm.
Answer: An ObjectListView will do exactly that and much more. It is a wrapper around a normal .NET ListView. It is open source.
Its website has a Getting Started to help you begin, as well as a whole page devoted to cell editing
Comment: Actually, it's not a custom control really. It's just a helpful wrapper around a plain ListView. But we won't tell anyone that :)
Comment: Thanks for your response. This custom control looks interesting, but may be overkill for what I'm trying to do. I shall experiment with it nonetheless.
Comment: It also might not be a suitable licence for all projects (as it appears to be under GPLv3)
Comment: editing is not good with this lib. when i press tab its so slow to open next control. cound't find a fix for that.
Answer: From the sounds of it, you might want to consider using the DataGridView instead.
DataGridView (MSDN)
Answer: You could use the listview's DoubleClick event, and when it is called, you would open a new form where the user would enter a new value for the selected item. Then when the user has pressed ok, you would edit the value of the specific item to what the user has entered.
Answer: DataGridView is your friend
SourceGrid is alternative
Answer: You could use a DataTemplate to specify that the column contains a textbox (if editable) or a textblock (if not editable) then bind the textbox to the class property from your Source Object Collection that is bound to your listview's itemsource.
<Window.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="NameHeader">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Name" VerticalAlignment="Center" Margin="10,0,0,0" />
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="NameCell">
            <StackPanel Orientation="Horizontal">
                <TextBox Text="{Binding Path=Name}" VerticalAlignment="Center" Margin="10,0,0,0" />
            </StackPanel>
        </DataTemplate>
    </ResourceDictionary>
</Window.Resources>

<Grid>
    <ListView x:Name="lvwList" Height="200" VerticalAlignment="Top" ItemsSource="{Binding Path=SourceObjectCollection}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" HeaderTemplate="{StaticResource NameHeader}" CellTemplate="{StaticResource NameCell}" Width="140" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

Nick Hanshaw
Comment: Welcome to SO, Nick. This is a good answer but unfortunately the question is tagged `winforms`, not `wpf`.
Answer: Yes, use a DataGridView.
Not only can you edit a cell, but if you declare a generic List where T is the class you want to display in the grid,  you can set the DataSource=that list and as you edit the gridview you are actually editing the List  automagically!
Answer: maybe this could help you:
msdn:How to create a ListView with Editable Cells
Comment: This is a WPF article. Is that what is desired, or are we looking at straight WinForms here? The tags indicate WinForms.
Answer: I recently encountered this issue. After taking the hint from Simon Gillbee that it is possible to configure DataGridView to appear much like ListView, I searched for a sensible solution to accomplish just that. The following code worked well for me. Source here.
class GridLineDataGridView : DataGridView
{
    public GridLineDataGridView()
    {
        this.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        int rowHeight = this.RowTemplate.Height;

        int h = this.ColumnHeadersHeight + rowHeight * this.RowCount;
        int imgWidth = this.Width - 2;
        Rectangle rFrame = new Rectangle(0, 0, imgWidth, rowHeight);
        Rectangle rFill = new Rectangle(1, 1, imgWidth - 2, rowHeight);
        Rectangle rowHeader = new Rectangle(2, 2, this.RowHeadersWidth - 3, rowHeight);

        Pen pen = new Pen(this.GridColor, 1);

        Bitmap rowImg = new Bitmap(imgWidth, rowHeight);
        Graphics g = Graphics.FromImage(rowImg);
        g.DrawRectangle(pen, rFrame);
        g.FillRectangle(new SolidBrush(this.DefaultCellStyle.BackColor), rFill);
        g.FillRectangle(new SolidBrush
           (this.RowHeadersDefaultCellStyle.BackColor), rowHeader);

        int w = this.RowHeadersWidth - 1;
        for (int j = 0; j < this.ColumnCount; j++)
        {
            g.DrawLine(pen, new Point(w, 0), new Point(w, rowHeight));
            w += this.Columns[j].Width;
        }

        int loop = (this.Height - h) / rowHeight;
        for (int j = 0; j < loop + 1; j++)
        {
            e.Graphics.DrawImage(rowImg, 1, h + j * rowHeight);
        }
    }
}

Just inherit from DataGridView and override the OnPaint method.
You can change the various properties of the control to suit your needs and preferences.
For those who need assistance with incorporating a custom control into their project look here.
Comment: The example is incomplete. For those new to WPF, where do you put the new DataGrid?
Comment: @CJohnson: This question is about WinForms and **not** WPF. Please check the question tag and context.

Editable ListView


javax.servlet.ServletException: javax.servlet.jsp.JspException: In <parseDate>, value attribute can not be parsed

Question: I have a Calendar object that I'm trying to pass to the JSP and format with JSTL into my own custom format:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:forEach items="${employees}" var="employee" varStatus="loop">
                <fmt:parseDate value="${employee.startDate}" var="parsedStartDate" pattern="HH:mm dd/MM/yyyy z" />
                <fmt:parseDate value="${employee.endDate}" var="parsedEndDate" pattern="HH:mm dd/MM/yyyy z" />
                var contentString = '
' +
                        '

${parsedStartDate}
 to
${parsedEndDate}

' +
                        '
' +
                        '
${employee.details}
' +
                        '
' +
                        '
';
</c:forEach>

The employee object is a standard Calendar.getInstance(); object.
edit, full exception:
java.text.ParseException: Unparseable date: "java.util.GregorianCalendar[time=1417392000000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/London",offset=0,dstSavings=3600000,useDaylight=true,transitions=242,lastRule=java.util.SimpleTimeZone[id=Europe/London,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=11,WEEK_OF_YEAR=49,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=335,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0]"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at org.apache.taglibs.standard.tag.common.fmt.ParseDateSupport.doEndTag(ParseDateSupport.java:187)
    at org.apache.jsp.index_jsp._jspx_meth_fmt_005fparseDate_005f0(index_jsp.java:459)
    at org.apache.jsp.index_jsp._jspx_meth_c_005fforEach_005f0(index_jsp.java:405)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:142)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
    at com.example.controller.EmployeeController.doGet(EmployeeController.java:48)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:620)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:745)

at com.example.controller.EmployeeController.doGet(EmployeeController.java:48) is: request.getRequestDispatcher("/index.jsp").forward(request, response);
Comment: what is the complete error?
Comment: updated question with it
Comment: how is startDate defined in employee class? looks like it is a Calendar instance instead of Date object
Comment: `private Calendar startDate;`
Answer: parseDate is used to parse string input and convert to Date object. You should not use parseDate. Instead use formatDate
<c:forEach items="${employees}" var="employee" varStatus="loop">
   var contentString = '
' +
     '

    <fmt:formatDate type="time" value="${employee.startDate.time}" pattern="HH:mm dd/MM/yyyy z"/>
 to

    <fmt:formatDate type="time" value="${employee.endDate.time}" pattern="HH:mm dd/MM/yyyy z" />

' +
    '
' +
    '
${employee.details}
' +
    '
' +
    '
';
</c:forEach>


Need help on $ \chi^2 $ test

Question: A die is thrown $150$ times with the following results,
No of tossed up - 1 2 3 4 5 6 and the frequency will be $19,23,28,17,32,31$.
I got the value for $(O-E)^2$ as $198..$ E is $25$.
I got the $X_2$ value as $7.92$ but in my text book it shows as $7.32$
Not sure where did I go wrong.Can someone help me with the right answer ?
Comment: $7.92= (36+4+9+64+49+36)/25$ looks reasonable
Answer: I assume you are testing the null hypothesis that the
die is fair.
Chi-squared statistic. As as stated in @Henry's Comment, the chi-squared statistic for your data computes to
$$Q = \sum_{i=1}^6 \frac {(X_i - E_i)^2}{E_i} = 7.92.$$
Using R as a calculator:
X = c(19, 23, 28, 17, 32, 31);  X
[1] 19 23 28 17 32 31
E = mean(X);  E
[1] 25
X - E
[1] -6 -2  3 -8  7  6
(X-E)^2
[1] 36  4  9 64 49 36
(X-E)^2/E
[1] 1.44 0.16 0.36 2.56 1.96 1.44
sum((X-E)^2/E)
[1] 7.92

If the die is fair, then $Q \stackrel{aprx}{\sim}
\mathsf{Chisq}(\nu = 6-1 = 5).$
Critical value for test at 5% level. The critical value for a test at the 5% level is $c = 11.0705.$  Because $Q < c$ you cannot reject the null
hypothesis, so you conclude that your 150 observed
rolls of the die are consistent with a fair die.
qchisq(.95, 5)
[1] 11.0705

P-value of the test. The P-value is the probability in the right-hand tail
of $\mathsf{Chisq}(5)$ beyond the observed value $Q = 7.92.$ That is, $0.1607 > 0.05,$ so you cannot reject the null hypothesis.
1 - pchisq(7.92, 5)
[1] 0.1607

In the figure below the density function of $\mathsf{Chisq}(5)$ is shown along with the observed
value $Q = 7.92$ (solid vertical line) and the
critical value $c = 11.0705$ (dotted vertical line).
The P-value is represented by the area to the right
of the solid vertical line.

Chi-squared goodness-of-fit test in R. In R statistical software, this test is performed as shown below. (The default null hypothesis is that categories are equally likely.)
chisq.test(X)

        Chi-squared test for given probabilities

data:  X
X-squared = 7.92, df = 5, p-value = 0.1607

Does $Q$ really have a chi-squared distribution? The test statistic has nearly a chi-squared distribution. As the sample size become infinite, the approximate becomes better. Simulation studies have shown that the fit is quite good provided that the expected count for each category (face of the die) is 5 or greater; here we have $E = 25.$
The simulation below shows that the true significance level using critical value $c = 11.0705.$ is very nearly 5%. The simulation is based on finding the value $Q$ for a million 150-roll experiments with a fair die.
set.seed(614)
q = replicate(10^6,
chisq.test(tabulate(sample(1:6, 150, rep=T)))$stat)
c = qchisq(.95, 5);  mean(q >= c)
[1] 0.049564

The histogram of the one million simulated values of $Q$ is shown below along with the density curve of $\mathsf{Chisq}(5).$ The proportion of the
simulated $Q$'s to the right of the critical value $c$ is very nearly 5%.

Power of the goodness-of-fit test. If your die is biased, then it is reasonable to ask how likely the test is to reject the null hypothesis. That probability is called the 'power' of the test.
Suppose we roll a 'loaded' die (perhaps with a lead weight embedded under face 1), for which the probability of getting  1 is $1/18,$ the probability of getting 6 is $5/18,$ and all other faces have probability $1/6.$
Thus the probability vector is not $p_0 = (1/6, 1/6, \dots, 1/6),$ as specified by the null hypothesis, but is has the alternative values $p_a = (1/18, 1/6, 1/6, 1/6, 1/6, 5/18).$
A simulation with such a biased die is shown below. We see that the power of the test against this alternative distribution is about 98.5%.
So we the test is almost sure to reject the null
hypothesis that such a die is fair.
set.seed(2019) ; p.a=c(1,3,3,3,3,5)/18
q = replicate(10^6,
chisq.test(tabulate(sample(1:6, 150, rep=T, prob=p.a)))$stat)
c = qchisq(.95, 5)
mean(q >= c)
[1] 0.984847

Theoretically, for large sample sizes, the distribution of the test statistic $Q$ is now a noncentral chi-squared distribution. The
noncentrality parameter is
$$\lambda = n\sum_{i=1}^6 \frac{(p_{ai}-p_{0i})^2}{p_{01}}.$$
Using the noncentrality parameter, we can get the
approximate power of the goodness-of-fit test against this specified alternative as 97.1%, which is not far from what we got from the simulation.
p.a = c(1,3,3,3,3,5)/18
lam = 150*sum((p.a-1/6)^2/(1/6)); lam
[1] 22.22222
1 - pchisq(c, 5, lam)
[1] 0.9709793

If the die were less heavily biased so that the respective values of faces 1 trough 6 are
$p_a = c(2/18, 1/6, 1/6, 1/6, 1/6, 4/18),$ then the power of the test would be only about 40%.
p.a = c(2,3,3,3,3,4)/18
lam = 150*sum((p.a-1/6)^2/(1/6)); lam
[1] 5.555556
1 - pchisq(c, 5, lam)
[1] 0.4018898

References; See Wikipedia for a basic explanation of the noncentral chi-squared distribution. This paper by W. Guenther in The American Statistician (1988) shows the use of the noncentral distribution in power computations for goodness-of-fit tests.

Need help on $ \chi^2 $ test