"Unable to find the report in the manifest resources" .NET 4.0

Question: I know this question have been asked before. But i have tried the answers in the other questions without any luck. I have removed the Namespacing from the .rpt file reference and also set the build action of the file to be Embedded Resource but nothing helps i still get the same error. The error occurs here:
<code>  public override string FullResourceName {
            get {
                return "RptManifest3.rpt";
            } <--------
            set {
                // Do nothing
            }
        }
</code>
When the code reaches the arrow i get the error. Anybody who can help with this ?
Comment: Please see this

[http://stackoverflow.com/questions/6367624/unable-to-find-the-report-in-the-manifest-resources/29602674#29602674][1]

  [1]: http://stackoverflow.com/questions/6367624/unable-to-find-the-report-in-the-manifest-resources/29602674#29602674
Answer: Finally i could solve the problem
just go to the references and choose all the 'dll's starts with 'crystalldesicion' there.
after you choose them all, find the 'Copy Local' property in properties table, now change its value to 'true'.
build the project and save it all.
now its ready to action


Use mobile phone number as account ID so users dont have to register?

Question: Im making a mobile first site. Is there a way of using a user's mobile phone number so they dont have to register for an account?
Or, if a user creates an account the normal way on a desktop and enters their phone number, is it possible to detect when the visit the site with a phone from that number and log them in?
Thanks
Answer: If I get you right you want detect that a user is recuring user? Generaly this can be done with a cookie.
Tecnicaly there is no reason to use a phone number. As far as I know there's no possibility for a web application to get the phonenumber automatically. A solution could be an app as frontend which delegates to the website.
Answer: You don't have access to the visitor's phone number when they visit your website from their phone. O2 recently got into a bit of trouble for sending the user's mobile number in the request headers.
According to the article:

Rival 3G networks are not appending visitors' phone numbers to the HTTP headers.

So I'm afraid there's no way to do this automatically.
You might want to look into building an app for the various platforms if that's an option, I believe in that context you do have access to the user's phone number.


Persisting URL params on form_set_error

Question: Scenario
I have a page which looks like
  http://notfound.stackexchange.com?a=1&b=2
After validation, i use form_set_error to display a drupal error message on the same page(url)
but end up without the url params
  http://notfound.stackexchange.com
Question

Is there a way to preserve/persist the url params on form_set_error ?
Is using drupal_goto the correct way (since i can send the url params again) to redirect to the same page ?
hidden form elements to store the params for use on different pages in the process flow, but as a last resort if there is no other way ?
Comment: Please let me see your `drupal_goto` code.
Comment: @NikhilM : `drupal_goto($url, array('query' => array('a' = $value1, 'b' = $value2)));`
Answer: <code>$form_state['redirect'] = FALSE;</code>
This works like a charm since the form is not rebuilt or reloaded.
Below link contains more info
https://drupal.org/node/1850410

Persisting URL params on form_set_error


How to get user id of order from order entity metadata wrapper

Question: I am implementing hook_commerce_cart_line_item_refresh(). It will be receiving line item and entity metadata wrapper for the commerce order.
How can I get user id of order from its metadata wrapper without loading user object like this
$uid = $order_wrapper->owner->value()->uid

With above line it will be loading user object. I would like to avoid loading user object and simply take uid directly.
Following line does not work:
$uid = $order_wrapper->uid;

Or should I think of loading order object? As it might be already in static cache.
Thanks
Answer: It's the same as any property on a metadata wrapper:
$uid = $order_wrapper->uid->value();

Or should I think of loading order object?

You can't have an entity metadata wrapper without an underlying entity, so the object you're referring to is already 'loaded'. You can get it with
$order = $order_wrapper->value();

Comment: Oh, why didn't I try that simple line!!
Comment: This is not correct, check 3rd answer,
$uid = $order_wrapper->author->uid->value();
Comment: The order entity has a uid property @Ponzio - it's correct. Your method is identical to this, except it involves unnecessary database calls
Answer: You need to get uid from the entity object.
$uid = $order_wrapper->value()->uid;

Answer: For a multi-valued entity reference field you can get the raw values using this pattern
$wrapper->field_multiple->raw()

This would return an array like this:
array(0 => 123, 1 => 456)

Answer: Correct answer is:
$uid = $order_wrapper->author->uid->value();
Comment: This isn't right - see [`commerce_order_entity_property_info()`](http://www.rit.edu/drupal/api/drupal/sites!all!modules!commerce!modules!order!commerce_order.info.inc/function/commerce_order_entity_property_info/7.43). The related user entity is available through the `owner` property, not `author`. This code might work for a node, or for a custom property you or something else has defined on commerce_order, but would be equally redundant as using `$order_wrapper->owner->uid->value()`, forcing a load of the user object just to get an ID you already have in `$order_wrapper->uid->value()`


If an integral is divergant with a non-negative intigrand, than the limit of the antiderivative is infinite

Question: Somebody asked me this question in calculus 2, which I've already done, but I finished it in like a year so I don't really remember that much.
The question is : "if $f(x)$ is a non-negative and continuous function in $(a,b] $, and  $ \int_a^bf(x)dx $ is divergent, then $ \lim_{ x\to a} \int_x^bf(t)dt = \infty$".
This is assuming that it is not bounded on $(a,b]$. The definition of a divergent integral is that the limit which I described does not exist.
Intuitively I was thinking that because $f(x)$ is non-negative, than it means that the anti-derivative is non-decreasing, but I forgot some things in calculus, so I could use your help.
Comment: This is impossible. If $f:[a,b]\to\Bbb{R}$ is continuous, then it is certainly bounded and Riemann-integrable (in the proper sense), so $\int_a^bf$ always exists. So, for your question to be non-trivial you have to drop the continuity hypothesis.
Comment: You're right, the function is continuous at $ (a,b] $. wow I forgot a lot of calculus...
Comment: Show that $F(x) = \int_x^b f(t) dt$ is decreasing on $(a,b]$ (think FTC). It follows that the limit exists if $F$ is bounded above.  Hence $\lim_{x \to a} F(x) = \infty$.
Answer: Since $f$ is non-negative, the function $F:(a,b]\to [0,\infty)$ defined as $F(x)=\int_x^bf$ will be (weakly) decreasing. So, $\lim\limits_{x\to a^-}F(x)$ always exists in $[0,\infty]$ (in fact, it equals $\sup\limits_{x\in (a,b]}F(x)$), and the question is whether the limit is finite or infinite. But, you're told that "$\int_a^bf$ is divergent", which means either:

$\lim_{x\to a^-}\int_x^bf$ is $\pm \infty$ or
$\lim_{x\to a^-}\int_x^bf$ does not even exist in $[-\infty,\infty]$

Well, like I mentioned above, since $F$ is a (weakly) decreasing function, the second option is not possible. So, only the first option is possible. Hence
\begin{align}
\lim_{x\to a^-}F(x)=\lim_{x\to a^-}\int_x^bf = \infty.
\end{align}
Comment: Why is the first option is the only one possible?
Comment: @TomerC. do you agree that for any (weakly) decreasing function, $\lim_{x\to a^-}F(x)=\sup_{x\in (a,b]}F(x)$, so this always exists in $[-\infty,\infty]$?
Comment: Bounded increasing or decreasing functions have a limit. Hence the function must be unbounded. Since it's decreasing and the limit does not exist, the limit from the right must be $\infty$.


Lifetime reference among struct data fields

Question: I have the following code which will throw me this error. Basically I want C to reference B which has reference to A.
How can I achieve this in Rust? Is it possible to do this with multiple life time?
Btw that I do not want to use Rc. Also I do not want C to own B.
struct A;

struct B<'a> {
    a: &'a A,
}

struct C<'a> {
    b: &'a B<'a>,
}

struct D<'a> {
    a: &'a A,
    b: B<'a>,
    c: C<'a>,
}

