Distinguish Text of Certain Format with Python

Question: Alright, so I have a question to pose, and I'm not exactly sure how to phrase it, and I couldn't find anything on the Internet either for that same reason.  But I have a large text file, and it's an output from a Nastran job; here is a sample :
<code>                                         D I S P L A C E M E N T   V E C T O R

  POINT ID.   TYPE          T1             T2             T3             R1             R2             R3
    158819      G      1.709110E-04   7.605540E-16  -1.555717E-15  -4.860894E-18   1.829865E-03  -2.318361E-02
    158820      G      1.875926E-04   7.603908E-16  -1.382438E-15   2.883937E-18   3.121088E-04   2.332622E-02
    158821      G      1.275168E-04   6.281925E-16  -1.472595E-15  -1.425970E-17   4.282258E-03  -1.669750E-02
    158822      G      1.712281E-04   7.267596E-16  -1.473447E-15  -2.136693E-18   1.425850E-03   2.210620E-02
    158823      G      1.010464E-04   5.633097E-16  -1.426041E-15  -3.498301E-17   4.969753E-03  -1.144002E-02
    158824      G      1.274082E-04   6.164795E-16  -1.567410E-15  -5.947361E-18   3.224372E-03   1.580865E-02
                                                 L O A D   V E C T O R

  POINT ID.   TYPE          T1             T2             T3             R1             R2             R3
    158801      G      1.175810E+02  -3.610042E-16  -2.782717E-12   0.0            0.0            0.0
    158802      G      8.539756E+01   1.118419E-15  -2.639934E-12   0.0            0.0            0.0
    158803      G      9.717072E+01  -7.574143E-16  -2.682750E-12   0.0            0.0            0.0
    158804      G      1.175825E+02   0.0           -2.986422E-12   0.0            0.0            0.0
</code>
So as you can see, Nastran creates the file by heading each section with the name in all caps and a space between each letter, and three spaces between each word.  So my question is, if I have a script that looks for a POINT ID. in the file, how can I write it such that if I specify a section, it looks for the section name with the formatting, but it also stops at the next section, regardless of the name of the section, but stopping with respect to the formatting of the section header.
Thanks so much for any help, please let me know if that doesn't make sense.
Comment: I'm thinking [pandas](https://pandas.pydata.org) here.
Comment: Did you manage to solve your question?
Comment: I did, so sorry for not replying. It worked just fine.
Answer: On the top of my head I would read the file in, split the content by sep="   " (three spaces) and finally create a dictionary of the separate parts. The headers are the keys and the following rows are the values.
Comment: I'll try this out and let you know what happens.
Answer: The phrase for formatting that you might have been looking for can be called as pattern matching, or regex.
If all else fails, you should always be able to muscle your way through this problem using regex to find the end of a section.
Note that it might still be wise to follow up this code with logic that can import your data into pandas or something similar that you can manage easily.
If you wish to tweak this regex, i find regex101.com very useful. Hope this helps.
<code>import re
#matches the pattern UPPERCASE,SPACE followed by (UPPERCASE, SPACE) repeated,
#followed by TWO SPACE optional
#whole pattern can be repeated.
#You may want to tweak the rules to make it more strict as necessary.

pattern = re.compile("(([A-Z] )([A-Z] )+(  )?)+")

test = '''                                         D I S P L A C E M E N T   V E C T O R

  POINT ID.   TYPE          T1             T2             T3             R1             R2             R3
    158819      G      1.709110E-04   7.605540E-16  -1.555717E-15  -4.860894E-18   1.829865E-03  -2.318361E-02
    158820      G      1.875926E-04   7.603908E-16  -1.382438E-15   2.883937E-18   3.121088E-04   2.332622E-02
    158821      G      1.275168E-04   6.281925E-16  -1.472595E-15  -1.425970E-17   4.282258E-03  -1.669750E-02
    158822      G      1.712281E-04   7.267596E-16  -1.473447E-15  -2.136693E-18   1.425850E-03   2.210620E-02
    158823      G      1.010464E-04   5.633097E-16  -1.426041E-15  -3.498301E-17   4.969753E-03  -1.144002E-02
    158824      G      1.274082E-04   6.164795E-16  -1.567410E-15  -5.947361E-18   3.224372E-03   1.580865E-02
                                                 L O A D   V E C T O R

  POINT ID.   TYPE          T1             T2             T3             R1             R2             R3
    158801      G      1.175810E+02  -3.610042E-16  -2.782717E-12   0.0            0.0            0.0
    158802      G      8.539756E+01   1.118419E-15  -2.639934E-12   0.0            0.0            0.0
    158803      G      9.717072E+01  -7.574143E-16  -2.682750E-12   0.0            0.0            0.0
    158804      G      1.175825E+02   0.0           -2.986422E-12   0.0            0.0            0.0'''

#your input for beginning of a section header
begin = 'displacement vector'
#getting it into the correct style laid out here for section headers.
begin = ' '.join(begin.upper())
location = test.find(begin)

if location != -1:
    relevant_section = test[location + len(begin):]
else:
    relevant_section = test
#regex matching for end of section
end = pattern.search(relevant_section)
if end is not None:
    end = end.span()[0]
    relevant_section = relevant_section[:end]
</code>


Using set as an default parameter of recursive method in Python

Question: I wanted to do something like:
class foo():
    def __init__():
        ...
    def bar(self, param=set()):
        ...

where bar call itself using recursion, passing set. But after implementing following snippet my script started to do strange things. So I decided, that I will change it to the following form:
class foo():
    def __init__():
        ...
    def bar(self, param):
        if param is None:
            param=set()

After this change everything works as intended. Do anyone now, why the origin form does not work?
Comment: @Carcigenicate Not at all. From outside the object I call this function not using this parameter. Let's assume, that I want to check some properties of passed object. If I want to check some properties, from time to time I have to prove, that other property is owned by passed object. But I do not want to check previously checked properties, so I pass set of checked features, when I call bar inside bar.
Answer: This is a documented thing, from Docs

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function.

So, it says the second method, explicitly test for the parameters if None and then assign the empty set is the best way to avoid the problem.
Comment: Thats it! Thank you a lot. Actually there is nothing new to me in the quoted lines, but I wasn't thinking about this problem this way. Thank you so much!
Comment: I think this is one of the places where Python really screwed up.  This feature catches everyone, even if you know about it.
Comment: @FrankYellin yeah you are right, but bright community always bring workarounds for us!


How should I model a continuous dependent variable in the $[0, \infty]$ range?