impl<'a> D<'a> {
    pub fn new(a: &'a A) -> D<'a> {
        let b = B { a };
        let c = C { b: &b };

        D { a, b, c }
    }
}

fn main() {
    let a = A;
    let d = D::new(&a);
}

error[E0515]: cannot return value referencing local variable `b`
  --> src/main.rs:22:9
   |
20 |         let c = C { b: &b };
   |                        -- `b` is borrowed here
21 |
22 |         D { a, b, c }
   |         ^^^^^^^^^^^^^ returns a value referencing data owned by the current function

error[E0505]: cannot move out of `b` because it is borrowed
  --> src/main.rs:22:16
   |
17 | impl<'a> D<'a> {
   |      -- lifetime `'a` defined here
...
20 |         let c = C { b: &b };
   |                        -- borrow of `b` occurs here
21 |
22 |         D { a, b, c }
   |         -------^-----
   |         |      |
   |         |      move out of `b` occurs here
   |         returning this value requires that `b` is borrowed for `'a`

Rust playground
Comment: Why would every struct field need a separate (and same) lifetime declaration, when every struct already has a lifetime declaration?
Comment: @9000 because without life time you cannot contain a reference no?
Comment: What you're trying to do is impossible in safe Rust, since `D` is a self-referential struct. It'd probably be better to rethink the design to replace at least some of the references with owned values.
Answer: Actually this seems to do the trick...
struct A
{
}

struct B<'a>
{
    pub a : &'a A
}

struct C<'a, 'b>
{
    pub b : &'b B<'a>
}

struct D<'a, 'b>
{
    a : &'a A,

    b : B<'a>,

    c : Option<C<'a, 'b>>
}

impl<'a, 'b> D<'a, 'b>
{
    pub fn new(_a:&'a A) -> D<'a, 'b>
    {
        let _b = B{ a : _a };
        D
        {
            a : _a,
            b : _b,
            c : None,
        }
    }

    pub fn calc(&'b mut self)
    {
        self.c = Some( C{ b : &self.b } );
    }
}

fn test()
{
    let a = A{};
    let mut d = D::new(&a);
    d.calc();
}


Listbox not completely vanishing on hide

Question: I've got a simple method that does this:
private void searchButton_Click(object sender, EventArgs e)
    {
        searchResultsBox.Hide();
        doSomething();
    }

searchResultsBox is a listbox, and when I call its Hide method, it doesn't actually completely vanish until 'doSomething' finishes processing. It kind of leaves artifacts (in fact you can still see any part of the box that had an empty form surface behind it.
If I comment out 'doSomething', it vanishes promptly.
Any ideas on how to fix this? It's just a bit ugly.
Answer: You could try calling this.refresh() after calling searchResultsBox.Hide();
Comment: Bingo. I couldn't find a Refresh method on the form object so I gave up looking. Thanks for that.
Comment: No prob, as the guys pointed out below - refresh is useful for fixing a quick stall in the GUI thread but if doSomething() could take a lot of time, look into putting it into a separate thread.
Answer: You should not do significant work in the GUI event thread, as it will cause the UI to freeze up while it is busy running your event handling code. It is a good practice to do any long-running tasks in another thread, either by signaling another already-running thread to do the work or by starting a new thread on the spot.
new Thread(new ThreadStart(doSomething)).Start();

Comment: Agreed, but the behaviour is still detectable with as little as a 50ms wait time.
Answer: Sound like doSomething is process intensive and blocking the GUI thread, not sure why it would not finishing hiding the list before executing doSomething.
I would try putting doSomething in to a separate thread.
Comment: You could simply run it in another thread, thereby negating the need to update controls... or if you mean, changes them, then you can use Invoke() to pass control back to the GUI thread to change things.
Comment: doSomething only takes a second or so to run, but it updates GUI controls so it can't be in another thread sadly. You're right though - it's weird behaviour.
Answer: The separate thread or background worker process is the best answer.  You can also try calling Application.DoEvents().  That seems to work at times for this specific issue although I'm not in favor of using that call often.


Is it possible to create a view to show a field from a user acc and content?

Question: when i create a view in Drupal7 i have to choose what i want to display ( like Users, Content, Terms ... ) .
Is it possible to choose Users and Content?
My problem is:
I have a geofield field in the User Account and in 2 content types. I need a view where i can display this field from all Nodes and Users in one view.
Has someone a trick or a solution for this? I can't find anything about this...
Thanks Flo
Comment: possible duplicate of [Merge two drupal views with different base types ('user' and 'node')](http://drupal.stackexchange.com/questions/15180/merge-two-drupal-views-with-different-base-types-user-and-node)
Answer: To do that you need to link the user account some how to content which i assume could be possible using  $node_author, you also need to connect both the contents with each other using reference field.
In drupal view you can use Relationships tab which available above the Arguments in the center colum of the view add/edit form. To learn about Using View's relationship pleases refer to How To: Using View's Relationships


$k\geq3$ , $np \rightarrow \infty$ show that w.h.p $G_{n,p}$ contains a copy of the k-cycle $Ck$

Question: I had been given this questions:
Suppose that $k\geq3$ is constant and that ($np \rightarrow \infty$).
show that with high probability $G_{n,p}$ contains a copy of the k-cycle $Ck$
The questions is from the book 'Intro to random graphs', but theres no solution, and i have no clue..
Answer: Use the second moment method.
Let $X$ be the number of copies of $C_k$ in a random graph with distribution $G_{n,p}$.  You want to show that $\mathbb{P}(X = 0) \to 0$ as $n \to \infty$.
Chebyshev's inequality implies that if $X$ is a nonnegative random variable with finite mean and nonzero variance, then
$$\mathbb{P}(X = 0) \leq \mathbb{P}\bigl(|X - \mathbb{E}X| \geq \mathbb{E}(X)\bigr) \leq \frac{\operatorname{Var} X}{(\mathbb{E}X)^2}.$$
So, you want to show that $\operatorname{Var} X$ is much smaller than $(\mathbb{E}X)^2$.
N.B.: $\operatorname{Var} X = \mathbb{E}X^2 - (\mathbb{E}X)^2$.  In this case, to compute $\mathbb{E}X^2$, it helps to compute the expected number of pairs of distinct copies of $C_k$, which is $\mathbb{E}X(X - 1) = \mathbb{E}X^2 - \mathbb{E}X$.


Trying to perform subspace iteration by applying a matrix $A\in\mathbb{R}^3$ repeately to a matrix $S$, but its not working?

Question: I am trying to perform subspace iteration in MatLab but I am not getting the results I expected.
Let the matrices $A$ and $S$ be given by
$$
A =
\begin{pmatrix}
5 & 0 & 0 \\
0 & 3 & 0 \\
0 & 0 & 2
\end{pmatrix},
\quad
S =
\begin{pmatrix}
3 & 4 & 6 \\
9 & 5 & 2 \\
0 & 0 & 0
\end{pmatrix}.
$$
$A$ clearly has the eigenvalues $5, 3$, and $2$, and $S$ defines a subspace of dimension $k = 2$. I then assumed that repeated application of $A$ to $S$, followed by normalization, should 'push' the subspace represented by $S$ to the subspace given by the 2 dominant eigenvectors (the ones associated with eigenvalues $5$ and $3$) of $A$. I would have expected to end up with a matrix very close to the following matrix $M$, after performing many iterations:
$$
M = A^k S =
\begin{pmatrix}
1 & 0 & 0 \\
0 & 0.6 & 0 \\
0 & 0 & 0
\end{pmatrix},
$$
as $k$ becomes large.
However, when I perform this iterative process in MatLab I end up with a one-dimensional matrix
$$
\hat{M} \approx
\begin{pmatrix}
0.38 & 0.51 & 0.76 \\
0 & 0 & 0 \\
0 & 0 & 0
\end{pmatrix}.
$$
I thought iteration with the matrix $A$ should take matrix $S$ to the $2$ dominant eigenvectors of $A$. So why hasn't it?
Edit
Here is my code:
A = [ 5, 0, 0 ; 0, 3, 0; 0, 0, 2 ];
S = [ 3, 4, 6; 9, 5, 2;, 0, 0, 0];

jMax = 20;
for j=1:jMax
    S = A*S/norm(A*S);
    disp(S);
end

Comment: You will need to normalize anisotropically so that you scale up the 0.6 or it will diminish exponentially compared to the 1 eigenvalue.
Comment: What do you mean when you write that "$S$ defines a subspace of dimension $k=2$"? What is normalization in this context?
Comment: No, normalization for dimensions greater than 1 should involve something like the QR decomposition, `S,R=qr(A*S)`. Then $S_kR_kR_{k-1}…R_1=A^kS_0$, so $S_k$ is an orthonormal basis of the space spanned by the rows of $A^kS_0$.
Comment: I edited my post to include the code I used. Is my normalization incorrect?
Answer: Normalization for dimensions greater than $1$ requires to find a basis with some fixed properties like orthonormality for the subspace in each step. This can be achieved by the QR decomposition,
[S,R]=qr(A*S).

Then
$$
S_kR_kR_{k−1}…R_1=A^kS_0,
$$
so $S_k$ is an orthonormal basis of the space spanned by the rows of $M_k=A^kS_0$.
Executed (here in scilab) it results in the expected relatively slow linear convergence towards a diagonal matrix with a factor of $0.6$ or $1$ digit per $4.5$ steps in the off-diagonal elements.
for J=1:20
    [S,R] = qr(A*S); S
end

.
 S  =
  - 0.4856429  - 0.8741573    0.
  - 0.8741573    0.4856429    0.
    0.           0.           1.
 S  =
  - 0.6794080  - 0.7337607    0.
  - 0.7337607    0.6794080    0.
    0.           0.           1.
...

 S  =
  - 0.9999996  - 0.0008463    0.
  - 0.0008463    0.9999996    0.
    0.           0.           1.
 S  =
  - 0.9999999  - 0.0005078    0.
  - 0.0005078    0.9999999    0.
    0.           0.           1.
 S  =
  - 1.0000000  - 0.0003047    0.
  - 0.0003047    1.0000000    0.
    0.           0.           1.
...


Hidden Markov model MS GARCH

Question: I am currently working on the MS GARCH model proposed by Haas paper given below
$\epsilon_n=Z_n \sigma_{\Delta_n,n}$
where $\epsilon_n$ is a time-series of residuals, $\left\{Z_n ,n\in \mathbb{Z}\right\}$ is a sequence of normal independent and identically distributed random variables with mean zero and unit variance, and $\left\{ \Delta_n,n\in \mathbb{Z}\right\}$ is a Markov chain.
The $k \times 1$ vector $\boldsymbol{\sigma}_n^2=[\sigma_{1n}^2,\sigma_{2n}^2,\ldots,\sigma_{kn}^2]'$ of regime variances follows the multivariate GARCH(1,1) equation
\begin{equation}  \label{2.2}
\boldsymbol{\sigma}_n^2=\boldsymbol{\alpha_0}+\boldsymbol{\alpha_1}\epsilon_{n-1}^2+\boldsymbol{\beta}\boldsymbol{\sigma}_{n-1}^2\,,
\end{equation}
where $\boldsymbol{\alpha_i}=[\alpha_{i1},\alpha_{i2},\ldots,\alpha_{ik}]'$, $i=0,1$; $\boldsymbol{\beta}=diag(\beta_1,\beta_2,\ldots,\beta_k)$.
Now I am trying to link the underlying latent Markov chain to the theory of hiddem markov models. In the theory of HMM I am finding that the observations sequence should be independent. In my case the observation sequence is the residuals $\epsilon_n$ which even though they are uncorrelated, they are not independent.
Can this assumption of independence be eliminated in some way? Or am I making some mistake by joining HMM and MS GARCH?
Comment: you haven't described what $\sigma_{\Delta_n,n}$ is
Comment: Yes, it is the square root of one of the elements of the vector $\boldsymbol{\sigma}_n$. We have k elements which can take the value of $\sigma_{\Delta_n,n}$, and it is chosen from these k elements depending on which regime we are in at time $n$.
Comment: okay, I understand now
Answer:
In the theory of HMM I am finding that the observations sequence
  should be independent.

Typically for HMMs, conditioning on the states, the observations are conditionally independent. In the case of your model, it is not true, as
$$
p(\epsilon_1, \ldots, \epsilon_n \mid \Delta_1, \ldots, \Delta_n) \neq p(\epsilon_1 \mid \Delta_1) \times \cdots \times p(\epsilon_n \mid \Delta_n).
$$
For your model, the distribution of $\epsilon_t$ depends on the previous values, as well as the contemporaneous hidden state. So this isn't a typical example of a HMM, although I wouldn't object to it being called that.

Can this assumption of independence be eliminated in some way?

If you changed the GARCH part of your model to an ARCH part, and if you treated the $\sigma^2_t$ process as being part of the state, there would be conditional independence. The $k+1 \times 1$ state vector could be
$$
\left[ \begin{array}{c}
\Delta_t \\
\boldsymbol{\sigma}_t^2
\end{array}\right].
$$
This would give you a latent first-order Markov process, although its state space is not finite, which is another typical assumption of what are called Hidden Markov Models. Also note that the $\boldsymbol{\sigma}_t^2$ is totally deterministic, which isn't typical either, for these sorts of models.
Comment: I do not understand why removing the GARCH part helps, since actually there is still the dependence on $\epsilon_{n-1}$ which depends on the regime at time $n-1$. and what do you mean treat the $\sigma_t^2$ as being part of the state?
Comment: @Anna see my edits. Overall I'd say if you're interested in specifically this model, it won't help much in the short run to go exploring HMMs thinking they're somehow related.

Hidden Markov model MS GARCH


VAR model: include all lags up to AIC-suggested order or just the significant ones?

Question: I'm building a regression model in which I have a dependent variable OSE, and two independent variables, MSCI and Brent.
In this model I wish to include lagged variables. I performed an AIC for my model: I ran a VAR lag-order selection pre-estimation with all the three as dependent variables. It tells me the optimal lag for the model is 2.
Does this mean I should include all the lag levels of the variables to my regression, or just keep the significant ones?
Comment: *I performed AIC for my model* sounds weird, but I did not dear to rephrase it when editing.
Comment: I was going through my old answers and noticed this one was not accepted. Do you perhaps need further clarification?
Answer: I suppose AIC corresponds to the model with full lags rather than just the significant ones (correct me if I am wrong), so what it is telling you directly regards models with full lags. Whether kicking out the insignificant ones will improve the model is an empirical question. Note that you can also obtain AIC for the model once you have removed the insignificant lags. Then you can see whether removing those lags worked in terms of AIC reduction.
Generally, AIC is useful, but it does not perform well if you consider a very large pool of models. See e.g. Hansen "A winner's curse for econometric models: on the joint distribution of in-sample fit and out-of-sample fit and its implications for model selection" (2010).
Comment: AIC just tells how many not the lag length. Any subset of lagged variables could be searched.
Comment: Agree with the second sentence, cannot quite follow the first sentence.


Generate QQ plot for sets of different size

Question: I'm coming from this question Similarity between two sets of random values (which still stands BTW) where @whuber suggested in the comments that I use a Q-Q plot to assess the similarity of two discrete distributions.
To recapitulate, I have two sets of random floats between [0,1] of different sizes:
$$A = \{0.3637852, 0.2330702, 0.1683102, 0.2127219, 0.0152532, ..., N_A\}$$
$$B = \{0.4541056, 0.7521812, 0.0266602, 0.5099002, 0.3468181, ..., N_B\}$$
where $N_B > N_A$.
and I need to generate the Q-Q plot for thess sets. For what I've read, if the sets where of equal sizes ($N_B = N_A$) I would simply sort both sets from minor to major values and then plot one against the other in a 1:1 correspondence.
My sets are different in sizes and the sources I've found [1], [2] both say that I need to sort both sets and then interpolate the larger set ($B$ in my case). This is counter-intuitive to me since I would expect to have to generate more points from the smaller $A$ set (through interpolation) so as to be able to plot this expanded set $A'$ against the $B$ set.
So obviously I'm not understanding correctly the process. What are the steps I should follow to generate a Q-Q plot for two distributions like the ones I presented above?
Comment: Most full-featured stats software does this with a single command.  What software are you using?
Comment: Actually, source 1 says the larger set is interpolated, not that you have to interpolate it. Confusing wording. But they mean to interpolate the larger set into the smaller. It would be easier to think of forming quantiles of each set and then plotting those.
Comment: I _could_ use R but I would prefer the steps outlined separately so I can implement it in python.
Answer: Generate some data:
 A <- rgamma(50,4,.1)
 B <- rnorm(30,40,20)

And then:
 plot(sort(B),sort(quantile(A,probs=ppoints(B))))

Here I interpolated the larger set (that is, estimated 30 quantiles from 50 points); you can do the same to "interpolate" the smaller set but I don't think that helps at all, since the extra 'information' is really just a function of your quantile interpolation function.
That looks like this:

Here they are both plotted together (with the second plot above now having X and Y swapped so they both have the same variable on the same axis); the greater number of points has been plotted with the smaller, red circles. I think there's not really any additional information of any real value in the plot with more points, but you are free to disagree:

So in short, look at ?quantile and ?ppoints to see what's going on.
edit: sorry, I just noticed you have $N_B>N_A$. Mine is the other way around. I assume you can interchange the roles of A and B.
By the way, you can easily avoid sorting the sets, it's just that ppoints doesn't return things in the same order as its argument and I was being lazy.
If you define alpha=.5 then quantile(A,probs=(rank(B)-alpha)/(length(B)+1-2*alpha)) should reproduce the above plot without calling sort on either argument to plot.
(personally, I prefer values nearer alpha=.375 but not so much that I would bother fiddling with the ppoints default in most cases)
That should be enough detail that you can implement it in Python, I think.
Comment: I just saw your post there; I'm sorry of not thinking to just point you to the code for ppoints itself, but I wasn't thinking you would want to reproduce its behavior exactly (just the concept underlying it, which was the purpose of `quantile(A,probs=(rank(B)-alpha)/(length(B)+1-2*alpha))` in my third-last paragraph there). Anyway I am glad you are happy with the outcome.
Comment: Thanks again Glen, I've managed to implement this in python thanks to your thorough description. Cheers.


Como mapear todas as requisições para um único arquivo?

Question: Preciso mapear todas as requisições que chegam ao servidor da seguinte forma:
exemplo.com/joao  =>  exemplo.com/index.pl?u=joao
exemplo.com/joao/ =>  exemplo.com/index.pl?u=joao

Meu arquivo /var/www/.htaccess está assim até o momento:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9\_\-]+)\/?$ index.pl?u=$1

Em casos normais a regra funciona. Porém falha no caso de o diretório /var/www/joao existir.
Eu preciso que a URL seja transformada mesmo que o diretório joao exista. Alguém tem alguma ideia?
Answer: Muito bom.
agora eu tenho um servidor web e outro servidor de aplicativos rodando jboss. minhas requisições passam pelo servidor web. queria fazer a url amigável mas ta dando erro


How can I order these bars using ggplot? Why is the forcat method not working?

Question: I'm trying to reorder the bars on my bargraph so they are biggest to smallest, ordered by log(Max_N) rather than alphabetically. I've tried using forcats but it brings up an error message. This is my code so far, whats going wrong? I'm trying to teach myself how to use ggplot, so please do point out any errors I've made, because I am self-taught!
library("ggplot2")
library (forcats)
test<-ggplot(all, aes(x=all$Species, y=log(all$Max_N+1))) +
geom_bar(stat = "identity") +
coord_flip()

test <- test + labs(title = "",
              subtitle = "",
              caption = "",
              y = "Log(MaxN)", x = "Species",
              tag = "")
test %>%
  mutate(name = fct_reorder(Species, log(Max_N+1)) %>%

Original plot
a) Here's the reproducible example requested (I hope that's what you mean?)
 structure(list(Site = c("Mylor", "Mylor", "Mylor", "Mylor", "Mylor",
 "Mylor", "Mylor", "Mylor", "Mylor", "Mylor"), Trial = c(1L, 1L,
 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), Location = c("centre", "edge",
 "edge", "edge", "edge", "edge", "edge", "centre", "centre", "centre"
 ), Bait = c("whitefish", "whitefish", "whitefish", "whitefish",
 "whitefish", "whitefish", "whitefish", "whitefish", "whitefish",
 "whitefish"), ECP = c("yes", "yes", "yes", "yes", "yes", "yes",
 "yes", "no", "no", "no"), SSP = c("no", "no", "no", "no", "no",
 "no", "no", "no", "no", "no"), KP = c("no", "no", "no", "no",
 "no", "no", "no", "no", "no", "no"), OSP = c("no", "no", "no",
 "no", "no", "no", "no", "no", "no", "no"), Density =
 c("dense_seagrass",
  "dense_seagrass", "dense_seagrass", "dense_seagrass",
 "dense_seagrass",
 "dense_seagrass", "dense_seagrass", "dense_seagrass",
 "dense_seagrass",
 "dense_seagrass"), Viz = c(1.75, 1.75, 1.75, 1.75, 1.75, 1.75,
 1.75, 4.5, 4.5, 4.5), Species = c("sea_sprat", "corkwing_wrasse",
 "pollack", "sand_smelt", "unknown_wrasse", "two_spotted_goby",
 "unknown_wrasse", "mackerel", "sand_smelt", "mullet"), AJ = c("juv",
 "juv", "juv", "adu", "adu", "adu", "adu", "adu", "adu", "adu"
 ), FG = c("pelagic_neritic", "reef_associated", "pelagic_neritic",
 "pelagic_neritic", "reef_associated", "reef_associated",
 "reef_associated",
 "pelagic_neritic", "pelagic_neritic", "pelagic_neritic"), Max_N =
 c(1L,
 1L, 2L, 2L, 2L, 2L, 1L, 1L, 26L, 1L)), row.names = c(NA, 10L), class
 = "data.frame")

b) so I changed the Species to name as suggested, and it has order some but not others? Changed code to this.
 test<-ggplot(all2, aes(x=name, y=log(Max_N+1))) +
  geom_bar(stat = "identity") +
  coord_flip()

plot after changing code to above
Comment: Hm. In that case we need a reproducible example including a snippet of your data or some fake data. To this end have a look at how to make  a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). To share your data, you could type `dput(NAME_OF_DATASET)` into the console and copy the output starting with `structure(....` into your post.  If your dataset has a lot of observations you could do e.g. `dput(head(NAME_OF_DATASET, 10))` for the first ten rows of data.
Comment: `mutate` will not work on a ggplot object. Reorder the column before passing it to ggplot, i.e. do `all <- all %>% mutate(name = fct_reorder(Species, log(Max_N+1))`. Additionally, don't use `all$...` inside aes. Simply do `aes(x = Species, y=log(Max_N+1))`.
Comment: Without your code and graph it's hard to say. But I'd guess that you forget to change the `aes(x = )` from `Species` to `name` (if you saved the `fct_reorder` result to the `name` column)
Comment: @stefan I have now tried this and run the code, but the same result still comes up. I cleared the environment and did it again to the same end.  Any suggestions?
Answer: Acutally if I were you, I will just have a reorder inside ggplot(aes()), then you don't need to change anything in your data.
If you want to plot this bar chart that sum up all Max_N within a species, you can do a group_by and summarise before piping into ggplot. This will NOT change your original all dataframe.
library(tidyverse)