Question: I have a dependent variable that can range from 0 to infinity, with 0s actually being correct observations. I understand censoring and Tobit models only apply when the actual value of $Y$ is partially unknown or missing, in which case data is said to be truncated. Some more information on censored data in this thread.
But here 0 is a true value that belongs to the population. Running OLS on this data has the particular annoying problem to carry negative estimates. How should I model $Y$?
> summary(data$Y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   0.00    0.00    0.00    7.66    5.20  193.00
> summary(predict(m))
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  -4.46    2.01    4.10    7.66    7.82  240.00
> sum(predict(m) < 0) / length(data$Y)
[1] 0.0972098

Developments
After reading the answers, I'm reporting the fit of a Gamma hurdle model using slightly different estimate functions. The results are quite surprising to me. First let's look at the DV. What is apparent is the extremely fat tailed data. This has some interesting consequences on the evaluation of the fit that I will comment on below:

quantile(d$Y, probs=seq(0, 1, 0.1))
        0%        10%        20%        30%        40%        50%        60%        70%        80%        90%       100%
  0.000000   0.000000   0.000000   0.000000   0.000000   0.000000   0.286533   3.566165  11.764706  27.286630 198.184818

I built the Gamma hurdle model as follows:
d$zero_one = (d$Y > 0)
logit = glm(zero_one ~ X1*log(X2) + X1*X3, data=d, family=binomial(link = logit))
gamma = glm(Y ~ X1*log(X2) + X1*X3, data=subset(d, Y>0), family=Gamma(link = log))

Finally I evaluated the in-sample fit using three different techniques:
# logit probability * gamma estimate
predict1 = function(m_logit, m_gamma, data)
{
  prob = predict(m_logit, newdata=data, type="response")
  Yhat = predict(m_gamma, newdata=data, type="response")
  return(prob*Yhat)
}

# if logit probability < 0.5 then 0, else logit prob * gamma estimate
predict2 = function(m_logit, m_gamma, data)
{
  prob = predict(m_logit, newdata=data, type="response")
  Yhat = predict(m_gamma, newdata=data, type="response")
  return(ifelse(prob<0.5, 0, prob)*Yhat)
}

# if logit probability < 0.5 then 0, else gamma estimate
predict3 = function(m_logit, m_gamma, data)
{
  prob = predict(m_logit, newdata=data, type="response")
  Yhat = predict(m_gamma, newdata=data, type="response")
  return(ifelse(prob<0.5, 0, Yhat))
}

At first I was evaluating the fit by the usual measures: AIC, null deviance, mean absolute error, etc. But looking at the quantile absolute errors of the above functions highlight some issues related to the high probability of a 0 outcome and the $Y$ extreme fat tail. Of course, the error grows exponentially with higher values of Y (there is also a very large Y value at Max), but what is more interesting is that relying heavily on the logit model to estimate 0s produce a better distribution fit (I wouldn't know how to better describe this phenomena):
quantile(abs(d$Y - predict1(logit, gamma, d)), probs=seq(0, 1, 0.1))
           0%           10%           20%           30%           40%           50%           60%           70%           80%           90%          100%
   0.00320459    1.45525439    2.15327192    2.72230527    3.28279766    4.07428682    5.36259988    7.82389110   12.46936416   22.90710769 1015.46203281
quantile(abs(d$Y - predict2(logit, gamma, d)), probs=seq(0, 1, 0.1))
         0%         10%         20%         30%         40%         50%         60%         70%         80%         90%        100%
   0.000000    0.000000    0.000000    0.000000    0.000000    0.309598    3.903533    8.195128   13.260107   24.691358 1015.462033
quantile(abs(d$Y - predict3(logit, gamma, d)), probs=seq(0, 1, 0.1))
         0%         10%         20%         30%         40%         50%         60%         70%         80%         90%        100%
   0.000000    0.000000    0.000000    0.000000    0.000000    0.307692    3.557285    9.039548   16.036379   28.863912 1169.321773

Comment: Is the variable continuous other than at 0? If so, a zero-inflated model (e.g. zero-inflated gamma / zero-inflated lognormal etc might be used)
Comment: Robert, some concrete examples of zero-inflated models to take it out of abstraction-land (and to help explain why they are not really about data "having a problem"): (1) how many cigarettes one smoked per day in the past 30 days may require a zero-inflated model, since *one must be in the habit of smoking cigarettes* for the number to be >0. (2) How many fish one caught on this boating trip requires that one *went fishing* for the number to be >0.
Comment: Yes. It's not a probit model for sure. I'm a bit hesitant about zero-inflated models, because it seems to suggest 0s were over-reported and the IV distribution "has a problem", so to speak, where in my case all IV values are correct.
Comment: And how about removing the intercept (I know, I know... but here the origin is truly 0)?
Comment: Can you give us some insight as to the data generating mechanism?  For instance, compound poisson distributions can handle this type of data, but really this is designed for modelling the sum of some statistic applied to a collection of random events (i.e. sum of cost of insurance claims on a policy).
Comment: @jlimahaverford Y is the distance from target in meters, so it cannot be 0.
Comment: @RobertKubrick is that a typo? Do you mean it _can_ be zero?
Comment: @ssdecontrol sorry I meant cannot be lower than 0.
Comment: @RobertKubrick a zero-inflated model would also make sense if you can postulate a two-step data generating process, where "zero or not zero" gets decided first, and then "how far, given not zero" gets decided after.
Comment: This may be a strange comment, but how are we hitting the target so much?  Is it big?  If the target is a point in space then we would expect distance from target to always be strictly greater than zero.  Consider the problem where the target is a circle of radius $r$.  I would be inclined to add $r$ to all my positive measurements and for my zeros sample (probably uniformly) from a circle of radius $r$.  This would give you positive values (almost surely) while not departing seriously from the true nature of the data generating mechanism.
Comment: @Glen_b Please see my added gamma hurdle model results.
Answer: Censored vs. inflated vs. hurdle
Censored, hurdle, and inflated models work by adding a point mass on top of an existing probability density. The difference lies in where the mass is added, and how. For now, just consider adding a point mass at 0, but the concept generalizes easily to other cases.
All of them imply a two-step data generating process for some variable $Y$:

Draw to determine whether $Y = 0$ or $Y > 0$.
If $Y > 0$, draw to determine the value of $Y$.

Inflated and hurdle models
Both inflated (usually zero-inflated) and hurdle models work by explicitly and separately specifying $\operatorname{Pr}(Y = 0) = \pi$, so that the DGP becomes:

Draw once from $Z \sim Bernoulli(\pi)$ to obtain realization $z$.
If $z = 0$, set $y = z = 0$.
If $z = 1$, draw once from $Y^* \sim D^*(\theta^*)$ and set $y = y^*$.

In an inflated model, $\operatorname{Pr}(Y^* = 0) > 0$. In a hurdle model, $\operatorname{Pr}(Y^* = 0) = 0$. That's the only difference.
Both of these models lead to a density with the following form:
$$
f_D(y) = \mathbb{I}(y = 0) \cdot \operatorname{Pr}(Y = 0) + \mathbb{I}(y \geq 0) \cdot \operatorname{Pr}(Y \geq 0) \cdot f_{D^*}(y)
$$
where $\mathbb{I}$ is an indicator function. That is, a point mass is simply added at zero and in this case that mass is simply $\operatorname{Pr}(Z = 0) = 1 - \pi$. You are free to estimate $p$ directly, or to set  $g(\pi) = X\beta$ for some invertible $g$ like the logit function. $D^*$ can also depend on $X\beta$. In that case, the model works by "layering" a logistic regression for $Z$ under another regression model for $Y^*$.
Censored models
Censored models also add mass at a boundary. They accomplish this by "cutting off" a probability distribution, and then "bunching up" the excess at that boundary. The easiest way to conceptualize these models is in terms of a latent variable $Y^* \sim D^*$ with CDF $F_{D^*}$. Then $\operatorname{Pr}(Y^* \leq y^*) = F_{D^*}(y^*)$. This is a very general model; regression is the special case in which $F_{D^*}$ depends on $X\beta$.
The observed $Y$ is then assumed to be related to $Y^*$ by:
$$
Y = \begin{align}\begin{cases}
0 &Y^* \leq 0 \\
Y^* &Y^* > 0
\end{cases}\end{align}
$$
This implies a density of the form
$$
f_D(y) = \mathbb{I}(y = 0) \cdot F_{D^*}(0) + \mathbb{I}(y \geq 0) \cdot \left(1 - F_{D^*}(0)\right) \cdot f_{D^*}(y)
$$
and can be easily extended.
Putting it together
Look at the densities:
$$\begin{align}
f_D(y) &= \mathbb{I}(y = 0) \cdot \pi &+ &\mathbb{I}(y \geq 0) \cdot \left(1 - \pi\right) &\cdot &f_{D^*}(y) \\
f_D(y) &= \mathbb{I}(y = 0) \cdot F_{D^*}(0) &+ &\mathbb{I}(y \geq 0) \cdot \left(1 - F_{D^*}(0)\right) &\cdot &f_{D^*}(y)
\end{align}$$
and notice that they both have the same form:
$$
\mathbb{I}(y = 0) \cdot \delta + \mathbb{I}(y \geq 0) \cdot \left(1 - \delta\right) \cdot f_{D^*}(y)
$$
because they accomplish the same goal: building the density for $Y$ by adding a point mass $\delta$ to the density for some $Y^*$. The inflated/hurdle model sets $\delta$ by way of an external Bernoulli process. The censored model determines $\delta$ by "cutting off" $Y^*$ at a boundary, and then "clumping" the left-over mass at that boundary.
In fact, you can always postulate a hurdle model that "looks like" a censored model. Consider a hurdle model where $D^*$ is parameterized by $\mu = X\beta$ and $Z$ is parameterized by $g(\pi) = X\beta$. Then you can just set $g = F_{D^*}^{-1}$. An inverse CDF is always a valid link function in logistic regression, and indeed one reason logistic regression is called "logistic" is that the standard logit link is actually the inverse CDF of the standard logistic distribution.
You can come full circle on this idea, as well: Bernoulli regression models with any inverse CDF link (like the logit or probit) can be conceptualized as latent variable models with a threshold for observing 1 or 0. Censored regression is a special case of hurdle regression where the implied latent variable $Z^*$ is the same as $Y^*$.
Which one should you use?
If you have a compelling "censoring story," use a censored model. One classic usage of the Tobit model -- the econometric name for censored Gaussian linear regression -- is for modeling survey responses that are "top-coded." Wages are often reported this way, where all wages above some cutoff, say 100,000, are just coded as 100,000. This is not the same thing as truncation, where individuals with wages above 100,000 are not observed at all. This might occur in a survey that is only administered to individuals with wages under 100,000.
Another use for censoring, as described by whuber in the comments, is when you are taking measurements with an instrument that has limited precision. Suppose your distance-measuring device could not tell the difference between 0 and $\epsilon$. Then you could censor your distribution at $\epsilon$.
Otherwise, a hurdle or inflated model is a safe choice. It usually isn't wrong to hypothesize a general two-step data generating process, and it can offer some insight into your data that you might not have had otherwise.
On the other hand, you can use a censored model without a censoring story to create the same effect as a hurdle model without having to specify a separate "on/off" process. This is the approach of Sigrist and Stahel (2010), who censor a shifted gamma distribution just as a way to model data in $[0, 1]$. That paper is particularly interesting because it demonstrates how modular these models are: you can actually zero-inflate a censored model (section 3.3), or you can extend the "latent variable story" to several overlapping latent variables (section 3.1).
Truncation
Edit: removed, because this solution was incorrect
Comment: Truncation is not correct; you indeed want censoring. Truncation of a continuous distribution leads to *zero* probability that an endpoint is realized.  Censoring of a distribution at zero causes the probability of all negative values to be accumulated at zero, creating a discrete atom there: "zero inflation." As a matter of fact, the comments suggest the censoring actually occurs at a tiny positive value $\epsilon$ and that all values less than $\epsilon$ are recorded as zeros: that is censoring, pure and simple.
Comment: That sounds like a more complicated model (in general) than the simple censored regression one I described. I am not suggesting the boundary for $y$ will vary: however, relative to the distribution of the *residual*, the boundary does vary. If you like, let $\theta=X\beta$ and set $F_\theta(y)=F(y-\theta)=F(y-X\beta)$, so that $F_\theta(0)=F(-X\beta)$: that exhibits my model as a special case of the more general one you just described.
Comment: @whuber I just never thought about that before. For a r.v. $X$ that is truncated below $c$, $\operatorname{Pr}(X \leq c) = 0$, right? That, and the half-Cauchy or half-t distributions are used for _positive_ scale parameters, anyway. Now I'm curious about the difference between censored distributions and boundary-inflated truncated distributions...
Comment: Mathematically I see no difference. Conceptually I would be willing to acknowledge that there may be a subtle difference, in that the censored distribution suggests to us what the distribution of a hypothetical uncensored result would be, whereas sticking an atom at the boundary of a truncated distribution makes no suppositions about that hypothetical distribution. There can be a mathematical (*i.e.* real) difference in more complex censoring situations, such as when censoring limits vary.
Comment: @whuber it just comes down to how the atom is parameterized, right? As in, a zero-censored Gaussian would be equivalent to a zero-inflated, truncated Gaussian with a Probit "link function"
Comment: I think so. I realize my earlier comments were conceptualized in a non-regression framework. For regression the truncation/censoring limit *must* be allowed to vary. For a parent distribution $F$ and left-censoring limit $0$, the likelihood of $y$ given covariates $X$ and parameters $\beta$ is $dF(y-X\beta)$ for $y\gt 0$ and otherwise is $F(-X\beta)$, which obviously varies since $X$ must vary. I presume your "truncated" models operate similarly. I'm not sure what role a link function would play here.
Comment: @whuber are you sure? Wouldn't it just be $F_\theta(y)$ where $\theta$ is some parameter that depends on $X\beta$? Then the mass at the censoring boundary (let's say zero) would be $F_\theta(0)$. That's what I know as the Tobit-I model, and it wouldn't make sense in most of the typical econometrics applications if the boundary itself were forced to vary.
Comment: @whuber very good point, and now that I think about it that must actually be the case with the Tobit regression as well (although I've never seen it brought up in an econometrics paper or textbook).
Comment: @ssdecontrol I was leaning towards a gamma hurdle model, intuitively it makes the most sense for my problem. I'm not clear why you would use a Tobit model censored at 0 instead. Some information here: http://seananderson.ca/2014/05/18/gamma-hurdle.html
Comment: @RobertKubrick I'm not sure either -- you know your data better than I do! But I wanted to at least clarify what the model does because there seemed to be some confusion about it in your question
Comment: @ssdecontrol ok, I think it would be interesting to understand the mathematical differences between a censored 0 and gamma hurdle model. But that's the subject for a different, more complex question...
Comment: @RobertKubrick that's a bit of what I got into with whuber. I can edit in some details about the distinction
Comment: @ssdecontrol Yes, now that we've narrowed the focus to those two methodologies, it would be very interesting to understand the differences! Gamma hurdle vs. Tobit censored at 0, that is.
Comment: Zero-inflation and hurdle models are nicely compared and contrasted at http://seananderson.ca/2014/05/18/gamma-hurdle.html.  In brief, the hurdle models allow the zero responses to be modeled differently than the non-zero responses, thereby being more flexible but less parsimonious. I imagine the initial choice of a model would rely primarily on your concept of how the data are generated.
Comment: Although this answer keeps getting better and better, your description of censoring doesn't really fit the introductory characterization. It doesn't work by first determining whether $Y \gt 0$. Instead, the observations (for left censoring at zero) are simply the transformed variable $\max(0, Y^{*})$. It's unclear what "$l$" is or what role it plays, either.
Comment: @whuber that equation is riddled with typos. Also, I know this isn't the typical interpretation of censoring but I wanted to tie them together. The "$max$-transformed" version is very concise for this case but it doesn't generalize to multiple censoring bounds.
Comment: But you're right that it isn't necessary. I fixed the equation and dropped that characterization entirely
Comment: @ssdecontrol Added results from gamma hurdle model.
Comment: Sorry for off-topic; could you please take a look at this Meta discussion? https://stats.meta.stackexchange.com/questions/5040 I think your opinion would be important as you seem knowledgeable in this topic. Cheers.
Answer: Let me start by saying that applying OLS is entirely possible, many real life applications does this. It causes (sometimes) the problem that you can end up with fitted values less than 0 - I assume this is what you are worried about? But if only very  few fitted values are below 0, then I would not worry about it.
The tobit model can (as you say) be used in the case of censored or truncated models.
But it also applies directly to your case, in fact the tobit model was invented your case. Y "piles" up at 0, and is otherwise rougly continuous. The thing to remember is that the tobit model is difficult to interpret, you would need to rely on APE and PEA. See the comments below.
You could also apply the possion regression model, which has an almost OLS like interpretation - but it's normally used with count data. Wooldridge 2012 CHAP 17, contains a very neat discussion of the subject.
Comment: "the tobit model has no real interpretation" could you explain this a bit more? I can't say I agree with that statement as-is.
Comment: I added the negative estimate percentage to my question. It's 10% of the sample, quite high. What would be $c$, the censoring constant, in my case? There is no fixed censoring value after which $Y$ becomes 0. And what are APE and PEA?
Comment: @ssdecontrol In the tobit model the \beta_j measure the partial effects of the x_j on E(y*|x), where y* is the (so-called) latent variable.

The variable that OP would like model is y, which is the observed outcome (hours worked, charitable contributions etc.). This is why one should rely on the average partial effect (APE) and partial effect at the average (PEA).

You should not use the censored model. If your data was censored you would know, ie: you have a question about income, where the last answer is "I earn more than $x", that information can "put into" the estimation -> censoring.
Comment: @user3551644 sure, but I don't see how you can say that the model therefore has "no real interpretation"
Comment: Hmm, okay, I will update my answer.
Comment: The likelihood functions of censored and truncated models can differ radically with the same data. In what circumstances is your claim true that they are "almost identical"?


Como apagar informação no BD usando DataGridView?

Question: alguém sabe me informar qual comando devo colocar para apagar do Banco de dados usando a informação da celular selecionada?
Coloquei assim:
    SQLcmd.CommandText = ("DELETE FROM usuario WHERE nome = '" & DataGridView3.IsCurrentCellInEditMode & "' ")

mas pelo visto não deu certo....
Answer: Para pegar o valor do dataGrid seria apenas isso:
var valordacelular = DataGridView3.CurrentCell.Value;

Não é indicado você concatenar o valor direto na string do SQL não, abaixo como sua linha iria ficar, mas que não é aconselhável.
SQLcmd.CommandText = ("DELETE FROM usuario WHERE nome = '" & DataGridView3.CurrentCell.Value & "' ");

O correto seria você adicionar parâmetros dentro da String assim:
SQLcmd.CommandText = ("DELETE FROM usuario WHERE nome = @param1");
SQLcmd.CommandType = CommandType.Text;
SQLcmd.Parameters.Add(new SQLiteParameter("@param1", DataGridView3.CurrentCell.Value));

Comment: entendi, mas seu deixar como vc disse que minha linha iria ficar e não é aconselhavel, teria algum problema de execução?
Comment: Não teria problema de execução não.
Comment: eu deixei desta forma
        SQLcmd.CommandText = ("DELETE FROM usuario WHERE id = '" & DataGridView3.CurrentRow.Cells(0).Value & "' "
Comment: isso, no caso vc pega a linha selecionada e a celula zero dela, vai pegar o valor do id que você quer sim. Bom que te ajudou, se atendeu sua dúvida não deixa de marcar  resposta.
Comment: obrigado, ajudo sim :)


How can i refresh all Views in Database in SQL server

Question: I want to refresh all views in Database because i renamed some columns and add some more columns in tables so i need to update all views by refreshing them
i created all views as select * from tableName only
Comment: You need to get a list of all views and call sp_refreshview for each one. But you should stop using * in  views.
Comment: Why did you bother creating views at all if they all all "select * from tableName only"? That defeats the purpose of views; you might as well select directly from the tables.
Comment: I assume by "refresh" you mean "change the views so they now show the renamed/new columns"? No way to do that without an external tool or some sophisticated implementation. After all, how would the view *know* which of the new columns it should include?
Comment: @DanGuzman select P.*, S.Col1, C.Col2 from PrimaryTable P (joined to) SecondaryTable S. First table is most of results, second table linked data. I do this ALL the time for search results and a column added to PrimaryTable will require a refresh. Concrete example - Person linked to Address.
Answer: Thank you guys for your response but below query fulfilled my requirement
    SET NOCOUNT ON

DECLARE @ActualView varchar(255)

DECLARE viewlist CURSOR FAST_FORWARD
FOR
SELECT
    DISTINCT s.name + '.' + o.name AS ViewName
FROM sys.objects o JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE   o.[type] = 'V'
        AND OBJECTPROPERTY(o.[object_id], 'IsSchemaBound') <> 1
        AND OBJECTPROPERTY(o.[object_id], 'IsMsShipped') <> 1

OPEN viewlist

FETCH NEXT FROM viewlist
INTO @ActualView

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @ActualView
    EXEC sp_refreshview @ActualView

    FETCH NEXT FROM viewlist
    INTO @ActualView
END
CLOSE viewlist
DEALLOCATE viewlist

Answer: DECLARE @Vie SYSNAME
DECLARE cr CURSOR LOCAL FAST_FORWARD FOR
SELECT DISTINCT s.name + '.' + o.name
    FROM sys.objects o JOIN sys.schemas s ON o.schema_id = s.schema_id
    WHERE   o.type_desc='VIEW'
OPEN cr

FETCH NEXT FROM cr INTO @Vie
WHILE @@FETCH_STATUS=0
BEGIN
    PRINT 'exec sp_refreshview   '+''''+@Vie+''''
    EXEC ('exec sp_refreshview   '+''''+@Vie+'''')
    FETCH NEXT FROM cr INTO @Vie
END
CLOSE cr
DEALLOCATE cr

Comment: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it'd be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren't as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?**
Answer: you can use this,
DECLARE @sqlcmd NVARCHAR(MAX) = ''
SELECT @sqlcmd = @sqlcmd +  'EXEC sp_refreshview ''' + name + ''';
'
FROM sys.objects AS so
WHERE so.type = 'V'

--SELECT @sqlcmd     //**uncomment this line if you want to see all views names

EXEC(@sqlcmd)

Comment: This doesn't include the schema in the view reference (essentially ***assuming*** everything resides in the current schema or `dbo`), and it doesn't quote view names that need quoting (views named with space, for example, will cause this to error).
Comment: Even if there is space on the name of the view it will work, and on the other side he executes the query in the database where he wants to do the refresh
Comment: A database is not a schema!
Comment: I think that one of us did not quite understand his question (maybe me), otherwise it is that he has to make modifications on the columns of his database and he just wants to refresh his view, if he executes this query in his database it will do the trick.

Regards,
Comment: If in the database `x` and he creates a view `v`, that view can be addressed through `x.dbo.v` or `dbo.v` or just `v`. Your code does the latter. But, if they create a SCHEMA called `y` inside database `x`, and then create the view `v` there, it can be addressed through `x.y.v` or `y.v`, but not through just `v`. It will still be in the `sys.objects` as `v`, and so your code will try to address `v`, and error. You need to ALSO check `sys.schemas`, just like the Other Answer Here! Your answer DOES NOT RELIABLY WORK.
Comment: Look at this example...  https://dbfiddle.uk/_Oo_2AIj


Darboux sums of an indicator function.

Question: Let $a < c < d < b$.  Let $f(x)=\begin{cases} 1 \text{ if } x \in [c,d]\\ 0 \text{ if } x \in [a,b]\setminus[c,d]. \end{cases}$
I want to verify that I understand how to properly apply the upper and lower Darboux sums.
Let $P=\{a=x_0<...<x_{k-1}<c<x_k<...<x_{l-1}<d<x_l<...<x_n=b\}$
$U(f,P)=\sum\limits_{i=1}^{n}M_i(f)\Delta x_i=\sum\limits_{i=k}^{l}M_i\Delta x_i=x_l-x_k \geq d-c.$
Verify that $L(f,P) \leq d-c$.  This is my attempt at a verification.
$L(f,P)=\sum\limits_{i=1}^{n}m_i(f)\Delta x_i=\sum\limits_{i=k-1}^{l-1}m_i\Delta x_i=x_{l-1}-x_{k-1} \leq d-c.$
Is my verification correct?
Comment: Your definition of $f$ is not clear, as you use the interval $[c,d]$ both times. Also, since you use $\Delta x_i = x_i - x_{i-1}$
$$
  L(f,P) = \sum_{i=k\color{red}{+1}}^{l-1}M_i\Delta x_i.
$$
Comment: @emka: well, it can be $k$ as well but the point is that $\min\{f(x):x\in [x_{k-1},x_k]\} = 0$ so that the sum ends up in $x_{l-1} - x_{k+1}$.
Comment: Shouldn't your $f(x)=0$ if $x\in [a,b]\setminus [c,d]$ instead of the other way around?
Comment: I just noticed that I defined the function incorrectly.  Also, why does it have to be $k+1$ and not just $k$?
Comment: @Ilya This makes more sense.  Thanks!
Answer: Yes, this is correct except for some indices. Just to sum up:
$$
M_i=\sup_{[x_{i-1},x_i]}f=
\begin{cases}1,\quad &i=k,\ldots,l\\
0,&\text{otherwise}
\end{cases}
$$
by the definition of $f$ and your partition $P$. A similar thing holds for $m_i$. Then
$$
U(f,P)=\sum_{i=1}^n M_i(x_i-x_{i-1})=\sum_{i=k}^l (x_i-x_{i-1})=x_l-x_{k-1}\geq d-c,
$$
and similarly for $L(f,P)$. Note that you want $x_l$ to be larger than $d$ but $x_{k-1}$ to be  smaller than $c$ in order for the inequality to hold.
Comment: Thanks for helping me clear this up.  I haphazardly copied this example off of the board and didn't really understand it until now.

Darboux sums of an indicator function.


Chromium OpenGL dead project?

Question: I've recently started exploring the guts of VirtualBox's Guest Extensions on my Ubuntu Guest. Mostly from curiosity. Partly due to "OpenGL Warning: ... not found in mesa table" warnings. I noticed they are using Chromium OpenGL implementation.  I have a two part question.
1.How do I get rid of those warnings?  Are they indications of a larger problem?  I'm noticing repaint issues which lead me down this path.
2.Am I missing something are is this a 12 year old project last touched 6 years ago!?  Is it being actively developed some where else?  Will it support OpenGL 3?
Online references would be appreciated as I'm having a hard time finding anything other than these below.

http://sourceforge.net/p/chromium/discussion/stats
http://chromium.sourceforge.net/doc/index.html
Answer: The chromium project is basically dead since 2008 or so. There is no support for GL3.x, and it is not planned. Actually, implementing the main purpose of chromium (application-transparent distributed rendering by manipulating the GL command stream) is incredibly hard to outright impossible with the programmable pipeline and modern GL features.
I'm not really familiar with virtualbox, but I am aware that they just used parts of the chromium project to implement a hw-accelerated guest GL simply by forwarding the GL command stream to the host. Such a task is much easier to adapt to modern GL, as no real stream manipulation is to be done. But I'm not aware of how far they have come on that path. So consider this only half of an answer to your question.

Chromium OpenGL dead project?


Finding a confidence interval with two samples

Question: Let $X_1, X_2, \ldots, X_{n_1}$ and $Y_1, Y_2, \ldots, Y_{n_2}$  be two different independent i.i.d. samples from $N(\mu_1, \sigma^2)$ and $N(\mu_2, \sigma^2)$, respectively. Note the variances are the same. How can I find a $100(1 - \alpha)\%$ confidence interval for $4\mu_1 - 3\mu_2$?

I know the following derivation for a confidence interval for difference of means (however, the variables not necessarily have to be normal).
If we have variables $X$ and $Y$, and we define $\overline{X} = n_1^{-1} \sum_{i = 1}^{n_1} X_i$ and $\overline{Y} = n_2^{-1} \sum_{i = 1}^{n_2} Y_i$ to be rthe sample means, then $\hat{\Delta} = \overline{X} - \overline{Y}$ is an unbiased estimator for $\Delta = \mu_1 - \mu_2$. Furthermore, by the independence of the samples, we have $\text{Var}(\hat{\Delta}) = \frac{\sigma^2}{n_1} + \frac{\sigma^2}{n_2}$ assuming the variances are the same.
Now if we define $S_1^2 = (n_1 - 1)^{-1} \sum_{i = 1}^{n_1} (X_i - \overline{X})^2$ and $S_2^2 = (n_2 - 1)^{-1} \sum_{i = 1}^{n_2} (Y_i - \overline{Y})^{2}$ to be the sample variances, we can estimate the variances by the sample variances and consider the random variable $Z = (\hat{\Delta} - \Delta)/\left(\sqrt{\frac{S_1^2}{n_1} + \frac{S_2^2}{n_2}}\right)$, which follows a $N(0, 1)$ distribution due to the Central Limit Theorem. This leads to a $(1 - \alpha)100\%$ confidence interval for $\Delta = \mu_1 - \mu_2$ given by
$$\left((\overline{x} - \overline{y} - z_{\alpha/2}\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}, (\overline{x} - \overline{y}) \right) + z_{\alpha/2}\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}},$$
where the quantity $\sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}$ represents the standard error of $\overline{X} - \overline{Y}$.
However, I'm struggling to extend this to find a confidence interval for $4\mu_1 - 3\mu_2$ specifically when the samples come from normal distributions with a common sample variance. Can someone please help me approach this problem? Note that I would like to actually derive the interval myself and not just use R or some other software.
Comment: You don't need the delta method for this: you can directly (and easily) compute the distribution of the estimator $4\bar X - 3\bar Y.$
Comment: Do you know the Delta method?
Comment: Yes, I am aware of the Delta method, but I'm not sure how it can be applied here?
Answer: You could estimate $4\mu_1 - 3\mu_2$ by $\hat \Delta =4\bar X_1 - 3\bar X_2).$
Then
$$E(\hat\Delta) = E(4\bar X_1 - 3\bar X_2) = 4\mu_1 - 3\mu_2,$$
$$Var(\hat\Delta) = Var(4\bar X_1 - 3\bar X_2) = 16\frac{\sigma_1^2}{n_1} + 9\frac{\sigma_2^2}{n_2},$$
and
$$SD(\hat\Delta) = \sqrt{16\frac{\sigma_1^2}{n_1} + 9\frac{\sigma_2^2}{n_2}} =
\sigma\sqrt{\frac{16}{n_1}+\frac{9}{n_2}},$$
because the two variances are the same. In a balanced design with $n = n_1 = n_2,$
$SD(\hat\Delta) = 5\sigma/\sqrt{n}.$
You might estimate $\sigma$ by $\hat\sigma_p = \sqrt{\frac{(n_1-1)S_1^2+(n_2 - 1)S_1^2}{n_1+n_2-2}},$ or in the balanced case, $\hat\sigma_p =\sqrt{(S_1^2 + S_2^2)/2}.$
Thus a 95% confidence interval for $\Delta$ would be of the form
$\hat\Delta \pm t^*\left[\widehat{SD}(\hat\Delta)\right],$ where $t^*$ cuts probability $0.025$ from
the upper tail of $\mathsf{T}(\nu =n_1+n_2-2),$ Student's t distribution with
degrees of freedom $\nu = n_1+n_2-2,$ and $\widehat{SD}(\hat\Delta)$ is the
estimated standard error of $\hat\Delta.$
Simulation in R with $n_1 = n_2 = 16, \sigma=3, \mu_1 = 50, \mu_2 = 53,$
illustrates normal distribution of $\Delta.$
<code>n = 16; sg=3
set.seed(1234)
Dlt.est = replicate(10^6, 4*mean(rnorm(n,50,sg))
                          -3*mean(rnorm(n,53,sg)))
mean(Dlt.est)
[1] 40.99765    # aprx 41
4*50-3*53
[1] 41          # exact
var(Dlt.est)
[1] 14.08624
sd(Dlt.est)
[1] 3.753164   # aprx 3.75
5*sg/sqrt(16)
[1] 3.75       # exact

hist(Dlt.est, prob=T, br=30, col="skyblue2")
curve(dnorm(x, 41, 3.75), add=T, col="orange", lwd=2)
</code>
Comment: How did you get the expression for $\hat{\sigma_p}?$ And would $\overline{SD}(\hat{\Delta})$ just be equal to $\hat{\sigma_p}$ here?
Comment: I got $\hat \sigma_p$ as the square root of of the "pooled variance" $\hat \sigma_p^2.$ In the balanced case $\sigma_p^2$ is just the average of the two sample variances $S_1^2$ and $S_2^2.$ If sample sizes are unequal, the slightly messier formula gives greater weight to the larger sample in estimating the common variance $\sigma^2.$ // The answer to your second question is NO. The estimate of $SD(\hat \Delta)$ needs to take into account how $\Delta$ is defined in terms of the two samples (with coefficients 4 and 3, instead of just the usual difference).
Comment: Thank you. How can I compute $\overline{SD}(\hat{\Delta})$?
Comment: System went down to be maintained as I was answering your comment and fixing an (unrelated)  typo in my answer. I think I have restored everything, but ask again if unclear.
Comment: I gave the formula for the standard error $SD(\hat\Delta)$ in terms of $\sigma.$ Then you get the _estimated_ standard error $\widehat{SD}(\hat\Delta)$ by plugging in $\hat\sigma_p$ for $\sigma.$


Mudança de base binária para base decimal

Question: Venho tentando programar um código para resolução de um exercício. Eis a questão:
Escreva um programa na linguagem C que leia uma string de tamanho qualquer contendo dígitos binários e imprima na tela o valor decimal correspondente.
A leitura da entrada deve ser feita carácter a carácter usando a função getchar().
Contudo, após de criar um código que eu achava ser melhor complexidade para o programa, percebi um problema à qual não sei resolver.
O Código:
#include <stdio.h>

int main()

{
char c;
unsigned int dec=0, i=1;

do
{

    c = getchar();

    if ( c -'0'== 1)
    {
        dec+= i;
    }

    i*=2;

}
while(c != '\n');

printf("%d\n", dec);

return 0;
}

O problema é que o código está lendo o número e criando um polinômio com sentido esquerda -> direita, e polinômios de mudança de base são lidos no sentido contrario. Devido o uso da função getchar() não sei terminar o exercício. Alguém consegue resolver este problema ?
Comment: Qual é o problema ? Os resultados não dão corretos ? No teste rápido que fiz pareceu me correto
Comment: Para alguns números o programa funciona, o problema ta na logica o programa necessita ler do último para o primeiro, e eu n consigo implementar isso
Comment: Então alguns não funciona é isso ? Pode dar um exemplo de um que não funciona ? Fica dificil de corrigir o que quer que seja sem ver um exemplo que não está correto
Comment: 254 = 11111110, 508 = 111111100, 52 = 110100
Comment: nenhum deles da o numero exato, pois  o programa le neste sentido  --->
Answer: A lógica que tem funciona, mas lendo do bit de menor peso para o de maior peso. O que significa que tem de introduzir os bits ao contrário do que seria normal.
Para resolver esse problema em particular e mantendo a lógica que tem, pode guardar primeiro os bits num array, e depois percorrer esse array na direção inversa, aplicando as mesmas operações.
Exemplo:
#include <stdio.h>

int main() {
    char c;
    unsigned int dec = 0, i = 1;

    char bits[32];
    int bit_corrente = 0;
    while ((c = getchar()) != '\n') { //este while so guarda os bits
        bits[bit_corrente++] = c - '0';
    }

    int j;
    for (j = bit_corrente - 1;j >= 0; --j){ //agora percorre os bits na ordem inversa
        if (bits[j] == 1){
            dec += i;
        }
        i *= 2;
    }

    printf("%d\n", dec);
    return 0;
}

Veja no Ideone
É interessante mencionar que tem muitas formas de fazer a mesma conversão, mas esta é a mais semelhante à lógica que já tinha no código.


SSH with the -F option returns me usage

Question: I want to create a config file and tell ssh to deal with it. I don't want to use ~/.ssh/config because these are config files per project and not per user. So I'm trying to roll with:
ssh -F project_servers.ssh

And terminal returns ssh usage. This is the contents of the file I want SSH to play with:
Host preview
User xxxx
Port 52
HostName xxxx.com

Anybody knows what I'm doing wrong here?
Thanks
Answer: You still need to request the named Host section on the command line:
ssh -F project_servers.ssh preview

Comment: i hope you'll never extinct! Thank you sir, that was the hack indeed!

SSH with the -F option returns me usage


How to convert a Database from Sqlite3 to Mysql with Inconsistent Schema using Ruby

Question: I'm working with a project that is transitioning from sqlite to mysql. Unfortunately the schema of individual tables has changed somewhat and a wholesale import won't work. Are there any good tools or solutions to do this?
I'm using ruby on rails 3.0.10 currently. My best guess was going to be initiate a console session, use namespaced active record adapters to connect to both databases, and then copy all the items over in code.
(the original database is fairly small i.e. less than a few thousand rows per table)
Answer: What might be easiest is to export the Sqlite database in a format that can be loaded back in to MySQL directly, then create migrations that alter the schema as required, starting with the Sqlite structure and adjusting from there.
One tool you might try is yaml_db to dump the one database into fixture-style YAML files, and then load it back in on the other side.
Remember that your schema.rb file should be sufficiently database agnostic so as to allow you to rake db:create when switching your database.yml adapter definition.
You might want to create a separate environment for the previous structure by adding a new entry to database.yml and config/environments so you can switch back and forth without having to hack at a few different config files all the time.
Comment: I ended up writing a simple converter and DSL for a yaml_db doc that might be useful to others: https://gist.github.com/1444018


Semantically confusing webwork question Calculus 2

Question: Using disks or washers, find the volume of the solid obtained by rotating the region bounded by the curves $y=\sqrt{x-1}$, $y=0$, $x=2$, and $x=3$ about the $x$-axis.
To me it seems like this question is asking for the upper half of the solid because it specifies $y=0$.
Setting it up, then: $\dfrac{\pi}{2}\displaystyle\int_{2}^{3}\left(\sqrt{x-1}\right)^2dx$ and the answer is $3\pi/4$.
That is not the answer webwork is after, though.
What don't I understand about how $y=0$ figures in?
TIA
Comment: The $x$-axis is your axis of revolution. $y = 0$ is how you bound the region that you're revolving. They're two separate things.
Comment: Why have you divided your $pi$ upfront the integral by $2$? This is a classic disc problem.The $y=0$ ensures this is just a disc problem, otherwise it could have been a washer problem.
Comment: It already says the x axis. So why state it twice unless it adds some information?
Comment: Well, it's happy with that, so must be. Normally you don't include another function unless it modifies r, however.
Answer: The question is not asking for just the upper half as it's of the solid rotated completely around the $x$-axis. Note that to rotate a region with certain bounds around the $x$-axis, you need to know what those bounds are. In this case, the lower vertical bound is specified as being $y = 0$.
However, as imranfat's question comment indicates, if this lower limit was replaced by something else, say like $y = 1$ instead, you would still rotate it completely around the $x$-axis. However, because the rotation region is smaller, the resulting volume would be smaller as well. Also, because the lower bound would then no longer coincide with the line you're rotating around, i.e., the $x$-axis which is the same as $y = 0$, it would change from being a disc problem to being a washer problem instead.
Note the disc method to determine volume rotations is a special of the washer method, where the internal circle is a degenerate one with a radius of $0$. Thus, your current volume is double what your integral specifies, but with the lower bound squared being implicitly subtracted, i.e., it would be $\pi\int_{2}^{3}\left((\sqrt{x-1})^2 - (0)^2\right)dx$. Also, in my alternate example above of a lower bound of $y = 1$, the integral would instead be $\pi\int_{2}^{3}\left((\sqrt{x-1})^2 - (1)^2\right)dx$.
A more general different case would be if the lower bound of the region was $y = -1$ and rotating around the line $y = -2$. In this case, the region being rotated would include parts of both the upper & lower halves of the Cartesian co-ordinate plane being rotated. Also, since the height of the function would then be $\sqrt{x - 1} - (-2) = \sqrt{x - 1} + 2$, but with the height still being $-1 - (-2) = 1$ for the lower bound, the volume in this case would then be given by $\pi\int_{2}^{3}\left((\sqrt{x-1} + 2)^2 - (1)^2\right)dx$.
Comment: @mtlchk As KM101 stated, the lower bound of $y = 0$ and rotating around the $x$-axis are separate things, with them just happening to coincide. It also helps to make your work a bit easier. I added some more details about this in my answer, including about a more general different case. I hope this helps you to better understand what is going on.
Comment: Well, I was assuming that it specified y=0 for some reason. y=0 is the x axis, so saying it again must mean the volume that strictly lies between this curve and the x axis, not further.

Maybe I am trying to make something sensible that is just redundant, though.
Answer: The equation $y=0$ is the equation of the $x$-axis in the rectangular Cartesian plane.
Thus, the question is just telling you to calculate the area of the region between the given parabola, the vertical lines and the horizontal line that happens to be the $x$-axis.


How do you save additional parameters using Reform

Question: Here is my main Reform Form object;
class CardHolderSupplierForm < ApplicationForm
  property :supplier_id, validates: { presence: true }
  property :standing_order, form: StandingOrderForm
end

And the StandingOrderForm is;
class StandingOrderForm < ApplicationForm
  property :amount_pence
  property :reference
  property :frequency
end

I have a column in standing_orders called amount_currency that should always be "GBP". I cannot seem to get Reform to just shove this in for me. I have tried various ways;
class StandingOrderForm < ApplicationForm
  property :amount_pence
  property :reference
  property :frequency

  # does nothing
  def amount_currency
    "GBP"
  end

  # does nothing - can't even binding.pry
  def save
    model.amount_currency = "GBP"
    super
  end

I don't know how to get this working. The rest of the form works as normal.
Comment: If you want to do this without the reform gem I can show you how since Rails makes it easy.  Then you won't have to worry about playing nice with a prebuilt library and can customize things as normal.  Let me know if you're stuck and I'll show you how to setup form objects the Rails way.
Comment: thanks for the offer but it's a work project not a personal one and I am tied to Reform for this.
Answer: How about using Reform's default value setting?
property :amount_currency, default: "GBP"


AttributeError: 'Response' object has no attribute 'read'. Uses requsts and jsons

Question: Full code:
import requests as req
import json
Bin = int(300000)
BinMax = int(600000)
File = open("C:/Users/admin/Desktop/PS Now Generaetors/Bins.txt", 'a')

while Bin != BinMax:
    json1 = req.get("https://lookup.binlist.net/" + str(Bin))
    json2 = json1.text
    jsonout = json.loads(json2)
    country = jsonout["country"]
    cc = country["alpha2"]
    if "US" or "AT" or "BE" or "CA" or "FR" or "De" or "IE" or "JP" or "LU" or "NL" or "CH" or "GB" or "ES" or "IT" or "PT" or "NO" or "DK" or "FI" or "SE" or "PH" == cc:
        print (bin, "writed")
        File.write("\n" + str(Bin) + ";" + cc)
    Bin =+ 1

Full error:
Traceback (most recent call last):
  File "C:\Users\admin\Desktop\PS Now Generaetors\test.py", line 3, in <module>
    json2 = json1.read()
AttributeError: 'Response' object has no attribute 'read'

How to fix it? Please help.
Comment: `json2 = json1.read()` That line is not in the posted code sample.  Please edit the question to include your actual code.
Comment: Your posted code has `json2 = json1.text`, not `json2 = json1.read()`.  Also, the error message says it's on line 3, which does not match the posted code.  We can't help if you don't show us the real code you're using.
Comment: Josh Gordon, its full code and every string in question. I too dont understand why  error have string ```json2 = json1.read()```
Answer:
Use .json() to convert response to python dict. There's no need in import json usage.
Your country code comparison is invalid.

Try to do something like this:
import requests

Bin = 300000  # no need for int()
BinMax = 600000  # no need for int()
File = open("C:/Users/admin/Desktop/PS Now Generaetors/Bins.txt", 'a')
countries = ("US", "AT", "BE", "CA", "FR", "De", "IE", "JP", "LU", "NL", "CH", "GB", "ES", "IT", "PT", "NO", "DK", "FI", "SE", "PH")

while Bin != BinMax:
    response = requests.get("https://lookup.binlist.net/" + str(Bin))
    jsonout = response.json()  # use .json() to get response as JSON
    country = jsonout["country"]
    cc = country["alpha2"]
    if cc in countries:  # previous comparison won't work as you expect
        print(bin, "written")
        File.write("\n" + str(Bin) + ";" + cc)
    Bin =+ 1


Query for the creation date of indexes

Question: Is there a way to get the creation date of indexes?  I'm using the following query to identify indexes based on their name but would like to see a date and time stamp of their creation.  I'm hoping there is a way to join the sysindexes table to another via indid to get these details.
SELECT * FROM sysindexes WHERE name LIKE '%CustomReport%'

Right clicking on the index in ssms object explorer allows viewing the properties but a create date and time stamp is not included.
Comment: Is there a field associated with the index to tell when it was created? Such as `ID|Username|dateCreated`
Comment: Does this answer your question? [Get index creation date from SQL server](https://stackoverflow.com/questions/7579932/get-index-creation-date-from-sql-server)
Answer: If you join back to sys.objects there's a create date there.
select o.create_date
from sysindexes i
inner join sys.objects o
  on i.id = o.object_id

Comment: yes - but the create date appears to be the table creation not the index creation.
Comment: Hmm, you're correct...it looks like there's no way to find out after doing some more research. See this related question on SO: http://stackoverflow.com/questions/7579932/get-index-creation-date-from-sql-server
Comment: wow - that's bad news, but thanks for the link to the information.
Comment: * inner join sys.objects o on o.object_id = i.object_id

Query for the creation date of indexes


Courses, books or other resources specifically written to teach and help understand algorithmic notation?

Question: The algorithm course/book I'm taking (based on the book Algorithm Design by Jon Kleinberg and Éva Tardos) assumes we understand the language of algorithmic syntax used to describe problems and solutions, as well as theory.
However, the syntax is not intuitive (at least to me).
Basically, how would a brand new human who only knows English, understand ever thing in this book - between the words in English?
Aware of this question and the Wikipedia reference(s), it does provide a supplemental reference for after thought, which is great when in a pinch and need to "look-up" a specific....however, when attempting new algorithm problems, the reference does not translate to a transferable understanding.
Q:
Are there any courses, books or resources - specifically written to teach and help understand algorithmic language?
It seems like a cross between mathematical notation and theory notation? Not that I even know what that is... and other strange characters.
Comment: Algorithmic language? there are many of those.
Comment: I have no idea what "algorithmic language" could possibly mean.
Comment: @fkraiem: all those strange symbols between all the words in English, throughout the entire book. I was never taught what all this means...what is it even called? Sets and unions are maybe some of them....?
Comment: @P.S perhaps something like this: https://www.amazon.com/Mathematical-Notation-Guide-Engineers-Scientists/dp/1466230525#productDescription_secondary_view_div_1518326830085. Also this: https://en.m.wikipedia.org/wiki/List_of_mathematical_symbols. This is assuming I'm understanding correctly and your issue is with certain mathematical symbols.
Comment: @tyberius: yes, based on the Amazon pre-view that loos like what I am looking for. On another note, I am amazed that others are having trouble understanding my question...I must be further behind than I thought....Anyways, please add as answer so I can accept.
Comment: @P.S. for algorithms much of the notation used is from set theory and logic. The only other thing I would look into is complexity notation like Big O, which is kind of distinct to algorithms.
Comment: https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/
Answer: After briefly looking at the book, I think what you're most likely having trouble with is what I would call "basic formal mathematics notation", including set theory symbols, subscript notation for sequences, notation for functions, maybe summation notation, and the use of Greek letters.
At most colleges in the United States, computer science majors typically take a course called "Discrete Mathematics" or something similar during their first or second year which includes an introduction to set theory and formal mathematics.  This would include all of the notation that you're missing as well as some basic formal proof techniques such as mathematical induction.  The algorithms book that you're referring to seems to expect that students have taken such a course.
My advice would be to find something like a review book or outline of Discrete Mathematics and start looking through it.  I'm not that familiar with any of these, but looking on Amazon I notice Discrete Mathematics Demystified by Steven Krantz and Schaum's Outline of Discrete Mathematics by Seymour Lipschutz.  You could alternatively try to get an actual textbook on Discrete Mathematics, which would be much more complete but also longer.
Answer: Kleinberg & Tardos (KT) is a good second book into algorithms. It assumes a lot of basics. I'd place it at a senior undergraduate level with at least two prerequisites (intro programming, and intro data structures & algorithms). It could be that you are just in too advanced a course and should take a course leading into this one that will teach you the foundations.
An interesting practical/theoretical approach can be found in Sedgewick & Wayne (SW) Algorithms. It does go through a lot of basic notations and definitions in a comfortable pace. I hear there are videos for it too though I have not seen them. The approach here is close to a real programming language and its structure (Java). I do highly recommend jointly engaging with the practice of writing algorithms (also just called programming) and the theory that allows us to do this with some smarts at the same time. It may be worthwhile to supplement with a text in your chosen programming language if you do not have the background yet.
A book that fills some term definitions that you may miss in KT can be found in Michael Sipser's Introduction to the Theory of Computation. It's introductory chapter goes through all typically used mathematical notation and it defines what an algorithm is. You won't need much else from Sipser but it will give you clear and careful notation definitions that are quite broadly used across many texts.
Answer: Why don't you try a programming course for non-programmers, like this python one from coursera: https://www.coursera.org/course/pythonlearn
Comment: That did not seem to help, did not see anything in the course like in the book...


How to format a local time object in Go with correct minutes?

Question: Edit: I have updated the question with code that highlights why the alleged duplicate's solution doesn't work for me
I am trying to take UTC (+0000) times and format them into local times (eastern time in my case) without hard coding any timezone offsets (as to avoid implementing dst correction).
I have the following code which demonstrates the problem I am having
package main

import (
    "fmt"
    "time"
)

func main() {
    // Here I load the timezone
    timezone, _ := time.LoadLocation("America/New_York")

    // I parse the time
    t, _ := time.Parse("Mon Jan 2 15:04:05 +0000 2006", "Tue Jul 07 10:38:18 +0000 2015")

    // This looks correct, it's still a utc time
    fmt.Println(t)
    // 2015-07-07 10:38:18 +0000 UTC

    // This seems to be fine - -4 hours to convert to est
    t = t.In(timezone)
    fmt.Println(t)
    // 2015-07-07 06:38:18 -0400 EDT

    // This prints 6:07am, completely incorrect as it should be 6:38am
    fmt.Println(t.Format("Monday Jan 2, 3:01pm"))
    // Tuesday Jul 7, 6:07am
}

(https://play.golang.org/p/e57slFhWFk)
So to me it seems that it parses and converts timezones fine, but when I output it using format, it gets rid of the minutes and uses 07. It doesn't matter what I set the minutes to, it always comes out as 07.
Comment: @icza I have updated the question explaining the exact problem I have, including the solution from the "duplicate", which doesn't work for me.
Comment: Both the answers in the marked duplicate contains your solution (using `Time.In()`).
Comment: The other question was about how to make a new time instead of parse into a timezone which I am trying to do with ParseInLocation
Comment: You are printing the time wihtout the location. You can do

    `.Println(t.Format("Monday Jan 2, 3:01pm (MST)"))`

to print the time with the Location information. Also t.UTC() works. Your math is reversed.

    `// This looks correct, 20 - 0400 = 16 = 4pm`

The time should be added to get the UTC time. So UTC time is 12am next day rather than UTC minus 8

[Updated playground link](https://play.golang.org/p/WL9DQtvcBh)

See also the linked answer for `time.In()`
Comment: My math can't be reversed... I used a date returned by twitter at 4pm, and the twitter date said 8pm +0000, then golang converted it to 8pm -0400
Comment: @Stephen Yes, it is good now. Reopened and answered your question.
Answer: Your layout (format) strings are incorrect. As noted in the doc of the time package, the layout string must denote this time:
Mon Jan 2 15:04:05 MST 2006

When parsing, use the following format string:
t, _ := time.Parse("Mon Jan 02 15:04:05 -0700 2006", "Tue Jul 07 10:38:18 +0000 2015")

And when printing, use this format string:
fmt.Println(t.Format("Monday Jan 2, 3:04pm"))

This will result in your expected output:
Tuesday Jul 7, 6:38am

Try it on the Go Playground.


Passar dois conjuntos de valores do AJAX para controller

Question: Preciso passar os valores de uma view model, e de uma tabela, a da tabela está passando normalmente, quando passada sozinha, a do viewmodel não.
Segue como estou fazendo:
var model1 = objectifyForm(model);
    console.log(model1);
    debugger;
    $.ajax({
        url: '@Url.Action("Novo1", "PedidoFornecedor")',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        data: { valores: JSON.stringify(valores), model: model1 }
    });

Essa é a função que pega os input do form:
 function objectifyForm(formArray) {//serialize data function

    var returnArray = {};
    for (var i = 0; i < formArray.length; i++) {
        returnArray[formArray[i]['name']] = formArray[i]['value'];
    }
    return returnArray;
}

Porém no controller, de toda a forma que eu tento, um vem vazio, ou não vem com os dados corretos, como posso proceder?
[HttpPost]
    public IActionResult Novo1([FromBody]List<PedidosProdutosF> valores, NovoViewModel model)
    {
        if (ModelState.IsValid)
        {

Comment: mariana você vai ter que unir os dois objetos em um só e enviar um unico objeto
Comment: Como assim, unir os objetos ?
Comment: Vou escrever uma resposta
Comment: da uma olhada, se não funcionar me da detalhes que eu corrijo, principalmente na parte de criar o objeto novo no c#
Comment: pode colocar a classe NovoViewModel  e quais valores está passando no model1 .
Answer: É só você unificar os dois objetos dentro de um só, Ajax só passa apenas um objeto para o Controller...
var model1 = objectifyForm(model);
var _objetoUnificado = {Model:model1 , Valores:valores}; //passar esse objeto no AJAX
console.log(model1);
debugger;
$.ajax({
    url: '@Url.Action("Novo1", "PedidoFornecedor")',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: { objetoUnificado:_objetoUnificado }
});

[HttpPost]
public IActionResult Novo1([FromBody]ObjetoUnificado objetoUnificado)
{
    if (ModelState.IsValid)
    {
    }
}

Ai no seu C#, você cria um objeto chamado ObjetoUnificado com o NovoViewModel e List<PedidosProdutosF>
Comment: Eu crio a classe, com os dados, desta forma: `public class ObjetoUnificado {
            NovoViewModel model = new NovoViewModel();
            List valores = new List();
        }`
Comment: Sim, porém coloca os nomes iguais ao que está no javascript, mas ai fica de acordo com o que  você achar melhor, no meu exemplo ficou "Model" e "Valores" maiúsculo
Comment: Lembre-se , o javascript tem que ser um espelho do objeto C#, ele é case sensitive também ;)
Comment: Eu tentei, alterando para a primeira letra pra maiúsculo, porém mesmo assim, vem em null. `public class ObjetoUnificado {
            NovoViewModel Model = new NovoViewModel();
            List Valores = new List();
        }`
Comment: Como você está passando no ajax? igual ao que eu fiz?
Comment: Igualzinho, da mesma forma, Tentei até passando os parametros como JSON.stringify, e mesmo assim, ele sempre vai null.
Comment: Infelizmente, de toda forma que eu tento, retorna sempre null.
Comment: @marianac_costa vi na sua outra pergunta, que o `objetoUnificado` está minusculo no JS e maiúsculo no c#
Comment: Ele reconhece a classe, mas não passa os valores, no debugger eu vejo os valores corretamente.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/82370/discussion-between-leonardo-bonetti-and-marianac-costa).


javascript setting font-weight: want to set to bold or normal can't get it work

Question: I can't seem to workout how to get to the font-weight: bold; setting, I want to change the setting to normal or bold on the fly. any ideas?
HTML
<li onclick="showStuff(this)" id="tabs1" style="margin: -5px 0px 0px 0px; padding: 0px 10px; border-width: 1px 1px 0px; border-top-style: solid; border-right-style: solid; border-left-style: solid; border-top-color: rgb(215, 215, 215); border-right-color: rgb(215, 215, 215); border-left-color: rgb(215, 215, 215); font-family: inherit; font-size: inherit; font-style: inherit; font-variant: inherit; font-weight: bold; font-stretch: inherit; line-height: 1.7em; vertical-align: baseline; list-style: none; position: relative; z-index: 99; display: inline-block; float: left; bottom: 0px; background: none 0px 0px repeat scroll rgb(250, 250, 250);"
class="design1"><a style="margin: 0px; padding: 6px 1px 6px 2px; border: 0px; font-family: Verdana, sans-serif; font-size: 12px; font-style: normal; font-variant: normal; font-weight: bold; font-stretch: normal; line-height: 18px; vertical-align: baseline; outline: 0px; color: rgb(0, 0, 0); text-decoration: none; display: inline-block; text-align: center; min-width: 140px;"

test1

javascript.

This is a heading

This is a paragraph.

This is another paragraph.

<button>Add a class name to the first p element</button>

Answer: Your html is messed up. There's an unclosed -tag which has font-weight: bold; and it overrides font-weight: normal; on #tabs1.
Remove font-weight: bold; from  and it will work.

function showStuff(element)  {
  document.getElementById("tabs1").style.marginTop = "-5px"; // works fine.
  document.getElementById("tabs1").style.fontWeight = "normal"; // doesn't work, tried various settings.
}

      test1


Could not find a constructor that would match given arguments

Question: I'm trying to mock Microsoft.Azure.Cosmos.Table.CloudTable but I'm receiving:

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException: 'Can not instantiate proxy of class: Microsoft.Azure.Cosmos.Table.CloudTable.
Could not find a constructor that would match given arguments:
System.Uri

var cloudTableMock = new Mock<CloudTable>
        (new Uri("http://unittests.localhost.com/FakeTable"));

Answer: Reviewing the signature for CloudTable, I see it takes an optional TableClientConfiguration:
public CloudTable(Uri tableAddress, TableClientConfiguration configuration = null);

Passing the default value of the optional parameter works:
var cloudTableMock = new Mock<CloudTable>
        (new Uri("http://unittests.localhost.com/FakeTable"));
        , It.IsAny<TableClientConfiguration>());

Comment: You can also use `It.IsAny()` for the second parameter.


Unable to find resource style error

Question: I am having a problem with my stying where an error message is showing saying: Cannot find a Resource with the Name/Key PerformanceBarChartBarTemplate [Line: 454 Position: 35]
My style code is:

                </ResourceDictionary>
            </datavis:ResourceDictionaryCollection>
        </Setter.Value>
    </Setter>
    <Setter Property="LegendStyle">
        <Setter.Value>

        </Setter.Value>
    </Setter>
    <Setter Property="ChartAreaStyle">
        <Setter.Value>

        </Setter.Value>
    </Setter>
    <Setter Property="PlotAreaStyle">
        <Setter.Value>

        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="toolkit:Chart">
                <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}"
                    Padding="10">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <dataVisualizationToolkit:Title Style="{TemplateBinding TitleStyle}"
                                              Content="{TemplateBinding Title}" />
                        <Grid Margin="0,15,0,15"
                          Grid.Row="1">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <dataVisualizationToolkit:Legend x:Name="Legend"
                                           Style="{TemplateBinding LegendStyle}"
                                           Grid.Column="1"/>
                            <toolkitChartingPrimitives:EdgePanel x:Name="ChartArea"
                                           Style="{TemplateBinding ChartAreaStyle}">
                                <Grid Style="{TemplateBinding PlotAreaStyle}"
                                  Canvas.ZIndex="-1" />
                            </toolkitChartingPrimitives:EdgePanel>
                        </Grid>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And the control which it can't see is:
<ControlTemplate x:Key="PerformanceBarChartBarTemplate"
             TargetType="toolkit:BarDataPoint">
    <Border BorderThickness="0"
        Opacity="0"
        x:Name="Root">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.1" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal" />
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="MouseOverHighlight"
                                     Storyboard.TargetProperty="Opacity"
                                     To="0.6"
                                     Duration="0" />
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="SelectionStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.1" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Unselected" />
                <VisualState x:Name="Selected">
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="SelectionHighlight"
                                     Storyboard.TargetProperty="Opacity"
                                     To="0.6"
                                     Duration="0" />
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
            <VisualStateGroup x:Name="RevealStates">
                <VisualStateGroup.Transitions>
                    <VisualTransition GeneratedDuration="0:0:0.5" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Shown">
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="Root"
                                     Storyboard.TargetProperty="Opacity"
                                     To="1"
                                     Duration="0" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Hidden">
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="Root"
                                     Storyboard.TargetProperty="Opacity"
                                     To="0"
                                     Duration="0" />
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        <Grid Margin="0 4 0 4">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <Rectangle Fill="{TemplateBinding Background}"
                   Stroke="{TemplateBinding BorderBrush}"
                   StrokeThickness="{TemplateBinding BorderThickness}"
                   RadiusX="3"
                   RadiusY="3"
                   Grid.Row="0"
                   Grid.RowSpan="2">
                <Rectangle.Effect>
                    <DropShadowEffect BlurRadius="10"
                                  Direction="0"
                                  Color="#FFFFFFFF"
                                  ShadowDepth="0" />
                </Rectangle.Effect>
            </Rectangle>

            <Rectangle RadiusX="3"
                   RadiusY="3"
                   Margin="4"
                   Grid.Row="0"
                   Grid.RowSpan="2"
                   Opacity=".25"
                   Fill="White"
                   >
                <Rectangle.Effect>
                    <BlurEffect Radius="8" />
                </Rectangle.Effect>

            </Rectangle>

            <Rectangle RadiusX="3"
                   RadiusY="3"
                   Margin="2"
                   Grid.Row="0">

                <Rectangle.Fill>
                    <LinearGradientBrush>
                        <GradientStop Color="#99ffffff"
                                  Offset="0" />
                        <GradientStop Color="#22ffffff"
                                  Offset="1" />
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>

            <Rectangle x:Name="SelectionHighlight"
                   Fill="Red"
                   Opacity="0" />
            <Rectangle x:Name="MouseOverHighlight"
                   RadiusX="3"
                   RadiusY="3"
                   Fill="White"
                   Opacity="0" />
        </Grid>
        <ToolTipService.ToolTip>
            <ContentControl Content="{TemplateBinding FormattedDependentValue}" />
        </ToolTipService.ToolTip>
    </Border>
</ControlTemplate>

Answer: I think you just need to move the 'PerformanceBarChartBarTemplate' control template above the style you defined in the resource section.
Edit:
First you need to wrap your template in a style and give it a name

The reason of doing this is because I noticed I have to have the inner style named 'DataPointStyle' to get it working, and then I use BasedOn to get your template.
Here is how you define the palette.
    <toolkit:Chart.Palette>
        <toolkit:ResourceDictionaryCollection>
            <ResourceDictionary>

            </ResourceDictionary>
            <ResourceDictionary>

            </ResourceDictionary>
        </toolkit:ResourceDictionaryCollection>
    </toolkit:Chart.Palette>

I hope this helps.
Solution 2:
Just replace your setter of the Palette with this one. You will notice I added a x:Key to the style, which was what you were missing. I tested it and it works.
    <Setter Property="Palette">
        <Setter.Value>
            <toolkit:ResourceDictionaryCollection>
                <ResourceDictionary>

                </ResourceDictionary>

                <ResourceDictionary>

                </ResourceDictionary>
            </toolkit:ResourceDictionaryCollection>
        </Setter.Value>
    </Setter>

Comment: Thank you that does fix that problem - it is still not picking up the changes within the Control Template - Any ideas?
Comment: Well the control template will change the tooltip however the chart is still showing the default tooltip
Comment: that's because you are putting the style in the wrong place. pls see my edited answer.
Comment: That would work but was hoping to be able to change the colours of the chart and the tooltip. You example will only show one colour on the chart,#
Comment: oh sorry i misunderstood what you wanted to achieve, pls see my updated answer... hopefully this time it works as you expected. :)
Comment: Sorry for acting dumb but i'm totally confused now - do u mean that I dont style the chart I just add a barDataPointStyle. And if so where do I put the Palette?
Comment: okay, maybe i shouldn't tell you to create another style and then do BaseOn... pls see my updated answer...

Unable to find resource style error


what is the difference between GParsPool.withPool and GParsPool.withExistingPool?

Question: what is the difference between GParsPool.withPool and GParsPool.withExistingPool? I didnot understand what was explained in the documentation.
Answer: While the former creates a thread pool, the latter variant expects a pool instance as a parameter provided by the user.
Vaclav


What is the pattern in these ordering properties?

Question: I'm not exactly sure what my question is, but I've observed something about orders and would like to see if there is more of a story to this.

Let's assume $\;\lt\;$ is an order on some unspecified domain, and let's define $$
\newcommand{\calc}{\begin{align} \quad &}
\newcommand{\op}[1]{\\ #1 \quad & \quad \unicode{x201c}}
\newcommand{\hints}[1]{\mbox{#1} \\ \quad & \quad \phantom{\unicode{x201c}} }
\newcommand{\hint}[1]{\mbox{#1} \unicode{x201d} \\ \quad & }
\newcommand{\endcalc}{\end{align}}
\newcommand{\Ref}[1]{\text{(#1)}}
\newcommand{\then}{\Rightarrow}
\newcommand{\when}{\Leftarrow}
\newcommand{\true}{\text{true}}
\newcommand{\false}{\text{false}}
\tag{0}
a \le b \;\equiv\; a \lt b \lor a = b
$$  Now, as I recently discovered (when writing answer https://math.stackexchange.com/a/2251407/11994 where I used $\Ref{3}$), if the domain were the reals or the rationals then the following would hold:
\begin{align}
\tag{1} \langle \forall z :: z \le a \then z \le b \rangle \;\equiv\; a \le b \\
\tag{2} \langle \forall z :: z \lt a \then z \lt b \rangle \;\equiv\; a \le b \\
\tag{3} \langle \forall z :: z \lt a \then z \le b \rangle \;\equiv\; a \le b \\
\tag{4} \langle \forall z :: z \le a \then z \lt b \rangle \;\equiv\; a \lt b \\
\end{align}
Now visually it looks like $\Ref{4}$ is the odd one out, but let's see if that intuition is correct: I was wondering what kind of order we need to prove each of the above.
First let's look at the $\;\when\;$ direction: there, for all 4 equivalences, we only need the fact that $\;\lt\;$ is transitive.  For example, for $\Ref{3}$ we have that $\;z \lt a\;$ and $\;a \le b\;$ imply $\;z \lt b\;$ by transitivity.
For the $\;\then\;$ direction of $\Ref{1}$ and $\Ref{4}$ we see that we can simply choose $\;z := a\;$, and use the fact that $\;\le\;$ is reflexive (by definition $\Ref{0}$), in other words $\;a \le a\;$.
For $\Ref{2}$ we can choose $\;z := b\;$, and assuming $\;\lt\;$ is irreflexive (so $\;\lnot(b \lt b)\;$) we get $\;\lnot(b \lt a)\;$, and further assuming $\;\lt\;$ is trichotomous (so $\;a \lt b \lor a = b \lor b \lt a\;$) we get $\;a \le b\;$.
Finally the $\;\then\;$ direction of $\Ref{3}$ is the most complex one.  The best approach I found was to go existential:
$$\calc
    \langle \forall z :: z \lt a \then z \le b \rangle
\op\then\hint{see below, where $\;\lt\;$ is transitive and irreflexive}
    \langle \forall z :: z \lt a \then \lnot (b \lt z) \rangle
\op\equiv\hint{logic: DeMorgan}
    \lnot \langle \exists z :: z \lt a \land b \lt z \rangle
\op\then\hint{$\;\lt\;$ is dense, so $\;b \lt a\;$ implies there is a $\;z\;$ between them}
    \lnot (b \lt a)
\op\then\hint{$\;\lt\;$ is trichotomous}
    a \le b
\endcalc$$
where the first step above is proved as follows:
$$\calc
    z \le b \;\then\; \lnot(b \lt z)
\op\equiv\hint{logic}
    \lnot(z \le b \land b \lt z)
\op\when\hint{$\;\lt\;$ is transitive}
    \lnot(z \lt z)
\op\equiv\hint{$\;\lt\;$ is irreflexive}
    \true
\endcalc$$
So here we require that $\;\lt\;$ is transitive, irreflexive, trichotomous, and dense.
To summarize the requirements on $\;\lt\;$ that seem necessary to prove the statements above:
$$\begin{array}{cl}
\Ref{1}&\text{transitive}\\
\Ref{2}&\text{transitive, irreflexive, trichotomous}\\
\Ref{3}&\text{transitive, irreflexive, trichotomous, dense}\\
\Ref{4}&\text{transitive}\\
\end{array}$$
So by this table $\Ref{3}$ is the odd one out, since it requires the most properties of the order $\;\lt\;$: specifically it requires density, which makes it true for the reals and the rationals, but false for e.g. the integers.

So I think my questions are: Are all of the above indeed necessary, or can some be weakened?  And is there something more to this pattern?  Why does density only play a role in one of these equivalences?  Is there perhaps a more symmetrical way of organizing this information?
Comment: @coffeemath Yes, correct. [I was using](https://math.stackexchange.com/revisions/2252925/1) notations designed by Dijkstra et al. which I'm used to and fond of.  (See [EWD1300](http://www.cs.utexas.edu/users/EWD/transcriptions/EWD13xx/EWD1300.html) for details.)  Now edited to be a bit more mainstream. :-)
Comment: What does the extra colon in (1),(2),(3),(4) (between the two inequalities in these) mean? Same as "implies"?
Answer: Assume transitivity.
As you've already made the case, lifting density will give you a straightforward counter-example for $(3) (\implies)$.
To lift trichotomy, one must lift one or more of anti-reflexivity, anti-symmetry, or completeness.
Lifting completeness gives a straighforward lattice counter-example for $(2) (\implies)$, so completeness is necessary for $(2) (\implies)$.
Lifting anti-reflexivity, take a domain with some $a, b$ such that $b < b < a \land \lnot (a < a) \land \lnot (a = b) \land (\forall z: z \ge a \lor z \le b)$.  Thus, $z \le b \implies z < b$, so $\forall z: z < a \implies z \le b \implies z < b$, yet $a > b \land \lnot (a = b)$, i.e. $\lnot (a \le b)$ -- so anti-reflexivity is necessary for $(2) (\implies)$ as well.
Anti-reflexivity together with transitivity implies anti-symmetry, so anti-symmetry is also necessary for $(2) (\implies)$.
With all of anti-reflexivity, anti-symmetry ans completeness necessary for $(2) (\implies)$, trichotomy is also necessary.  Because $LHS (2) \implies LHS (3)$, any premise necessary for $(2) (\implies)$ is also necessary for $(3) (\implies)$, so trichotomy is also necessary for $(3) (\implies)$.
In conclusion: assuming transitivity, all the other premises are necessary as listed.
(Not sure about the rest of your questions, but you may want to check if 42 fits...)
Answer: For $(3)$ we can write:
$$\langle \forall z :: z \lt a \then (z \lt b \lor z=b) \rangle \;\equiv\; a \le b$$
which allows us to use the logic from $(2)$.
Answer:
Domain D is linear is sufficient. Assume left premise.  If not a <= b,
then a < b, thus b < b.  Also if D is almost complete (partial) order, then
D holds.
D can be a dense linear order or an almost complete dense order for 3 to hold.
Comment: Since transitive+irreflexive+trichotomous = (strict) linear = (strict) total, you're partially only restating what I said: for (2) strict lineair is sufficient, and for (3) strict dense linear is sufficient.
    However, I'm curious about the "almost complete" part of your statements.  What is an "almost complete order"?  I've searched for a while, but I found nothing that might be what you mean.
Comment: I've asked https://math.stackexchange.com/q/2283185/11994 for the "almost complete" part.


Why in Xcode, Groups can be created, but not real folders?

Question: When doing iOS programming, it is interesting that in Xcode (4.3.2), we can create groups, such as a group call Images, and add files to it (either as a link or choose "Copy items into group's folder").  So it looks like a real folder in the navigator, and it even mentions "copy into ... group's folder", but in fact there is no folder.  All added files are in the same location as the .m and .h files.
Why would we want Groups, but not real folder?  Is there advantage of Groups over the use of a folder?
Comment: at least when I right click on the project's folder, there is a choice for "New Group" but not "New Folder"
Answer: This is a pet peeve of mine.
I recommend, making the folder in your file system, where you have your project files, then drag that folder into Xcode where you want the group.  It will act like any other group, but now be linked to the folder on the file system.  Adding files to that group in Xcode now adds them to the folder in the file system.
Much cleaner way of working and helps when locating files in big projects.  Keeps git cleaner too.
Update for Xcode 9:
Once you have the groups in Xcode matching the directory structure on disk, moving a file from one group to another in Xcode will now move the file correctly on disk to match.
Comment: I just wonder why Xcode does not start out as just using folders instead of groups?
Comment: Yep, it keeps Git cleaner :)
Comment: Yeh noticed in Xcode 9 using folders for groups is now the default too
Answer:
Note: In Xcode 10, the default behavior now creates a linked folder when you create a new group. The information below still applies otherwise.

The recommended way to organize files is via groups, because it's more flexible than creating directories, and allows you to create complex file hierarchies while maintaining a totally different file hierarchy on the file system. It's simply an organization tool. That said, it is possible to turn groups into folder references, or create them initially as folder references.
Furthermore, using groups instead of folder references gives you greater flexibility if you need to change where things are in the file system - say you have a common folder of code that you use in a bunch of different projects. Groups allow you to organize the files inside of  projects as if they were in the projects, while still maintaining one copy of the code in a central location. And yes, you can do this with folder references as well, but groups are much more flexible if you later want to add other things to the same group but don't want them to be added to that common folder.
If you want to link a group to a folder, click on the group in the project file tree and hit command+option+1. Below the drop down that'll say something like "Path: Relative to Group" on the right, there's a little white square with a grey border around it kinda icon next to the word "none". Clicking on this and then selecting/creating a folder will bind the group to the folder.

Furthermore, when you drag a folder into Xcode, it will ask you if you want it to be a group or a folder reference:
Comment: But "bind the group to the folder" is not the same as "create folder references". The latter is special: it copies the *folder* into the build app.
Comment: However it is a pain when you want to look for a class in finder/svn and the directory structure is completely different
Comment: @htafoya I definitely agree. On the other hand, if you're reorganizing a bunch of files using groups instead of folders, there's less opportunity for merge conflicts in your actual source code since the files themselves don't move. There are absolutely important tradeoffs to consider.
Comment: I know some people prefer this style, and I'm sure it's great in theory. In practice... not so much. For instance my Xcode is currently crashing when I move things from one group to another. Hard to paint yourself as clever or in any way optimal if I can't organise my files at all
Answer: There is a Command Line Tool - "synx"
 available in github that do exactly what you need.
It reorganizes Xcode project folder in finder to match Xcode groups in project.
You can find it here:
https://github.com/venmo/synx
UPDATE: XCode 9 supports this feature by default. So, no need to use other tools anymore!
Comment: if you forgot to create folders while adding new group, then this is **the best** way to convert xcode groups into folder system


TypeError: $.post(...).success is not a function

Question: Can someone help me with my code below.. In Firefox developer tool I am getting error message: :TypeError: $.post(...).success is not a function
All variables are submitted from form page..
Any advice and suggestions will be appreciated ...
Thank you
$(document).ready(function(){

    $('#post-comment-btn').click(function(){

        var _comment = $('#comment-post-text').val();
        var _userId = $('#userId').val();
        var _userName = $('#userName').val();

        if(_comment.length > 0 && _userId != null) {

            $.post("ajax/comment_insert.php",

                {
                    task : "comment_insert",
                    userId : _userId,
                    comment: _comment,

                }
                ).success(
                    function(data)
                {
                    console.log("ResponseText:" + data);
                }

                );

            console.log(_comment + " Username: " + _userName + " User Id: " + _userId);

        } else {

            console.log("The text area is empty..");

        }

        $('#comment-post-text').val("");

    });

});

Comment: i mean... that function hasn't existed for a loooong time. Deprecated forever, and removed in 3.0 http://api.jquery.com/jquery.ajax/
Answer: There is no $.post().success method anymore, the function returns a promise, and can be used with done, fail, always, then etc, but not success
$.post("ajax/comment_insert.php", {
    task    : "comment_insert",
    userId  : _userId,
    comment : _comment,
}).done(function(data) {
    console.log("ResponseText:" + data);
});

The documentation for all ajax methods in jQuery now clearly states that

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback
  methods are removed as of jQuery 3.0. You can use jqXHR.done(),
  jqXHR.fail(), and jqXHR.always() instead.


vsftpd : limit connection to a set of IP addresses

Question: Is it possible to setup vsftpd to only accept connections from a certain set of IP addresses?
I've looked at the /etc/vsftpd.conf for options but there is no hint at that. The manual does not either.
My  Server OS : Red Hat Enterprise Linux Server release 6.5 (Santiago)
Answer: Seems you can use TCP Wrappers (just tested it on my Ubuntu) and use hosts.allow and hosts.deny to filter vsftpd access.
Add the following to your vsftpd.conf file :
tcp_wrappers=YES

Restart vsftpd.
In /etc/hosts.deny deny everyone for vsftpd :
vsftpd: ALL

Then, in /etc/hosts.allow add the authorized IPs :
vsftpd:192.168.0.39 192.168.0.50

Comment: nevermind: it works. Just be aware that you need to add a newline underneath the last command in your hosts.* files. (source: http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-tcpwrappers.html)
Comment: actually, it does not work. I can still access the server even though my IP adress is not one of the addresses listed in hosts.allow.
Comment: @pixeline Wow great and thanks for the info ! i admit i used to press "enter" each time i write a line in a file, so i didn't see this issue. Thanks for the tip ! Cheers


Cannot choose more than 520 files in the file upload

Question: I have an input element as below (Angular 6):
     <input type="file" (change)="uploadFile($event.target.files)" value="Add"
          [multiple]="true" accept="image/jpeg, application/pdf" />

And the event:
  uploadFile(event) {
    console.log(event);
  }

When I select up to 519 files, the element work file (the log is shown).
But if I select more than 519 files, nothing happen (the function uploadFile is not called).
I want to allow user to select up to 5000 files, is there anyway to do that?
Answer: That means, change event is not firing. You may be selecting an identical file already present or there may be some limit set for maximum file size or number of files. Also there is no need for value attribute in input[type='file'].


Calculate $\int_0^\pi{x\sin{x} \over 1+\cos^2x}dx$

Question: I am trying to get started on
$$\int_0^\pi{x\sin{x} \over 1+\cos^2x}dx$$
The usual trick I am familiar with would be to substitute $y=\tan{x \over 2}$. This doesn't seem to work in this case.
Comment: Doing quick numeric check says $\pi^2/4$.
Answer: Use the trick that $\int_a^bf(x)=\int_a^bf(a+b-x)$ we get
$$\int_0^\pi\frac{x\sin x}{1+\cos^2x}=\int_0^\pi\frac{(\pi-x)\sin(\pi-x)}{1+\cos^2(\pi-x)}=\int_0^{\pi}\frac{(\pi-x)\sin x}{1+\cos^2 x}$$
From this $$2\int_0^\pi\frac{x\sin x}{1+\cos^2 x}=\int_0^{\pi}\frac{(\pi-x)\sin x}{1+\cos^2 x}+\int_0^\pi\frac{x\sin x}{1+\cos^2 x}=\pi\int_0^\pi\frac{\sin x}{1+\cos^2 x}$$
With the substitution $u=\cos x$ we get
$$\pi\int_{-1}^1\frac{1}{1+u^2}=\pi(\arctan(1)-\arctan(-1))=\frac{\pi^2}{2}$$
So $$2\int_0^\pi\frac{x\sin x}{1+\cos^2 x}=\frac{\pi^2}{2}\\\int_0^\pi\frac{x\sin x}{1+\cos^2 x}=\frac{\pi^2}{4}$$
Answer: $$I=\int_0^\pi{x\sin{x} \over 1+\cos^2x}dx$$
Let $u= \pi-x$
$$I=\int_0^\pi{(\pi-x)\sin{x} \over 1+\cos^2x}dx$$
Thus
$$2I=\pi\int_0^\pi{\sin{x} \over 1+\cos^2x}dx$$
$$2I=-\pi\int_0^\pi{1 \over 1+\cos^2x}d(\cos x)$$
$$2I= - \pi \arctan(\cos x) \bigg|_0^{\pi}$$
$$=-\pi (\arctan(-1) - \arctan(1))$$
Thus
$$I=\frac{\pi^2}{4}$$
Comment: I'm afraid I'm gonna have to disagree with this solution: http://www.wolframalpha.com/input/?i=integral_0%5E%CF%80+(x+sin(x))%2F(1+%2B+cos%5E2(x))+dx
Comment: Check your result numerically.  This is far from the correct solution.
Comment: You left off the $\pi$. Also $arctan(cos(\pi)) = arctan(-1) = -\pi/4$. Then $2I = -\pi(-\pi/4-\pi/4) = \pi^2/2$ so $I = \pi^2/4$.
Comment: @SimplyBeautifulArt thanks, checking
Comment: @martycohen thank you so much! I was checking the earlier steps..