all %>% group_by(Species) %>% summarize(Max_N = sum(Max_N)) %>%
  ggplot(all, aes(x = reorder(Species, Max_N), y =log(Max_N+1))) +
  geom_bar(stat = "identity") +
  coord_flip() + labs(x = "Species", y = "Log(MaxN)")

Comment: Thank you so much for all your help, but I've just tried this too and for some reason it changes the order, but not by MaxN. Similar to how Unknown Wrasse hasn't followed the pattern. The data has duplicates for all species as these are recorded for each separate trial.
Comment: See if my edited answer helps :)


why read is faster when using O_DIRECT flag?

Question: I copied a 10GB of file in my SSD which has read bandwidth of around 3.3GB/s, benchmarked using fio command. Here is the ref: https://cloud.google.com/compute/docs/disks/benchmarking-pd-performance
I cleared out the cache using this "sync; echo 3 > /proc/sys/vm/drop_caches". After that I tried to read the file in small chunks of 3MB every time using system calls open() and read(). If I open the file without O_DIRECT and O_SYNC it gives me a bandwidth of around 1.2GB/s. However, If I use O_DIRECT and O_SYNC it gives me a bandwidth of around 3GB/s. Clearing the cache both times even O_DIRECT doesn't really use the page cache.
My question is why O_DIRECT is giving normal IO bandwidth and without O_DIRECT I cant get it. As the data going from IO to the page cache has bandwidth of 3.3GB/s and from page cache to user buffer is around 7GB/s i suppose. This pipeline should also give normal 3.3GB/s. Why it is slower?
I am always reading a new 3MB every time. I am not reusing the data so cache is not really useful. But the pipeline should be bound by IO why it is not?
CPU is Intel(R) Xeon(R) Silver 4214 CPU @ 2.20GHz. I am not sure about the DRAM speed. But the thing is if i re-read the same 3MB multiple times then i get ~8GB/s bandwidth. Which should be the DRAM bandwidth i suppose. Because linux can use all of the free RAM as page cache.
Update
I tried the fio command with and without O_DIRECT enabled in it and logged the iostat.
Used this fio command.
"fio --name=read_throughput --directory=$TEST_DIR --numjobs=1 --size=10G --time_based --runtime=30s --ramp_time=0s --ioengine=sync --direct=0 --verify=0 --bs=4K --iodepth=1 --rw=read --group_reporting=1 --iodepth_batch_submit=64 --iodepth_batch_complete_max=64"
Used this iostat.
"iostat -j ID nvme0c0n1 -x 1"
I had the following conclusion, a single threaded read without O_DIRECT flag is not able to saturate the SSD with enough read requests to achieve 3.3GB/s irrespective of the block size being used. However, with O_DIRECT falg a single threaded read is able to saturate the device when block size is 64M or higher. At 3M it is around 2.7GB/s.
Now the question is why without O_DIRECT flag, CPU is not able to send enough read requests to SSD why it is limiting them? Does it has to do with cache management limitation? If yes, which parameter is limiting it? Can I change it and see does it affect amount of read requests being sent to the device?
Comment: i just need to understand why it is happening.
Comment: As a guy who does a lot of benchmarking for work, I would submit that this question does belong here. Much of what determines these behaviors is very hardware/server specific. How was the I/O dye configured? What drives are being run? How are the PCIe lanes configured? For these reasons I would submit that the question, at least to me, makes sense in serverfault. If the OP asked, how do I "optimize JavaScript async calls" for example - agreed, no hardware factors - give it to SO.
Comment: if you need support for writing an application, stackoverflow.com is a better source in this due specifically for programming
Comment: I would rather migrate this to the Unix & Linux Stack Exchange.
Answer: O_DIRECT is faster than a generic read because it bypasses the operating system's buffers. You are reading directly from the drive. There are a couple of reasons this could be faster though keep in mind at this level things get insanely setup specific. Example of what I mean by setup specific factors: if you have a drive that is optimized for 8kB writes inside the NAND vs 4kB chunks and you write/read at the wrong size you'll see half performance but this requires you to have an internal understanding of how drives work. This can even vary within the same model - ex: the A model of a drive might have different optimizations than the same B model of the drive (I have seen this multiple times in the field)
But back to your question:

No cache to have to copy in and out of
If you're doing something like FIO you'll get more predictable read behavior
1MB is a large block size so you'll benefit extra from not dealing with the cache

Beyond that you have to start getting deeper into benchmarking and that's a pretty complex topic.
My general recommendation is to start with io_stat. Is avgqu-sz high? Is util close to 100%, it probably will be if you're close to the drive's max capacity. Is await long? Do you have RAID? What scheduling algorithm did you pick? The list of things I've seen cause these sorts of things are myriad and figuring out exactly what causes which behavior is going to be very unique to your specific system.
What I said in the beginning though may get you in the ballpark. Best guess is that if you are doing big block reads you're getting savings regarding some sort of cache inefficiency.
Comment: Posting a thread of comments. Not sure how to respond on the answer.

I used fio and changed the parameters against which i am trying to understand the behaviour. Here is the command
"fio --name=read_throughput --directory=$TEST_DIR --numjobs=1 --size=10G --time_based --runtime=30s --ramp_time=0s --ioengine=sync --direct=0 --verify=0 --bs=1M --iodepth=1 --rw=read --group_reporting=1 --iodepth_batch_submit=64 --iodepth_batch_complete_max=64"
Comment: I disabled the O_DIRECT, engine is sync which is normal read write, depth is 1 and numjobs is also 1. Initially this would give 1.3GB/s when it is actually sending read requests to disk and after that it goes to 6~7GB/s and then it is no longer sending any I/O requests.

here is the iostat when the read requests were being sent and bandwidth was 1.3GB/s.
r/s = 10799
rKB/s = 1382272
r_await = 0.2
rareq-sz = 128
svctm = 0.09
%util = 100
Comment: rest of the parameters were all 0. Checked using this command "iostat -j ID nvme0c0n1 -x 1"
But why it is 1.3GB/s not 3.3GB/s in this case? If i only enable O_DIRECT with the same command the bandwidth is 1.7GB/s. Which is a bit faster but now is not near normal I/O.
However, if I change the numjobs to 4. Both of them starts at 3.3GB/s and maintain it when the reads are being requested from the disk.
iostats are like  this
r/s = 26139
rKB/s = 3345792
r_await = 0.43
rareq-sz = 128
svctm = 0.04
%util = 100
Comment: Why is this behaviour like this? Essentially the "svctm" decreases for a 128KB of avg. size. Why it got decreased? The 128KB size serviced in 40us is 3.3GB/s contrary to 90us which is 1.45GB/s. As per this "https://unix.stackexchange.com/questions/104192/iostat-await-vs-svctm"
"The svctm column (service time) should display the average time spent servicing the request, i.e. the time spent "outside" the OS." Why this svctm changes
Comment: Q1: Why with or without O_DIRECT and numjob = 1 the bandwidth is not 3.3GB/s?
Q2: What causes the difference between 1.3GB/s and 1.7GB/s? Like what is happening extra in the process that it is 1.3 not 1.7?
Q3: Why it is normal I/O bandwidth if the numjobs = 4?
Comment: Some insight that i can think of is. When the numjobs=4. Some part of process gets overlapped with other and that time gets hidden and the overall bandwidth seems to be 3.3GB/s. Otherwise it is sequential and is added in that 3.3GB/s bandwidth making it slower. But what that is?
Comment: There is no RAID in the system that i am testing on
Comment: Ok. I did some more testing. So, increasing the block size of the read from 1M to 64M or higher with O_DIRECT can saturate the read requests for the SSD and can achieve 3.3GB/s with numjobs=1. But it is unable to send enough read requests to SSD without O_DIRECT flag. So, that it can saturate the device. Why without O_DIRECT CPU is not able to saturate the read requests even if the bs = 64M or higher?
Comment: hahaha ok - I'll read through this tomorrow but the accepted way to do this is take all these comments - copy pasta them into your OP, and just put them under a section called `## Update` or someithng.


Making sense of 5/4 time signatures

Question: Normally, we're told that 5/4 is usually 3/4 + 2/4 or 2/4 + 3/4. (At the very least, it's unusual to have a meter that large without "secondary stress" beats.) However, how do we make sense of the metrical pattern when the two rhythms are pitted against one another?
For instance, consider the following (reduced) excerpt from George Dyson's Quo Vadis:

The first bar is clearly 3/4 + 2/4—or would be if the tempo weren't so slow (it's about quarter note = 56). The second bar, however, puts the stress on the third beat in the men's voices but on the fourth beat in the women's voices. And in the third bar, the voices suggest a 2/4 + 3/4, but the accompaniment seems to be in a 3/4 + 2/4 pattern. Plus, the aforementioned slow pulse seems to wash away any real sense of an overall rhythmic organization.
So how do we analyze such a pattern to make sense of it?
Comment: If you are wondering how it would be directed, I'd guess it would be by directing the text, not the meter at this point. It's slow enough the director can subdivide the beat, and you have two hands to help with crossing. Only after the piano comes in would I expect it to be directed metrically, and the beats would still be (possibly subtly) subdivided due to the slow tempo and constant use of eight notes. And, even then, the soprano part would probably still have the text conducted, since it's the most different.
Answer:
Normally, we're told that 5/4 is really 3/4 + 2/4 or 2/4 + 3/4.

Well, I have to ask "told by who?" It is not the case that 5/4 has to be interpreted as either 3/4 + 2/4 or 2/4 + 3/4. It is perfectly valid to use groups of 5 crotchet beats as the overall rhythmic template of a piece of music, without having to have the same sub-groupings in different parts.
In fact, you suggest an answer in your question; the rhythmic complexity of the contrapuntal texture (particularly at this slow tempo), washes "away any real sense of an overall rhythmic organisation." Therefore, we do not need to interpret the music as having any accented groupings within the 5/4 time signature. However, I suspect the 5/4 time signature is still useful; it looks likely from your excerpt, that the piano part may more strongly emphasise 5/4.
If you are planning to conduct this piece, though, it does make sense to find the best grouping for each bar (either 2+3 or 3+2, as you have already done with the first few bars). But, in this kind of music, it is not always likely to follow the natural rhythmic stresses or rhythmic groupings in all of the parts.
Comment: What @BobBroadley said. It's worth pointing out that none of this is specific to a particular type of meter. Subdivision of the meter in a recurring pattern of strong and weak beats is not a property of the meter itself - rather the pattern is something that emerges from the music as it sounds, and the attached manner of counting the measures is merely a tool to help the performer navigate the piece. As a piece consists of more independent melodic lines, there is less of a change to find a recurring pattern.
Comment: @aeismail " Is it "strong-weak-weak-weak-weak" or something else?". Sometimes! I'm sure you'll hear that 'interpretation' in the following's main riff: https://www.youtube.com/watch?v=u-224agX0cA
Comment: Who says this? Conductors of amateur choirs, music teachers (before college), and so on. But how would we interpret this 5/4 then? Is it "strong-weak-weak-weak-weak" or something else? (Also, I've edited the question accordingly.)
Comment: Hi there, I added to my answer - you have hit upon the answer already - this is NOT strongly rhythmic music, so you don't need to try to "hear" either a 2+3 or 3+2 grouping. However, I suspect that a stronger 2+3 or 3+2 might be suggested by the piano accompaniment in the following bars - what do you think…?
Answer: I'm wondering if the 5 was considered a 'common denominator' by the composer, or such like. Often, when just reading particular words to a song, emphases and a natural rhythm will be apparent.Reading the phrase out loud gives various different rhythms, and the composer has taken some of these to make certain words more stressed. However, he's also put the phrase in other voices so that the stresses are 'unnatural'.The first bar, for example, could have been written for the bass voice as 4/4 starting with 'They'.That could put the tenor also in 4/4 starting on an anacrucis.
It could have been written is a Stravinsky sort of way, in whatever time sig. but using the '<' sign over emphasised notes.Or - it could have been written with the sig. changing in each bar, but that would complicate other voices' writing. We need a count of some sort, and the composer elected for 5 to incorporate all the parts. But as it's very slow (apparently), it could even be counted in 1s, especially as each part has what appears to be its own rhythm. Readers would not want it written that way, though.Time signatures are a Man-made phenomenon, which obviously usually reflect the intrinsic rhythm of what is written, either naturally or what the composer has decided. The two may not align, as I feel in this case.
The term 'pattern' is used in the question. A pattern is something that repeats uniformly.This doesn't seem to.
Answer: The excerpt shown is composed and performed in a consistent 3+2 meter.
In the score
Bar 2
Although the tenor and bass sing stressed syllables on beat 3, there are other elements working against this being a point of emphasis within the measure.

The presence of a descending line tends to draw emphasis away, particularly when set against an ascending line, and then especially when it's the higher voices ascending.
Three separate syllables are being sung on beat 3; whereas, on beat 4, there is a concordance on "home", already established in the previous bar as a moment of emphasis, and here presented at the highest pitches within the measure in two voices.

Bar 3
Notationally, the Alto, Tenor, and Bass look like they could be 2+3, given the onset of the half-note on beat 3. However, other aspects of the score suggest 3+2:

The onset of beat 3 in the Alto, Tenor, and Bass occurs with the unstressed syllable "-dour" from "SPLEN-dour".
The accompaniment descending figure lasts three beats, with a two-beat ascending figure starting on beat 4.

Here is my re-reduction of the score to emphasize the above two elements.
<code>X:1
T:Quo Vadis
T:IX: To Find the Western Path
C:Sir George Dyson
M:5/4
L:1/8
K:C major
%%score [S A T B] {RH | (LH1 LH2)}
V:S name=Soprano
V:A name=Alto
V:T name=Tenor clef=treble-8
V:B name=Bass  clef=bass
V:RH
V:LH1          clef=bass stem=up
V:LH2          clef=bass stem=down
[V:S] z10 | GA _B c2 d e2 d2- | dc c _B2 G-G2 z2 |
w:They in-her-it a HOME | _ of _ splen-dour |
[V:A] z4 z2 EF G2- | GF G2 A_B c2 BA | A G2 F E4 z2 |
w:They in-her- _ _ _ it a HOME _ of | SPLEN- _ _ dour
[V:T] GA _B c2 d e4 | d2 c2 _B3 c d2 | d e2 d c4 z2 |
w:They in-her-it a HOME | of un-fa- _ ding | SPLEN- _ _ dour
[V:B] z2 G,2 A,_B, C4 | _B,2 A,2 G,3 A, B,2 | _B,2 A,G, G,4 z2 |
w:They in-_HER-|it a home _ of | SPLEN- __ dour
[V:RH] z10 | z10 | [FAdf][EGce] [DF_Bd][CEAc] [_B,DGB][G,CEG] "_>"[G,B,DG][A,CEA] [B,DFB][CEGc] |
[V:LH1] z10 | z10 | z2 [E,G,_B,]4 z2 [E,G,C]2 |
[V:LH2] x10 | x10 | [C,,C,]4 [D,,D,]2 "_>"[_B,,,_B,,]4 |
</code>
In the recording
The only recording of the piece listed by the Dyson Trust (as of October 10, 2020) is on the Chandos label: Dyson: Quo Vadis, 2002, CHAN10061. The measures in question, on Disc 2 Track 4, run from approximately 16:31 to 16:50. The recording can be heard on Spotify with a membership.
Bar 2
Although the Tenor and Bass can be heard clearly on beat 3, the Soprano and Alto clearly provide the apex of the measure on beat 4.
Bar 3
The solo quartet (whose parts are not shown in the reduction) on beats 4 and 5 sings a crescendo-ing "-fad-ing", while the choir (whose parts are shown) sings "splendour" on beats 1-3 as a decrescendo to make way for the quartet's emergence on beat 4.

Making sense of 5/4 time signatures


Irreducibility of $x^2 + 1$ in $\Bbb F_p$

Question: I can show that in field formed by roots of $x^{4 \cdot 2^n + 1} - x$, the polynomial $x^2 + 1$ factors into linear factors. This gives $p = 4 \cdot 2^n+1\equiv 1 \pmod 4$. But how if $p \equiv 3 \pmod 4$, $x^2 + 1$ is irreducible in $\Bbb F_p$?
So far, I think if $x^2 + 1$ is irreducible in $\Bbb F_p$ then $x(x^p-1)$ should not contain a factor $x^2 + 1$. Any value other than $p=4n+1$ does not give this factor. But why $p \equiv 3 \pmod 4$ in particular? Why not $p \equiv 0 \pmod 4$ or $p \equiv 2 \pmod 4$?
Here it is done in example 1.0.3.

Workout: I was too stupid to realize that $p$ was prime.
  No primes have the form $p = 4n$ or $p = 4n+2 $
Comment: Hint: look at the group $\Bbb F_p^*$ of units of $F_p$. This group is a cyclic group of $p - 1$ elements; say it is generated by $\alpha$. Because $-1$ has order $2$ (except if $p = 2$; that's a separate case), it must be equal to $\alpha^{(p-1)/2}$. Now, when is this element a square?
Comment: @Magdiragdag when $p-1 = 4n$??
Comment: Yes, indeed. And, in particular, if $p \equiv 3 \pmod 4$, it is not a square, so in that case $x^2 + 1$ does not factor into linear factors.
Comment: @Magdiragdag I got confused, by not $p \equiv 2 \pmod 4$?
Comment: $p$ is prime and if $p \equiv 2 \pmod 4$, then $p = 2$. That's a special case, since then $-1 = 1$ and $x^2 + 1 = (x + 1)^2$.
Answer: The polynomial $x^2+1$ factors into linear polynomials if the field has a fourth root of unity.
Comment: He meant a primitive 4th root of unity
Comment: The numbers $\;\pm1\;$ are fourth roots of unity in any characteristic (but in characteristic two they're the same), yet it is false the polynomial $\;x^2+1\;$ is reducible if $\;p=3\pmod 4\;$ . What is true is that the polynomial is reducible iff the field has a square root of $\;-1\;$ , which is not the same...
Comment: @user1952009 Yup, I bet he may have meant that...
Comment: My question is about for what form of $p$, the field does not have fourth root of unity. Could you please explain me how ONLY $p=4n+3$ makes $x^2+1$ irreducible in $\Bbb F_p$ BUT NOT $p=3n$ or $p=3n+2$?


JavaScript setTimeout in a For loop issue

Question: My issue is I am trying to increment the timeout time by the iteration value and time it by 1000. for example if the increment value is 5 it will be 5*1000 on the timeout.
I have tried various ways the first being ->
var textValue = 10;
function doSetTimeout(i) {
   setTimeout(function() { console.log(i); }, i * 1000);
}

for(var i = 1; i <= textValue; i++){
     doSetTimeout(i);
 }

I also tried this ->
var textValue = 10;
 for(var i = 1; i <= textValue; i++){
     (function () {
         var j = i;
         setTimeout(function timer() {
               console.log(j);
              },j*1000);
      })();
 }

All I get on both is that the timeout is always set to 1000 ms even though the variable is being set correctly each time.
Any help would be appreciated.
Comment: Possible duplicate of [Javascript, setTimeout loops?](http://stackoverflow.com/questions/22154129/javascript-settimeout-loops)
Comment: possible duplicate of http://stackoverflow.com/questions/22154129/javascript-settimeout-loops
Comment: So is the idea that starting at time 0, you want the event to fire at times 1000, 3000, 6000, 10000, 15000, and so on?
Answer: The timeout is actually the correct duration, they are just all starting at the same time because setTimeout doesn't stop the execution of the for loop.
This should be what you want:

var textValue = 10;
delayLoop(textValue);

function delayLoop(to, at) {
    var at = at || 1;
    if (at <= to) {
        setTimeout(function() {
            console.log(at);
            delayLoop(to, at + 1);
        }, 1000 * at);
    }
}
Comment: They're starting at the same time, but the timeout value is `i * 1000`, so shouldn't they fire one second apart?
Answer: You create a bunch of setTimeouts to be triggered after 1000ms, 2000ms, 3000ms, etc. The problem is that you create them all at the same time, so each timeout will come 1 second after the next. There's two ways to solve the problem.

Calculate the correct delay initially for every setTimeout.

The first one should be 1000ms. The second should be after 1000ms + 2000ms. The third should be after 1000 + 2000 + 3000. etc.
var timeoutSum = 0;
for (var i = 1000; i <= 10000; i += 1000) {
    timeoutSum += i;

    setTimeout(function() { console.log("hi!"); }, timeoutSum);
}

Don't trigger the next timeout until you've finished the current one.

We create a function to add a new timeout, and then call it from the function that gets called when the timeout ends. You can think of it as a weird inverted for loop, with the initial value outside and the condition in the middle.
var wait = 1000;

function addTimeout(wait) {
    setTimeout(function() {
        console.log('hi');

        if (wait < 10000) {
            addTimeout(wait + 1000);
        }
    }, wait);
}

addTimeout(wait);


More narrow type is not assignable to other

Question: There two types:
type ExcludeString<T = any> = Exclude<T, string>;
type ExcludeStringAndBoolean<T = any> = Exclude<T, string | boolean>;

In the code of the function
function test1<T>(p: ExcludeStringAndBoolean<T>) {
  let a: ExcludeString<T>;
  a = p;
}

tsc throws an error for line a = p
Type 'Exclude<T, string | boolean>' is not assignable to type 'Exclude<T, string>'.ts(2322)

But for the certain use it works very well:
type CertainType = string | number | boolean;

function test2(p: ExcludeStringAndBoolean<CertainType>) {
  let a: ExcludeString<CertainType>;
  a = p;
}

Why is it like this?
Comment: Interesting case. Copied the code to the TS playground out of curiosity: [link](https://www.typescriptlang.org/play/?ssl=4&ssc=1&pln=4&pc=9#code/C4TwDgpgBAogHgYwDYFcAmEDKwBOBLAOwHMAeAFSgF4oBDAkAPitkVQ3IBooBnXQohgG4AUKEgtk6LH2IBBAmgBCAe2VIIdcszqNm8SezJde+YlAA+UAEar1dIcOEZkNHNABmKAgmB5lBKGAIXgBGcgYACjAALgk2aVMieSVbDQJwgEooAG9hKCh1YFpY-XjsRPCRfJpmMBEAX0cAeiaoAFoOzq7unt6+-v7HMWgAYQgcYBpCMnBoahN+CygCFABbK3GlmzU0kU9vX39A4OAAJiiS1ily-mSVHc0xiamCGcgGLNz8wuK465lSE9JtNZg5qrUGsIgA)
Answer: Exclude is a conditional type. If a conditional type contains an unresolved type parameter (such as T) typescript will not try to reason much about the conditional type. So the assignability rules become pretty restrictive.
For Exclude, if the second parameters are different (ie the type tested against is different) the assignability check fails (such as string | boolean vs string in your case) . If the first parameters (ie the tested type) has a type relation, the assignment succeeds. So for example this will work:
type ExcludeString<T = any> = Exclude<T, string>;
type ExcludeStringAndBoolean<T = any> = Exclude<T, string | boolean>;

function test1<T extends U, U>(p: ExcludeString<T>) {
  let a: ExcludeString;
  a = p;
}

Playground Link
Comment: @AndreiKovalev I wish I could. Most of the really arcane type stuff is only on GH and is not really easy to find. The conditional type compatibility I came across here https://github.com/microsoft/TypeScript/issues/12936#issuecomment-524631270 where the commenter mentions he got it from a compiler code comment ... so I guess official  ?
Comment: Can you supplement your answer with a link to the documentation page if it exists on the Typescript site?


Can't map a certain word to vector

Question: I'm having trouble with implementing word-to-vector mapping with GloVe. My code seems to be working fine, but there is a weird problem: I'm getting error when trying to map one particular word - 'the', to it's vector representation. I have no idea why this is happening.
This is my code for reading the GloVe file:
def read_glove_vecs(glove_file):
    with open(glove_file, 'r', encoding='utf-8', errors='ignore') as f:
        words = set()
        word_to_vec_map = {}
        for line in f:
            line = line.strip().split()
            curr_word = line[0]
            words.add(curr_word)
            word_to_vec_map[curr_word] = np.array(line[1:], dtype=np.float64)

        i = 1
        words_to_index = {}
        index_to_words = {}
        for w in sorted(words):
            words_to_index[w] = i
            index_to_words[i] = w
            i = i + 1
    return words_to_index, index_to_words, word_to_vec_map

As you can see the function above returns variable 'word_to_vec_map' which is supposed to map the words from training set to the their GloVe representations.
Here's a snippet from the training set:
I am proud of your achievements,2,,
Miss you so much,0,, [0]
food is life,4,,
I love you mum,0,,
Stop saying bullshit,3,,
congratulations on your acceptance,2,,
The assignment is too long ,3,,
I want to go play,1,, [3]

It appears as though I am able to map the words using word_to_vec_map:

print(word_to_vec_map['proud'])

[-0.5918    0.27671  -0.46971  -0.54743   1.3504   -0.63907  -0.6819
  0.54207  -0.40552   0.11271   0.1564    0.21604  -0.035073 -0.30228
  0.15753  -0.10437   0.64561   1.0843    0.28788  -0.24031  -1.2893
  0.82949  -0.44547   0.11085   1.1249   -1.5474   -1.3967    0.1393
  0.23133  -0.46974   1.5829    0.87095   0.13645   0.047461 -0.37914
 -0.45608   0.033173  0.39443  -0.67186  -0.92765  -0.19048  -0.59441
 -0.046391  0.14051   0.032863  0.42813  -1.3888   -0.20055  -0.26487
  0.57981 ]

print(word_to_vec_map['much'])

[ 0.36999    0.082841   0.16883   -0.50223    0.37935    0.13343
 -0.32527   -0.17964   -0.40393    0.58149   -0.14505    0.1399
 -0.1566    -0.60951    0.62075    0.5596     0.35677    0.25654
 -0.33583   -0.82497   -0.11897    0.21829    0.27755   -0.38194
  0.54374   -1.7705    -0.74366    0.40402    0.88709   -0.021368
  3.7891     0.39953    0.51627   -0.48584   -0.052367  -0.28135
 -0.60422    0.46096    0.11491   -0.49699   -0.34498    0.38645
  0.14052    0.43843   -0.33583    0.13546   -0.12158    0.0053184
 -0.50853    0.24986  ]

print(word_to_vec_map['miss'])

[-3.2273e-01  5.6182e-01 -6.6363e-01  3.8883e-01 -4.6558e-02  2.2328e-01
 -7.5691e-01  7.0853e-01  5.5714e-01 -5.9996e-02  3.1235e-01  1.6741e-01
 -5.4568e-01 -3.8765e-01  1.2309e+00  3.4766e-01 -5.0017e-02 -4.9804e-02
 -6.6282e-01  2.2854e-01 -7.8443e-01  6.5823e-01  5.6099e-01  3.3218e-01
  5.3049e-01 -1.3611e+00 -4.9452e-01  2.7711e-01 -2.2982e-01 -1.1492e+00
  1.5028e+00  1.0916e+00 -9.8464e-02  3.9349e-04  2.5753e-01 -1.5470e-01
  2.7595e-01  6.4750e-01 -5.6537e-02 -1.3046e+00 -5.8200e-01  1.2838e-01
 -1.1416e-01 -8.0836e-01 -8.3921e-01  2.5609e-01  1.5629e-01 -9.7299e-01
  1.1130e-01  4.4500e-01]

But then:
print(word_to_vec_map['the'])

KeyError                                  Traceback (most recent call last)
<ipython-input-24-ebc9756c0cc8> in <module>
----> 1 print(word_to_vec_map['the'])

KeyError: 'the'

Does anyone has any idea why this is happening? Why can't I map this particular word?
Answer: I solved the problem by downloading another file with pretrained GloVe vectors from here:
https://www.kaggle.com/rtatman/glove-global-vectors-for-word-representation#glove.6B.50d.txt
Answer: I tried the same code and it is able to map the vector for 'the' as well. kindly check once again.
def read_glove_vecs(glove_file):
    with open(glove_file, 'r', encoding='utf-8', errors='ignore') as f:
        words = set()
        word_to_vec_map = {}
        for line in f:
            line = line.strip().split()
            curr_word = line[0]
            words.add(curr_word)
            word_to_vec_map[curr_word] = np.array(line[1:], dtype=np.float64)

        i = 1
        words_to_index = {}
        index_to_words = {}
        for w in sorted(words):
            words_to_index[w] = i
            index_to_words[i] = w
            i = i + 1
    return words_to_index, index_to_words, word_to_vec_map

word_to_index, index_to_words, word_to_vec_map = read_glove_vecs(GLOVE_EMBEDDING_PATH)
word_to_vec_map['the']

array([ 4.1800e-01,  2.4968e-01, -4.1242e-01,  1.2170e-01,  3.4527e-01,
       -4.4457e-02, -4.9688e-01, -1.7862e-01, -6.6023e-04, -6.5660e-01,
        2.7843e-01, -1.4767e-01, -5.5677e-01,  1.4658e-01, -9.5095e-03,
        1.1658e-02,  1.0204e-01, -1.2792e-01, -8.4430e-01, -1.2181e-01,
       -1.6801e-02, -3.3279e-01, -1.5520e-01, -2.3131e-01, -1.9181e-01,
       -1.8823e+00, -7.6746e-01,  9.9051e-02, -4.2125e-01, -1.9526e-01,
        4.0071e+00, -1.8594e-01, -5.2287e-01, -3.1681e-01,  5.9213e-04,
        7.4449e-03,  1.7778e-01, -1.5897e-01,  1.2041e-02, -5.4223e-02,
       -2.9871e-01, -1.5749e-01, -3.4758e-01, -4.5637e-02, -4.4251e-01,
        1.8785e-01,  2.7849e-03, -1.8411e-01, -1.1514e-01, -7.8581e-01])

Can't map a certain word to vector


control the textfield from checkbox

Question: dear i have 2 text and 2 checkbox:
<input type="checkbox" id="class1">
<input type="checkbox" id="class2">

<input type="text" id="valclass1">
<input type="text" id="valclass2">

i want if i checked at "class1" then click show button "valclass1" can show. but if not checked, it hidden.how do i do that?
Answer: I would do it like this:

<input type="checkbox" id="class1">
<input type="checkbox" id="class2">

<input type="button" id="ShowButton" />

<input type="text" id="valclass1" style="display: none">
<input type="text" id="valclass2" style="display: none">

It would work, but probably doesn't answer your question. You need to learn more about JavaScript to be able to roll your own solution.
Check out W3C's JavaScript tutorial

control the textfield from checkbox


Is "number of times" ordinal or interval variable?

Question: For my research paper, I want to measure headache frequency and I asked participants " Since last month how many times you have had headche ? and they gave answers like 2 times, 3, 5, 10, 14 times etc..
I am confused with the type of this data, Shall I treat it as ordinal or interval ?
Comment: It's actually ratio scale. "4 times" is really twice "2 times". But it's discrete (since it's a count), not continuous.
Answer: It is ordinal, because the order matters. It is also interval, because the difference between 1 and 2 is the same as that between 20 and 21 - exactly, unambiguously 1 headache. It is also a "ratio" variable, because the value of zero reflects the complete absence of the thing being measured.
An example of ordinal but not interval would be if you asked them to rate the severity of the headache. You could rank these in a meaningful order (maybe as: low, medium, high) but there is nothing intrinsic about the measurement that says the distance between low and medium is the same as that between medium and high.
EDIT: Following from Peter's comment, I realize I didn't actually answer the question: Treat it as a ratio variable.
Comment: It's also a *count* - for most analyses you might want to do it's not rescalable.
Comment: When a variable is ratio it is always ordinal and interval, so usually we simply say it is ratio. Indeed, treating a ratio (or count) variable as ordinal will often be a bad idea - classifying continuous or count variables usually is.


Do linear continua contain $\mathbb{R}$? Can a nontrivial connected space have only trivial path components?

Question: Consider a connected space $X$ under the order topology, such that $X$ contains at least two elements. Does there exist a subspace of $X$ homeomorphic to $\mathbb{R}$? If there isn't, then $X$ has only trivial path components.
Answer: Consider $X = [0,1]^{\omega_1}$ with the dictionary order. The property that $f, h \in X \Rightarrow \exists g : f < g < h$ follows readily so I'll skip that. The least upper bound property holds as well (Does $[0,1]^{\mathbb{\lambda}}$ have the least upper bound property under the dictionary order?) so we conclude $X$ is a linear continuum.
We prove for $f < g$ such that $f$ and $g$ are eventually $0$ that there is no path $\phi : [0,1] \to X$ such that $\phi(0) = f$ and $\phi(1) = g$.
Let $\alpha$ be an element of $\omega_1$ such that $f$ and $g$ are $0$ for all elements greater than $\alpha$. Consider $\beta \in \omega_1$ with $\beta > \alpha$ and $f_{\beta} \in X$ which agrees with $f$ everywhere except at $\beta$ and has $f_{\beta}(\beta) := f(\beta) + 1$.
Define $I_{\beta} := (f_{\beta+1}, f_\beta)$. Each $I_\beta$ is a disjoint open subset of $[f,g]$ which is nonempty by the linear continuum property. There are uncountably many such $\beta$ so $[f,g]$ cannot be homeomorphic to $[0,1]$ and we conclude there is no path connecting $f$ and $g$.
Now let $f$ and $g$ be arbitrary elements of $X$. We prove there exists $f_0, g_0$ which are eventually zero such that $f < f_0 < g_0 < g$. Let $\alpha$ be the first element such that $f(\alpha) \neq g(\alpha)$, so $f(\alpha) < g(\alpha)$. Pick $f_0$ and $g_0$ such that they agree with $f$ and $g$ before $\alpha$, such that $f(\alpha) < f_0(\alpha) < g_0(\alpha) < g(\alpha)$ - which is possible since $[0,1]$ is a linear continuum, and such that $f_0$ and $g_0$ are zero after $\alpha$. Then the relation holds by definition of the dictionary order.
Therefore the closed interval between any two points contains a closed interval which is not path connected and so cannot be path connected.

I asked if $[0,1]^{\omega}$ under the dictionary order topology has only trivial path components and Niels Diepeveen answered this affirmatively (https://math.stackexchange.com/a/2318699/444923).
The nice thing about this linear continuum is that it has the same cardinality as the reals whereas $[0,1]^{\omega_1}$ has the cardinality of the power set of the reals. Therefore there's the uninsightful reason that $[0,1]^{\omega_1}$ has only trivial path components that its closed intervals have a different cardinality than that of a real interval.
Comment: I believe my construction actually gives a space with the cardinality of the reals (at least if you take $L$ to be complete and have cardinality at most that of the reals).  Since $L$ is complete and the construction of $Y$ is by an induction of length $\omega$, you will only need to fill gaps of cofinality $\omega$ in $Y$ in order to complete it.
Comment: did you simultaneously post a question and its answer? Both were posted exactly 12 min ago. Did you have your answer ready and typed when you posted your question?
Comment: well I guess this is what you did, and it seems to be acceptable ... well, the answer is nice, and here is who says it is ok to do this (subject to certain mild assumptions): https://math.meta.stackexchange.com/questions/20447/is-it-ok-to-post-a-question-you-already-know-the-answer-with-the-only-purpose-to and https://math.meta.stackexchange.com/questions/15017/can-i-post-a-question-and-an-answer-just-because-i-think-it-helps-others
Comment: @Mirko Yes. I've been typing my questions and then trying to answer them to the best of my ability. If I think I answered my question I'll include it with the "answer your own question feature".
Comment: if you like general topology you should show up at the coming Summer topology conference :) https://www.udayton.edu/artssciences/academics/mathematics/events/topology-conference-2017/welcome/index.php and if you like lex order in product spaces, you may find interesting the open question whether the countable power of the Sorgenfrey line is a D-space https://projecteuclid.org/euclid.pjm/1102785280
Comment: I might just come :)
Comment: you missed the early registration deadline ... but you might try the "Funding" link at the conference web site, in case they have some money left
Answer: Here's another way to get a counterexample.  Let $L$ be any totally ordered set that does not embed in $\mathbb{R}$ (e.g. $L=\omega_1$, or any totally ordered set of cardinality greater than $\mathfrak{c}$).  Define a sequence of totally ordered sets $Y_0\subset Y_1\subset Y_2\subset\dots$ as follows.  Let $Y_0=\mathbb{Q}$ (or really any totally ordered set with more than one point).  Given $Y_n$, define $Y_{n+1}$ to be $Y_n$ with a copy of $L$ inserted right after each element of $Y_n$.  (If you like, $Y_{n+1}=Y_n\times (1+L)$ with the lexicographic order.)
Now let $Y=\bigcup_n Y_n$, and let $X$ be the Dedekind completion of $Y$.  Note that $Y$ is a dense linear order, since if $x,y\in Y_n$ with $x<y$ then in $Y_{n+1}$ there is a whole copy of $L$ between $x$ and $y$.  Thus $X$ is a complete dense linear order, and thus is connected in the order topology.  But between any two points of $X$ there is a copy of $L$, and so no interval in $X$ is isomorphic to $\mathbb{R}$.  It follows easily that no subspace of $X$ in the order topology is homeomorphic to $\mathbb{R}$.


What does this series with generalized falling factorial converge to?

Question: I have a series which contains an $nth$ term $t(t-a)(t-2a)(t-3a)...(t-(n-1)a) = f(t,n).$
The series itself is
$$\sum_{n=0}^{\infty}\frac{f(t,n)e^{-an}}{n!}.$$
I looked at this article https://en.wikipedia.org/wiki/Falling_and_rising_factorials
and at the bottom of the "Relation to umbral calculus" section, I see a series with a falling factorial that converges to a known result. However, this doesn't quite match what I see.
So, I scroll further down and see under the "Generalizations" section that this object has a name, $f(t,n) = t^{n/-a}.$
Can these results be combined in any way to yield an explicit result? I'm hoping the result is some type of exponential function.
Comment: Note $f(t,n)/n!=a^n{t/a\choose n}$ so you're very close to the binomial theorem.
Answer: Expanding Gerry's comment into an answer,
\begin{align}
\sum_{n\ge 0}\frac{f(t,n)}{n!}e^{-an}
&=\sum_{n\ge 0} \frac{(t/a)(t/a-1)\cdots (t/a-n+1)}{n!} \cdot a^ n\cdot e^{-an}\\
&=\sum_{n\ge 0} \binom{t/a}{n} \Big(ae^{-a}\Big)^{n}\\
&= (1+ae^{-a})^{t/a}
\end{align}
The last step uses Newton's binomial theorem.
Comment: Good. But I can't help thinking it would have been better to encourage OP to do some of the work.


Suggestions on setting up a practice room

Question: We are setting up a simple practice room in our house, the room is quiet small approximately 30 square meters. Here's the layout.

As you can see their is no amps because of space constraints, electric drum kit for noise issues. I really dont know if this setup works.
We are not a professional musicians, this is just a hobby and for fun.
And probably use this setup for small parties like birthdays.
Comment: Probably not especially if one instrument is much louder than the others. Setting ups AUXs and using them with headphones or in-ear monitors lets everyone hear at all instruments at level that is good for them without affecting the mixer output.
Comment: Do you have AUXs set up for everyone on the mixer so they can hear themselves and each other?
Comment: The mixer has an AUX output on each channel. Does the speakers setup is not enough?
Answer: You haven't mentioned mics. You may need 2 or 3, if you are playing ; listening with headphones, bare voices won't be heard.
30 sq.m. is a nice size, and while the drum kit will take up valuable space, I think there is room for a couple of practice amps at least. 60 watt with 12" speakers will be plenty. Then the vox can go through the p.a.  With the amps spread out, there will be a more spacial feel, with guitar and bass coming from different directions. I also feel that using headphones, especially if you also use wired mics,etc., will end up with spaghetti all over the floor (too many cables).
Ideally the p.a. speakers would be hung on the wall, but then you will probably have feedback problems with mics - if you use them.
Also, a source to play backing tracks (and ordinary ones !) is useful. This, in stereo, will need inputs to plug into - unless it has its own speakers - which CAN go on the wall.
With the recording facility, you can always use the send output from the amps to get guitar/bass signals to the deck.
Answer: As you have an electronic kit the setup should be fine. I'm not sure I agree with needing headphones for monitoring. You have said noise is an issue so I assume you won't be overly loud. With a good balance and everyone taking responsibility for their own relative level, it should be fine.


Why is my provider asking me to use a VLAN

Question: We are getting a fiber PTP circuit from Verizon, and have been having trouble going live with it. Finally, through a conference call with Verizon, they tell us to configure point A as VLAN 29 and point B as VLAN 45. After doing so, we are able to establish communications. We told them to remove the VLAN because we should not need it on a point to point connection, which resulted in a change order that will take a month to complete. The reason I ask is because getting this connection has taken over a year, and Verizon says that we requested the VLAN. They also say that it is more secure. Is this some kind of industry standard that I don't know about?
Comment: I've never heard of "vlans are security" but then again there are people that think NAT adds security, so perhaps its something ridiculous like that.
Answer: One aspect of security with VLANs that Verizon may be (but I doubt it) thinking of, is that they allow/cause you to separate your network into logical (virtual) segments. If you have hosts on VLAN 29 and other hosts on VLAN 45, then those networks cannot talk to each other without being routed, so the traffic will be localized to that particular VLAN. This could be considered "more secure" (not "secure") because traffic between VLANs can be regulated, controlled, stopped with firewalls, etc.
I'd be more inclined to think that some Verizon person has no idea what they're talking about and just regurgitated something they heard somewhere else, but that's just my experience with them as well. At a previous job, we worked with them to get dark fiber and other connections run between my company's locations, and it was like explaining quantum mechanics to my child. Blank stares and crickets.
Answer: A VLAN will allow you to use a single physical Ethernet link between two locations to carry traffic of multiple logically separate Ethernet segments.
For example suppose at location A you have hosts A1 and A2 and at location B you have hosts B1 and B2. You have a single Ethernet cable between the two locations through which A1 will need to communicate with B1, and A2 will need to communicate with B2. No other communication is permitted.
You could attach an unmanaged switch to each end of the connection and configure A1 and B1 with one IP prefix and A2 and B2 with another IP prefix. However this is not highly secure as all hosts can still communicate with each other if only they do so using IP addresses from the other prefix than they were supposed to.
In such a setup using VLAN tagging can improve security. Instead of an unmanaged switch at each end a managed switch can be used. They can be configured to use VLAN tagging on the link between the two locations such that the traffic can be kept separate.
Then it will no longer be possible for A1 to communicate with any host other than B1, etc.
Whether such security needs apply to your scenario is impossible to say given the limited details in your question. If you do not have any need for the isolation provided by VLAN tagging, then there is no security to be gained from enabling VLAN tagging.
Comment: I have no use for VLAN tagging right now, I want a connection from point A to point B with all hosts being able to communicate. It is the telco that was requiring the use of VLAN's, which made no sense to me. My understanding is that they can use whatever routing or segmenting or tagging that they want inside of their network, and I should never know the difference. I should be able to see the WAN IP addresses at point A and point B, and set up a route between the two that allows my LAN's to see each other.


Jogar novamente, tabuleiro não "limpa" - Jogo da Velha Python

Question: Estou com um problema nesse código, é um jogo da velha para faculdade, ele está funcionando normal, mas na parte que coloquei pra jogar novamente, quando usuário digitar sim, ele não zera o tabuleiro, e fica com as marcações da partida anterior. Como faço para ele limpar as marcações, zerar o tabuleiro?
print('Bem Vindo ao Jogo da Velha! Vamos começar!')

print('-=-'*15)

def tabuleiro(**posicao):

    print('  {}  |  {}  |  {}  '.format(posicao['pos1'], posicao['pos2'], posicao['pos3']))
    print('------+------+------')
    print('  {}  |  {}  |  {}  '.format(posicao['pos4'], posicao['pos5'], posicao['pos6']))
    print('------+------+------')
    print('  {}  |  {}  |  {}  '.format(posicao['pos7'], posicao['pos8'], posicao['pos9']))

contar_jogadas = 0
def pedir_jogada(lista_totalpalpites):

    print('-=-'*15)
    while True:
        jogada = input('Digite uma posição no tabuleiro para jogar: ')

        if jogada.isdigit():
            jogada = int(jogada)
            if jogada in lista_totalpalpites:
                break
            else:
                print('Você digitou um número já pedido, tente novamente')
        else:
                print('Você não digitou um número válido, tente novamente')
    print('-=-'*15)
    return jogada

def verifica_jogada(jogada, numero_jogadas, **posicao):

    for key, value in posicao.items():
        if jogada == value:
            if numero_jogadas % 2 == 0:
                    posicao[key] = 'X'
            else:
                    posicao[key] = 'O'
    return posicao

def procurar_vencedor(**posicao):

    possiveis_1 = posicao['pos1'] == posicao['pos4'] == posicao['pos7']
    possiveis_2 = posicao['pos1'] == posicao['pos2'] == posicao['pos3']
    possiveis_3 = posicao['pos1'] == posicao['pos5'] == posicao['pos9']
    possiveis_4 = posicao['pos2'] == posicao['pos5'] == posicao['pos8']
    possiveis_5 = posicao['pos3'] == posicao['pos6'] == posicao['pos9']
    possiveis_6 = posicao['pos4'] == posicao['pos5'] == posicao['pos6']
    possiveis_7 = posicao['pos7'] == posicao['pos8'] == posicao['pos9']
    possiveis_8 = posicao['pos3'] == posicao['pos5'] == posicao['pos7']

lista_possiveis = [possiveis_1, possiveis_2, possiveis_3, possiveis_4, possiveis_5, possiveis_6, possiveis_7, possiveis_8]

    for possiveis in lista_possiveis:
        if possiveis == True:
            print('Temos um vencedor! Parabéns!')
            return True
        elif contar_jogadas == 8:
            print('Deu velha! Ninguém ganhou.')
            return True

posicao =
{
    'pos1': 1,
    'pos2': 2,
    'pos3': 3,
    'pos4': 4,
    'pos5': 5,
    'pos6': 6,
    'pos7': 7,
    'pos8': 8,
    'pos9': 9
}

lista_totalpalpites = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def denovo():
    jogar_denovo = input('''
Deseja jogar novamente?
Digite S para SIM ou N para NÃO.
''')

    if jogar_denovo.upper() == 'S':
        print('Bem Vindo ao Jogo da Velha! Vamos começar!')
        print('-=-'*15)
    elif jogar_denovo.upper() == 'N':
        print('Até logo!')
    else:
        denovo()

while True:

    tabuleiro(**posicao)
    jogada = pedir_jogada(lista_totalpalpites)
    lista_totalpalpites[jogada - 1] = 'X'
    posicao = verifica_jogada(jogada, contar_jogadas, **posicao)
    if procurar_vencedor(**posicao):
        tabuleiro(**posicao)
        denovo()

    contar_jogadas += 1

Answer: Dá para simplificar bastante o código e melhorar/corrigir vários detalhes:
Escolha a estrutura de dados adequada
Para o tabuleiro, você criou um dicionário com as chaves "pos1", "pos2", etc. Sempre que você tiver um dicionário cujas chaves são "alguma coisa 1", "alguma coisa 2", etc, é sinal de que provavelmente você deveria usar uma lista, e não um dicionário. Listas possuem posições numéricas sequenciais por definição, e usar dicionários neste caso não traz vantagem alguma e só complica o código à toa.
Pode até parecer um detalhe besta, mas escolher a estrutura de dados adequada é meio caminho andado para um programa melhor. Saiba quais são as estruturas que a linguagem disponibiliza (e principalmente, como elas funcionam) e use a mais adequada para cada caso.
A única "complicação" é que os índices de uma string começam com zero, mas acostume-se a isso, pois é assim que as linguagens funcionam ("praticamente tudo" na programação começa do índice zero).
Dê nomes melhores
Você chamou o tabuleiro de posicao, mas a variável deveria se chamar tabuleiro (ou então posicoes, no plural), pois ela não é uma posição, e sim o conjunto de todas as posições (ou seja, ela é o tabuleiro).
Também pode parecer um detalhe besta, mas dar nomes melhores ajuda muito na hora de programar. No código abaixo você verá que mudei outros nomes também.
Validar se foi digitado um número
Não use isdigit(), pois há vários caracteres para os quais isdigit() retorna True, mas dão erro ao converter para número com int(). Um exemplo é o ² (SUPERSCRIPT TWO), e há vários outros (veja a lista completa aqui).

"Ah, mas é só um exercício, o usuário sempre vai digitar números válidos."

Se for assim, bastaria converter para int direto, sem precisar testar se é dígito (ou seja, isdigit() também não seria necessário neste caso). Se o usuário vai digitar algo, esteja preparado para receber "qualquer coisa" e só prossiga se tiver certeza que o dado é válido.
A maneira mais garantida é simplesmente converter para int, e capturar o ValueError para saber se deu erro.
Há outros detalhes para arrumar, como:

não chame a função denovo() dentro dela mesma. Apesar de "funcionar", você está fazendo uma chamada recursiva, e poderá haver um estouro de pilha se o usuário não digitar nem "S" nem "N" por muitas vezes seguidas (veja aqui um exemplo - role até o final da página e veja o erro de stack overflow). Use um loop simples e pronto.
coloque todas as tarefas repetitivas em funções (até mesmo o print('-=-'*15), que apesar de ser uma única linha, se repete várias vezes, então se você quiser mudá-la, terá que mudar em vários lugares; já usando uma função, você só muda em um lugar e pronto)
não precisa passar os parâmetros com unpack (ou seja, com os asteriscos antes: funcao(**valor) não é necessário no seu caso - veja aqui um exemplo de caso em que seria necessário)
também é interessante verificar se a posição escolhida é válida, pois o usuário pode digitar 100, e ao tentar acessar a posição 100 do tabuleiro, dará erro
tem outros detalhezinhos que você poderá ver no código a seguir

def mostrar_separador():
    print('-=-' * 15)

def criar_tabuleiro(): # cria um tabuleiro vazio
    return list(range(1, 10)) # lista com os números entre 1 e 9

def mostrar_tabuleiro(tabuleiro):
    print('  {}  |  {}  |  {}  '.format(*tabuleiro[:3]))  # mostra as 3 primeiras posições
    print('------+------+------')
    print('  {}  |  {}  |  {}  '.format(*tabuleiro[3:6])) # mostra da quarta à sexta posição
    print('------+------+------')
    print('  {}  |  {}  |  {}  '.format(*tabuleiro[6:]))  # mostra as 3 últimas posições

def pedir_jogada(tabuleiro, jogador):
    mostrar_separador()
    while True:
        try: # não use isdigit(), capture o ValueError
            print(f'jogador atual: {jogador}') # incluí esta mensagem para facilitar um pouco
            jogada = int(input('Digite uma posição no tabuleiro para jogar: '))
            if jogada <= 0 or jogada > len(tabuleiro): # verifica se o valor não está fora dos limites do tabuleiro
                print(f'Posição inválida: {jogada}')
            elif jogada in tabuleiro:
                mostrar_separador()
                return jogada # retorna direto, não precisa do break
            else:
                print('Você digitou um número já pedido, tente novamente')
        except ValueError:
            print('Você não digitou um número válido, tente novamente')

def jogo_terminou(tabuleiro):
    posicoes_vencedoras = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8], # horizontal
        [0, 3, 6], [1, 4, 7], [2, 5, 8], # vertical
        [0, 4, 8], [2, 4, 6] # diagonal
    ]
    # verifica todas as combinações de posições vencedoras
    for pos1, pos2, pos3 in posicoes_vencedoras:
        if tabuleiro[pos1] == tabuleiro[pos2] == tabuleiro[pos3]:
            print(f'Temos um vencedor: {tabuleiro[pos1]}! Parabéns!') # mudei a mensagem para mostrar quem ganhou
            # se já encontrei um vencedor, posso retornar direto (não precisa continuar verificando as outras combinações)
            return True

    # não tem vencedor, verifica se todas as posições estão ocupadas (não preciso mais do contador de jogadas)
    if all(posicao in ('X', 'O') for posicao in tabuleiro):
        print('Deu velha! Ninguém ganhou.')
        return True

    # jogo ainda não terminou
    return False

import sys

def verificar_jogar_novamente(): # mudei o nome "denovo" para algo mais significativo
    while True: # use um loop em vez de chamar a função dentro dela mesma
        jogar_denovo = input('''
Deseja jogar novamente?
Digite S para SIM ou N para NÃO.
''').upper() # já transforma em maiúscula aqui

        if jogar_denovo == 'S':
            mostrar_separador()
            break # sai do while
        elif jogar_denovo == 'N':
            print('Até logo!')
            sys.exit() # sai do programa
        else: # incluí uma mensagem a mais para ajudar o usuário
            print('Você deve digitar "S" ou "N"')

def dados_iniciais(): # o jogo começa com o jogador X e tabuleiro vazio
    print('Bem Vindo ao Jogo da Velha! Vamos começar!')
    return ('X', criar_tabuleiro())

jogador, tabuleiro = dados_iniciais()
while True:
    mostrar_tabuleiro(tabuleiro)

    # como o tabuleiro agora é uma lista, posso simplesmente marcar a jogada mudando-o diretamente
    # e ele substitui a lista_totalpalpites, que se torna redundante
    jogada = pedir_jogada(tabuleiro, jogador)
    tabuleiro[jogada - 1] = jogador
    jogador = 'O' if jogador == 'X' else 'X' # troca o jogador de X para O ou vice-versa

    if jogo_terminou(tabuleiro):
        mostrar_tabuleiro(tabuleiro)
        verificar_jogar_novamente()
        # reinicio o tabuleiro
        jogador, tabuleiro = dados_iniciais()

Eu usei sys.exit() para sair do programa. O problema é que ele sai mesmo, ou seja, se tivesse algum outro código depois do while True, ele não seria executado.
Uma outra opção é mudar a função verificar_jogar_novamente para retornar True ou False, indicando se o jogo deve continuar ou não, e então eu verifico isso no código:
def jogar_novamente(): # mudei o nome para "jogar_novamente"
    while True: # use um loop em vez de chamar a função dentro dela mesma
        jogar_denovo = input('''
Deseja jogar novamente?
Digite S para SIM ou N para NÃO.
''').upper() # já transforma em maiúscula aqui

        if jogar_denovo == 'S':
            mostrar_separador()
            return True # o jogo deve continuar
        elif jogar_denovo == 'N':
            print('Até logo!')
            return False # o jogo não deve continuar
        else: # incluí uma mensagem a mais para ajudar o usuário
            print('Você deve digitar "S" ou "N"')

...
jogador, tabuleiro = dados_iniciais()
while True:
    mostrar_tabuleiro(tabuleiro)

    # como o tabuleiro agora é uma lista, posso simplesmente marcar a jogada mudando-o diretamente
    # e ele substitui a lista_totalpalpites, que se torna redundante
    jogada = pedir_jogada(tabuleiro, jogador)
    tabuleiro[jogada - 1] = jogador
    jogador = 'O' if jogador == 'X' else 'X' # troca o jogador de X para O ou vice-versa

    if jogo_terminou(tabuleiro):
        mostrar_tabuleiro(tabuleiro)
        if not jogar_novamente(): # se não é para jogar novamente, sai do while
            break # sai do while True
        # é para jogar novamente, reinicio o tabuleiro
        jogador, tabuleiro = dados_iniciais()

Assim ele sai do while True, mas não encerra o programa (ou seja, se tivesse algum código depois do while, ele seria executado, o que não ocorreria com sys.exit()).
Answer: Uma opção, é criar uma função que retorna o tabuleiro vazio.

Você tem o seguinte trecho que inicializa o tabuleiro vazio:
posicao =
{
    'pos1': 1,
    'pos2': 2,
    'pos3': 3,
    'pos4': 4,
    'pos5': 5,
    'pos6': 6,
    'pos7': 7,
    'pos8': 8,
    'pos9': 9
}

E também o que cria os palpites:
lista_totalpalpites = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Criamos então uma função que retorna esse valor do tabuleiro vazio:
def tabuleiroVazio():
  return {
      'pos1': 1,
      'pos2': 2,
      'pos3': 3,
      'pos4': 4,
      'pos5': 5,
      'pos6': 6,
      'pos7': 7,
      'pos8': 8,
      'pos9': 9
  }

E também uma que retorna os palpites vazios:
def palpitesVazios():
  return [1, 2, 3, 4, 5, 6, 7, 8, 9]

Passamos então a inicializar a variável posicao com o retorno da função tabuleiroVazio:
posicao = tabuleiroVazio()

E a lista_totalpalpites com a palpitesVazios:
lista_totalpalpites = palpitesVazios()

Agora no trecho que você verifica o final de jogo, você chama novamente a função tabuleiroVazio e a palpitesVazios:
if procurar_vencedor(**posicao):
    posicao = tabuleiroVazio()
    lista_totalpalpites = palpitesVazios()
    tabuleiro(**posicao)
    denovo()

Além disso, perceba que mesmo optando por não jogar novamente, o jogo prossegue, isso porque seu while True não tem nenhum break, não tem uma forma de sair do loop.
Podemos alterar a função denovo para passar a retornar um boolean e com base nele fazer o break do while:
def denovo():
    jogar_denovo = input('''
Deseja jogar novamente?
Digite S para SIM ou N para NÃO.
''')

    if jogar_denovo.upper() == 'S':
        print('Bem Vindo ao Jogo da Velha! Vamos começar!')
        print('-=-'*15)
        return True
    elif jogar_denovo.upper() == 'N':
        print('Até logo!')
        return False
    else:
        return denovo()

Caso então ela retorna False, significa que não devemos seguir no loop e o jogo é encerrado:
if not denovo():
  break

Seu código ficará então mais ou menos da seguinte forma:
print('Bem Vindo ao Jogo da Velha! Vamos começar!')

print('-=-'*15)

def tabuleiro(**posicao):
    print('  {}  |  {}  |  {}  '.format(posicao['pos1'], posicao['pos2'], posicao['pos3']))
    print('------+------+------')
    print('  {}  |  {}  |  {}  '.format(posicao['pos4'], posicao['pos5'], posicao['pos6']))
    print('------+------+------')
    print('  {}  |  {}  |  {}  '.format(posicao['pos7'], posicao['pos8'], posicao['pos9']))

contar_jogadas = 0

def pedir_jogada(lista_totalpalpites):

    print('-=-'*15)
    while True:
        jogada = input('Digite uma posição no tabuleiro para jogar: ')

        if jogada.isdigit():
            jogada = int(jogada)
            if jogada in lista_totalpalpites:
                break
            else:
                print('Você digitou um número já pedido, tente novamente')
        else:
                print('Você não digitou um número válido, tente novamente')
    print('-=-'*15)
    return jogada

def verifica_jogada(jogada, numero_jogadas, **posicao):

    for key, value in posicao.items():
        if jogada == value:
            if numero_jogadas % 2 == 0:
                    posicao[key] = 'X'
            else:
                    posicao[key] = 'O'
    return posicao

def procurar_vencedor(**posicao):

    possiveis_1 = posicao['pos1'] == posicao['pos4'] == posicao['pos7']
    possiveis_2 = posicao['pos1'] == posicao['pos2'] == posicao['pos3']
    possiveis_3 = posicao['pos1'] == posicao['pos5'] == posicao['pos9']
    possiveis_4 = posicao['pos2'] == posicao['pos5'] == posicao['pos8']
    possiveis_5 = posicao['pos3'] == posicao['pos6'] == posicao['pos9']
    possiveis_6 = posicao['pos4'] == posicao['pos5'] == posicao['pos6']
    possiveis_7 = posicao['pos7'] == posicao['pos8'] == posicao['pos9']
    possiveis_8 = posicao['pos3'] == posicao['pos5'] == posicao['pos7']

    lista_possiveis = [possiveis_1, possiveis_2, possiveis_3, possiveis_4, possiveis_5, possiveis_6, possiveis_7, possiveis_8]

    for possiveis in lista_possiveis:
        if possiveis == True:
            print('Temos um vencedor! Parabéns!')
            return True
        elif contar_jogadas == 8:
            print('Deu velha! Ninguém ganhou.')
            return True

def tabuleiroVazio():
  return {
      'pos1': 1,
      'pos2': 2,
      'pos3': 3,
      'pos4': 4,
      'pos5': 5,
      'pos6': 6,
      'pos7': 7,
      'pos8': 8,
      'pos9': 9
  }

def palpitesVazios():
  return [1, 2, 3, 4, 5, 6, 7, 8, 9]

posicao = tabuleiroVazio()

lista_totalpalpites = palpitesVazios()

def denovo():
    jogar_denovo = input('''
Deseja jogar novamente?
Digite S para SIM ou N para NÃO.
''')

    if jogar_denovo.upper() == 'S':
        print('Bem Vindo ao Jogo da Velha! Vamos começar!')
        print('-=-'*15)
        return True
    elif jogar_denovo.upper() == 'N':
        print('Até logo!')
        return False
    else:
        return denovo()

while True:

    tabuleiro(**posicao)
    jogada = pedir_jogada(lista_totalpalpites)
    lista_totalpalpites[jogada - 1] = 'X'
    posicao = verifica_jogada(jogada, contar_jogadas, **posicao)

    if procurar_vencedor(**posicao):
        posicao = tabuleiroVazio()
        lista_totalpalpites = palpitesVazios()
        tabuleiro(**posicao)
        if not denovo():
          break

    contar_jogadas += 1

Veja online: https://repl.it/repls/CluelessIcyAddon