Solutions of a set of trigonometric equations

Question: I am trying to find maxima of a linear combination of functions $\text{trig}(x)\text{trig}(y)\text{trig}(z)$, where $\text{trig}$ is $\sin$ or $\cos$ (which of course gives 8 such terms):
$$
f(x,y,z) =
A\cos{x}\cos{y}\cos{z}
+B\cos{x}\cos{y}\sin{z}
+C\cos{x}\sin{y}\cos{z}
+D\cos{x}\sin{y}\sin{z}\\
+E\sin{x}\cos{y}\cos{z}
+F\sin{x}\cos{y}\sin{z}
+G\sin{x}\sin{y}\cos{z}
+H\sin{x}\sin{y}\sin{z}
$$
Coefficients of this linear combination are arbitrary. After a series of substitutions, I was able to reduce it to maximizing the following function:
$$
g(u,v,w)=K\cos(u+v+w+e) + L\cos u + M\cos v + N\cos w.
$$
Equating its gradient to 0, we are presented with a set of equations:
$$
\begin{cases}
K\sin(u+v+w+e) + L\sin u = 0, \\
K\sin(u+v+w+e) + M\sin v = 0, \\
K\sin(u+v+w+e) + N\sin w = 0.
\end{cases}
$$
Unfortunately I am not able to proceed further. Do you have any ideas how to find a solution?
Analytical solution would be great, however in the end it is used in computer calculations, so numerical solutions are also accepted, however they should be stable and work for arbitrary coefficients. For some specific values of free parameters maxima can be lines or planes, so these cases have to be detected (I am probably able to figure it out myself).
Thanks.
Comment: Is $e$ known or not ? Or, is $e=F(u,v,w)$ ?
Comment: $e$ is known, or, more precisely, is a function of $A, \dots, H$ free parameters
Answer: $\def\c{{\rm c}}\def\s{{\rm s}}$
Hint ($c_x=\cos(x),s_x=\sin(x)$ and so on):
One can approach the problem in the following way. Write:
$$
\begin{align}
f(x,y,z)
&=[A\,c_xc_y+C\,c_xs_y+E\,s_xc_y+G\,s_xs_y]\cos(z)\\
&+[B\,c_xc_y+D\,c_xs_y+F\,s_xc_y+H\,s_xs_y]\sin(z)\\
&=g(x,y) \cos(z-\phi(x,y))\tag1
\end{align}
$$
with
$$
\begin{align}
g^2(x,y)
&=[A\,c_xc_y+C\,c_xs_y+E\,s_xc_y+G\,s_xs_y]^2\\
&+[B\,c_xc_y+D\,c_xs_y+F\,s_xc_y+H\,s_xs_y]^2\tag2
\end{align}
$$
Clearly the function (1) has maximum value $g(x,y)$ at $z=\phi(x,y)$. Therefore we need to maximize $g^2(x,y)$. This can be dealt exactly as we have done with $f(x,y,z)$ expanding in (2) the squares and using
$$\cos^2y=\frac{1+\cos2y}2,\quad
\sin^2y=\frac{1-\cos2y}2,\quad \cos y\sin y=\frac{\sin2y}2.\tag3$$
After doing this you will obtain an expression
$$
\lambda(x)+h(x)\cos(2y-2\psi(x)),
$$
which after setting $y=\psi(x)$ reduces to
a simple problem of maximizing $\lambda(x)+h(x)$.
PS. By my calculation
$$\begin{align}
\lambda(x)&=\frac12\Big[(A^2+B^2+C^2+D^2)c_x^2+(E^2+F^2+G^2+H^2)s_x^2
+2(AE+BF+CG+DH)c_xs_x\Big]\\
h^2(x)&=\frac14\Big[(A^2+B^2-C^2-D^2)c_x^2+(E^2+F^2-G^2-H^2)s_x^2
+2(AE+BF-CG-DH)c_xs_x\Big]^2\\
&+\quad\Big[(AC+BD)c_x^2+(EG+FH)s_x^2+2(AG+BH+CE+DF)c_xs_x\Big]^2
\end{align}$$
but I could make a mistake.
Comment: You need do maximize $\lambda(x)+h(x)$, not just $h(x)$. I would first reexpress $\lambda(x)$ and $h(x)$ via $\cos2x$ and $\sin2x$ and then solve $$\frac d{dx}[\lambda(x)+h(x)]=0.$$
Comment: Thank you, I will calculate it myself, test it and edit in the corrections if needed. I have one more question: what is a best way to optimise $h^2$?
Comment: What do you mean by optimizing $h^2$?
Comment: I mean maximizing, as needed to solve the original problem. I know how to find the maximum of $A c_x^2 + B c_x s_x + C s_x^2$ - you can express it as $k(A,B,C) + l(A,B,C) \cos 2x + m(A,B,C) \sin 2x$. But how to find the maximum of such 4-th degree polynomial?
Comment: You are right. But fortunately $\lambda(x)$ does not increase the degree. Probably one could divide everything by $\cos 2x$, rewrite the rest using $t = \tan 2x$, and reduce the problem to a 3-rd or 4-th degree polynomial. Thank you for your comments.
Answer: Assuming that $e$ is known, rewrite the equations as
$$Z + L\sin (u) = 0 \tag 1$$
$$Z + M\sin (v) = 0 \tag 2$$
$$Z + N\sin (w) = 0 \tag 3$$
$$Z =K\sin(u+v+w+e) \tag 4$$
Hoping that there is modulo problems, using $(1),(2),(3)$ we have
$$u=-\sin ^{-1}\left(\frac{Z}{L}\right)\qquad\qquad v=-\sin ^{-1}\left(\frac{Z}{M}\right)\qquad\qquad w=-\sin ^{-1}\left(\frac{Z}{N}\right)\tag 5$$
Plug $(5)$ into $(1)$ to obtain
$$K \sin \left(e-\sin ^{-1}\left(\frac{Z}{L}\right)-\sin ^{-1}\left(\frac{Z}{M}\right)-\sin
   ^{-1}\left(\frac{Z}{N}\right)\right)-Z=0 \tag 6$$ Expanding the sine, this gives an algebraic equation in $Z$.
When $Z$ is known, go back to $(5)$ to get $(u,v,w)$.
May be, this could work
Comment: @PKua. DOn't try to make it a polynomial !! lot the function, locate the root and use Newton method to polish the root. If this looks to you to be a valid answer, may be you could accept it.
Comment: This could work. Perhaps one has to add a couple of $\pi$-s here and there, but it will only change the signs. Unfortunately, this will probably lead to a high-degree polynomial in Z
Comment: Thanks, I will think about it. Of course, I will accept the answer which I'll end up using in the code
Answer: This accepted answer was most helpful in devising a solution, however I made some modifications, so I am posting my own additional answer to describe them.
In the cited answer the last step was to find solutions of the equation $\frac{d}{dx}[h(x) + \lambda(x)] = 0$. One could write it as $\frac{dh(x)}{dx} = -\frac{d\lambda(x)}{dx}$, compute derivatives, square both sides to eliminate square roots, multiply by denominators and divide by $\cos^8x$ ending up with 8-th degree polynomial in $\tan x$. It can then be solved numerically (using specialized polynomial root finding algorithms, such as Aberth or Jenkins-Traub methods). One then examines all solutions and checks which one gives the actual maximum.
I was able to improve numerical stability by reducing the polynomial's degree to 6. First we solve the problem in 2D:
$$
f_{2D}(x,y) = A'\cos x \cos y + B'\cos x \sin y + C'\sin x \cos y + D'\sin x \sin y
$$
which we rewrite as
$$
\begin{align}
f_{2D}(x,y) &= \underbrace{\frac{1}{2}\sqrt{(A'-D')^2 + (C'+B')^2}}_{\mathcal{N}_1} \cos(x+y-a) + \underbrace{\frac{1}{2}\sqrt{(A'+D')^2 + (C'-B')^2}}_{\mathcal{N}_2} \cos(x-y-b), \\
\tan(a) &= \frac{C'+B'}{A'-D'}, \\
\tan(b) &= \frac{C'-B'}{A'+D'}.
\end{align}
$$
The maximum is obviously $\mathcal{N} = \mathcal{N}_1 + \mathcal{N}_2$ and its position is given by $x+y = a, x-y = b$.
In 3D we restrict the maximalization to a plane with a constant $z$ reducing the problem to 2D and we find that
$$
\begin{align}
A'(z) &= A\cos z + B\sin z, \\
B'(z) &= C\cos z + D\sin z, \\
C'(z) &= E\cos z + F\sin z, \\
D'(z) &= G\cos z + H\sin z.
\end{align}
$$
We know how that the maximum in this fixed plane is $\mathcal{N}(z)$, so we just have to maximize this function over $z$. This is done in an analogous way as for $h(x) + \lambda(x)$, but we end up with 6-th degree polynomial instead of 8-th.
The whole solution is implemented here - I left a link if someone wants to see it in detail.


Apollo server v3 playground offline

Question: I migrated from Apollo server v2 to v3 and I had trouble loading a Graphql playground override for offline usage.
The previous syntax was by filling the "playground" property in the Apollo server constructor but now this property doesn't exist.
Answer: So after looking for the new way to load my offline playground I found that there is a plugin called ApolloServerPluginLandingPageGraphQLPlayground in the apollo-server-core package.
This package behaves expects the same params as the old syntax and it worked for me.
Hope it will be helpful for someone.

Apollo server v3 playground offline


Hide on not hover - BOOTSTRAP TOGGABLE PILLS

Question: I am using the bootstrap toggable pills with some modifications to work vertical.
I want the contant-tab to disappear when I live the pill.
I tried but it's not working.
Here is my code:

Pane A

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Pane B

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Pane C

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Pane D

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

and this the JS

How can i do this?
Comment: What's the reason of preventDefault on hover?
Answer: Try putting a style of display : none; then change the css "none" to "block" when you want it to show.
Use
$("#pill-first a").css("display" : "block")

Comment: Oh you also didn't end your jquery statements in the code above.
Comment: Use $("#pills-first a").css({"display" : "block"});
Comment: You also need to do two functions for your hover function a handler in and a handler out or else the css will stay the same after you hover on then off look at https://api.jquery.com/hover/


How can I detect spurious regressions results?

Question: I run bivariate Granger-causality regressions. Let $y_{t}$ and $x_{t}$ be stationary time series. I test if $x_{t}$ can forecast $y_{t}$ with the following regression:
$$y_{t+1} = \alpha + \beta_{1}y_{t} + \beta_{2}x_{t} + \varepsilon_{t+1}$$
I find that $\beta_{2}$ is significantly larger than zero, so $x_{t}$ appears to forecast $y_{t}$.
However, I do not find any plausible explanation for this effect. So I am thinking that the result might be spurious. Is there any way to test if my result is spurious? How would one go about to argue that the result might be spurious?
Comment: Chris, I have edited your post to incorporate MathJax notation. If you click the edit button (lower left), you can see the pretty straightforward TeX implementation of MathJax for future reference.
Answer: While I can't speak for your specific statistical method, I can give the following general advice.
Understand your p values.
When you say that $\beta_2$ is significantly larger than zero, I presume you mean that  you obtained a p value $< .05$ for that term. What this means is often poorly understood, but it is set in stone: the probability of observing $\beta_2$ this high if the true value is $0$ is less than 5%. Nothing can be done about this.
Replicate Replicate Replicate
If your result doesn't make sense given your theory, try to replicate it with a new data set. From a purely Poperian point of view, this might not seem to make sense, but this is how science works, and you're right to question your result if it doesn't fit in with what you know: the more surprising a result is, the more likely it is to be spurious. Take for example, the Daryl Bem affair in psychology, or, more famously, think back to that time CERN had data showing that neutrinos could move faster than the speed of light - the unexpectedness of the result forced the researchers to look extra hard for explanations that didn't violate special relativity, and found one ultimately. Do you think they would have done this if the data disproved a less well known theory?


Wrist, Age and Very Depressed

Question: I'm 60 yo, played guitar my whole life - just not very well.  Open chords.  4 years ago, I got serious - 2 hours a day practice - 4 hours on weekends.  I play electric blues.  I mainly play sitting on a stool.
Last Christmas, I opened a pickle jar and hurt both wrists.  I can't find a way back healthy.   Went to hand specialists at the Duke University medical complex in Durham, North Carolina in the USA.  X-rays show some arthritis but nothing more that what would be expected. I'm working with an OT. Took steroid packs.  I quit playing 2 weeks ago and they got better - quite a bit.  Practice for 1/2 hour and I can feel the soreness.  I'm very careful about warming up stretching, not pressing too hard, minimizing wrist bend… all the normal stuff.  Bones says I've got worn tires and I shouldn't waste the remaining tread on exercises for strength.  Although he doesn't know really what to do.
My question.  Is there anyone out there that is older, had a similar problem and found a way out.   I'm at the point of quitting. I can't tell you how much that would cost me - maybe more than I have in the bank or can borrow. Pretty serious here.
Thank you
Comment: I think that r lo has given some absolutely fantastic advice, especially about the action on your guitar. I don't have an answer exactly, and my experience with injury was in college, but I can say that recovering—especially as a performer—just takes so much longer than you ever expect. The recovery is so slow and non-linear that it mostly doesn't seem like recovery *at all*.  But it is, and it will get better. Make sure to be honest with yourself about even incremental improvement, and don't focus too much about the inevitable backslides. You'll get there, I promise.
Comment: Sounds like you just need to give it some time off to heal.  But we're not doctors -- I'm not sure that this question is on-topic.
Comment: A quick google for "injury preventative guitar" yields some good results. However, now that some damage has been done, your best bet might be to allow time for healing in addition to a restructuring of your technique.
Answer: I would say to make sure the action on your guitar is at the lowest it can be for ease of playing. Also, you may consider playing slide guitar if it hurts to press strings. Also look into open tunings, you may find songs that are easier to play as well.
Hope some of this advice helps and don't give up.
Answer: Try playing a classical guitar instead. With a thicker and wider neck, and with nylon strings, which require much less finger pressure than steel strings, you might find that a classical guitar is easier to play.
Go to a music store that sells classical guitars and try one for a few minutes.
It may seem like a paradox, but many older players believe that a thicker neck is easier to grip and less fatiguing to play than a thinner one, and classical guitars have thick necks. The wider spacing between each string might help your fingers find their position better as well.
Another very important point: whether you switch to classical guitar or keep the guitar that you have, you could certainly benefit from taking a few lessons with a good professional guitar teacher to learn how to hold your left hand and fingers in the proper position to play with the least amount of hand tension (not to mention checking up on your posture, and how you hold the guitar itself, to minimize tension in your body.) Over the years you may have developed some bad habits that need to be un-learned and replaced with better ones.
Answer: I wonder if you have tendinitis.  If so, don't despair.  For tendinitis, it's helpful to stay away from the guitar for a few months.  Many musicians with tendinitis have a good recovery by taking a break of 3-6 months.  (This statement comes from knowing a lot of musicians.)
In the meantime, you can wear a soft brace from the drug store.  It wraps around your hand.  No metal parts.  You can do some gentle hand stretches.
I second the idea of working with a private guitar teacher, after your break from playing, to make sure your set-up is as ergonomic as possible.

Wrist, Age and Very Depressed


Unable to send couchdb data to elasticsearch using logstash

Question: Hi greetings I have been trying to push data from couchdb to elasticsearch here is the code
input {
couchdb_changes {
    db => "users"
    host => "localhost"
    port => "5984"
    }
}
output {
elasticsearch {
    hosts => ["127.0.0.1:9200"]
    index => "playtym"
    }
}

Comment: What happens? Please describe your problem in more details.
Comment: I have placed the above code in a "/opt/logstash/couch.conf" and running the command "$bin/logstash -f couch.conf". On running the command a pipeline is getting created but when changes happen in couchdb it is not pushing the data into elasticsearch
Answer: Can you paste the logstash log? so we could help you better.
Anyway, I am pasting my config that I am using to replicate my couch to elastic.
I am using couch behind nginx. The logstash is on the same server that elastic.
input {
  couchdb_changes {
    type => "foo"
    db => "database"
    host => "couch.example.com"
    username => "user"
    password => "pass"
    initial_sequence => 0
    secure => true
    port => 443
  }
}

filter {
  if [type] == "foo" {

    if "delete" in [@metadata][action] {
      mutate { add_field => { "[@metadata][my_action]" => "delete" } }
    }
    else {
      mutate { add_field => { "[@metadata][my_action]" => "index" } }
    }

    if [doc] {
      ruby {
        code => '
                event["doc"].each{ |k,v| event["#{k}"] = v }
                '
      }
    }
    # 6)
    if [doc] {
      mutate { remove_field => [ "[doc]" ] }
    }
    if [doc_as_upsert] {
      mutate { remove_field => [ "[doc_as_upsert]" ] }
    }
    if [@version] {
      mutate { remove_field => [ "[@version]" ] }
    }
  }
}

output {

  if [type] == "foo" {
    elasticsearch {
      index => "%{[ClassName]}" #ClassName is a doc field that I am using to organize the index and document_type
      document_type => "%{[ClassName]}"
      document_id => "%{[@metadata][_id]}"
      action => "%{[@metadata][my_action]}"
      doc_as_upsert => "true"
    }
  }
}

My config was based on this:
https://github.com/gammaliu/couchdb-logstash-elasticsearch
Comment: The above code in my question is the logstash config file. I am using apache as mu server.
Comment: No log is getting dumped


How can I effectively use the same orm model in two git repositories?

Question: The initial situation is that I have two fast-api servers that access the same database. One is the real service for my application and the other is a service for loading data from different sources. Both services have their own Github repository, but use the same orm data model.
My question is: What are best practices to manage this orm data model without always editing it in both code bases?
The goal would be to have no duplicated code and to adapt changes to the database only in one place.
Current structure of the projects:
Service 1 (actual backend):
.
├── app
│   ├── __init__.py
│   ├── main.py
│   └── database
│       ├── __init__.py
│       ├── ModelItem.py   # e.g. model item
│       ├── ...            # other models
│       ├── SchemaItem.py  # e.g. schema item
│       └── ...            # other schemas
│   ├── routers
│   └── ...

Service 2 (data loader):
.
├── app
│   ├── __init__.py
│   ├── main.py
│   └── database
│       ├── __init__.py
│       ├── ModelItem.py   # e.g. model item
│       ├── ...            # other models
│       ├── SchemaItem.py  # e.g. schema item
│       └── ...            # other schemas
│   ├── routers
│   └── ...

sqlalchemy(.orm) library is used for the orm models and schemas.
I had thought about making another repository out of it or a library of my own. But then I would not know how best to import them and whether I won't just produce more work.

Based on the answer, I created a private repository that I install via pip in the two servers.

Structure of the package Python packaging projects
Install the package from a private Github repository Installing Private Python Packages
Answer: Modularisation (avoiding code repetition) is a best practice, and so the ideal thing to do would indeed be to extract the model definition to a single file and import it where needed.
The problem is, when you deploy your two services both of them need to be able to 'see' the model file ... otherwise they can't import it. Because they are deployed separately, this isn't going to be as easy as before (they presumably aren't sharing a filesystem; if they were, it would be just as simple as before).
The usual solution to this is to make your model file available as a Python module and provide it via some server both services can reach over the network (for example, the public python package index, PyPI). You then install the module and import it in both deployed services.
This is inevitably going to be (a lot!) more work than just maintaining two copies. However, if you go to more than two copies that calculus could quickly change.


How to solve differential equations using fft?

Question: Can anyone point me to the principles and books/websites about it?
Which properties must the differential equation have that a solution with fft is possible?
Why can it be solved that way?
Answer: Books

Fourier Transformation and Linear Differential Equations by Zofia Szmydt
An Introduction to Fast Fourier Transform Methods for Partial Differential Equations with Applications by Morgan Pickering

There are also books on Fourier Transforms and also books on PDEs that have sections regarding FFT and PDEs. For example:

A First Course in Fourier Analysis by avid W. Kammler
Fourier and Laplace Transforms by R. J. Beerends, H. G. ter Morsche, J. C. van den Berg, E. M. van de Vrie

Papers

Fourier collocation method for differential equations
Solving Poisson's Equation using the FFT
Introduction to Fast Poisson Solvers
You can Google and there are many papers in this area (including papers from this year as there is still work going on in this area)

You may also want to check your local college library and Open Courseware as I would imagine you'd find some online materials in this area.
Comment: Deserves another TU!
Comment: @amWhy: Happy POETS day and thank you! :-)


varias chaves estrangeiras SQL

Question: Tenho a seguinte tabela: itens (ref) o atributo "ref" como chave primaria da tabela, pode ter associada varias chaves secundarias em outras tabelas [ex:tabela1(ref) e tabela2(ref) sendo "ref" a chave secundaria das respectivas tabelas]?
Comment: Sim, pode ter..
Answer: Um breve resumo
As Chave primárias e estrangeiras são dois tipos de restrições que podem ser usadas para impor integridade de dados nas tabelas.
Geralmente, uma tabela tem uma coluna ou uma combinação de colunas que contém valores que identificam exclusivamente cada linha na tabela (identity). Como as restrições PRIMARY KEY garantem dados exclusivos, elas são frequentemente definidas como uma coluna de identidade.
Essa identidade é utilizada nas demais tabelas (chave estrangeira) para classificar os registros que "pertencem" à tabela primária.
Observe o modelo abaixo e veja que é possível SIM definir em quantas for necessário:
<code>tbl_usuarios
    PK id_usuarios numero identity---+
       nome texto                    |
                                     |
tbl_materias                         |
    PK id_materias numero identity---͡ -+
       descricao texto               | |
    FK id_usuarios-------------------◄ |
                                     | |
tbl_faltas                           | |
    PK id_faltas numero identity     | |
       dataRef data                  | |
    FK id_usuarios-------------------◄ |
                                     | |
tbl_notas                            | |
    PK id_notas numero identity      | |
    FK id_materias numero------------͡ -◄
    nota numero                      |
    FK id_usuarios-------------------◄
                                     |
tbl_eventos                          |
    PK id_eventos numero identity    |
       dataRef data                  |
    FK tiposEvento numero            |
    FK id_usuarios-------------------◄

tbl_tiposEvento
    PK id_tiposEvento numero identity
    descricao texto
</code>
Restrições de chave primária e chave estrangeira

varias chaves estrangeiras SQL


Programmatically import a feed

Question: I can successfully import remote content using the Feeds module by manually clicking on the Import button. I need to execute the import process from code, either from a module or executing PHP code from the Rules module.
I have tried the following code in a custom module.
function imports_cron_cron(){
  drupal_set_message('Import-CRON responding to cron execution! ...');
  $importer_id = 'publications_import';
  $url = "http://xml/url";
  $feeds_source = feeds_source($importer_id);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
  $feeds_config['source'] = $url;
  $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
  $feeds_source->save();
  $feeds_source->startImport();

  drupal_set_message(' .... ENDING IMPORTS-CRON CALL!');
}

Both the drupal_set_message() calls are successfully executed, but no node is imported.
Can anyone help, please?
Answer: Your code seems to be OK. I use some similar code in one of my projects (this a csv importer, similar concept):
function custom_function($importer_id, $csvfile_path) {
  // Load the Feeds Source object.
  $source = feeds_source($importer_id);
  // Load the source fetcher config.
  $fetcher_config = $source->getConfigFor($source->importer->fetcher);
  $fetcher_config['source'] = $csvfile_path;
  $source->setConfigFor($source->importer->fetcher, $fetcher_config);
  $source->save();
  $source->startImport();
}

Make sure that you are using the foreground configuration, this way the batch process could be be executed "inside" drupal with showing the progress bar. Or you can force it:
// Tweak the importer configuration, to enable "Process in the background".
$config = array(
  'process_in_background' => TRUE,
);
$source->importer->addConfig($config);

// Execute the import.

Another approach could be to schedule it
// Schedule the import, and make sure importer is scheduled, too.
$source->schedule();
$source->importer->schedule();

This is a good article about feeds importer
Answer: Ive seen lots about this.
Heres my take , I want to be able to do this from the command line, and be able to do it from an install profile.
so taking hints from previous answers, and from the documentation Ive seen / found, Ive come to the realisation that
dont use the batch api for this unless
a) you're doing this from the form api (a user clicks)
or
b)
you're writing a drush command.
so this is what Ive got working in an module install
function load_data(){

// Files to import in specific order.
  $files = array(
    'challenge_importer' => 'data/challenges.csv',
);

$file_location_base = drupal_get_path('module', 'challenge');
foreach ($files as $feed => $file) {

$feedSource = feeds_source($feed);
// Set the file name to import
$filename = $file_location_base.'/' . $file;
if (!file_destination($filename, FILE_EXISTS_ERROR)) {
  $config = $feedSource->getConfig();
  $config['FeedsFileFetcher']['source'] = $filename;
  $feedSource->setConfig($config);
  $feedSource->save();
    while (FEEDS_BATCH_COMPLETE != $feedSource->import());
    }
  }
}

where

challenge_importer is a feeds importer,
challenge is the module.
data is stored in module/data
and with this structure you can have multiple files imported in a defined order.
Answer: I believe you need to do something more like
$node = new stdClass();
$node->type = 'feed';
$node->title = 'My feed';
$node->feeds['FeedsHTTPFetcher']['source'] = 'http://example.com/rss.xml';
node_save($node);

You should take a look at https://drupal.org/node/622700 (Programmatic operations).
Comment: Thank you Steven but I am looking for a stand-alone form solution rather than a node based solution.
Comment: If that's what you are looking for I believe what you are trying to do should work. Try adding some `watchdog` functions on variables to see what the variables contain.

Programmatically import a feed


What do the numbers on Mavis (Yonex) Badminton cocks mean?

Question: I have seen sports shops selling Yonex Badminton cocks in boxes titled "Mavis 350", "Mavis 500" or "Mavis 10".
Do these numbers mean anything in particular, or is it just that the Brands can't get creative with their names?
I have tried to look into this a bit, and some say it may imply its resemblance to a feather cock. So a Mavis 2000 is better than a Mavis 10 in resembling a Yonex feather cock. Is this true?
Answer: YONEX offers 8 different plastic shuttlecock products, although availability may differ depending on what region/country you're in. Depending on the market, some products may also not be available in white and yellow. Despite the picture on the YONEX homepage, the 2000 is available in yellow.
The pricing and marketing suggests that the higher the number the better (= closer to feather shuttles) the flight path is.
Mavis 10 to Mavis 370 look very similar. In contrast, Mavis 2000 are visibly different, more so than it you can see in the official promotion pictures. (I have never handled 500 or 600.)
In my personal experience and opinion, Mavis 10, 350 and 370 feel quite similar. Anecdotally, the 10 breaks easier than the other ones, but I don't have enough data on that.
Mavis 2000 feels quite different than the other ones. I feel that you get more control at the net and there's a slightly larger range of distance (i.e. you can hit it out a little bit easier, but also play it quite slow), although that may be partially a placebo effect.
The Mavis 2000 breaks a little bit earlier than the 350/370, but it's still on the scale of a plastic shuttle; you can easily play multiple hours with a single shuttle.
Nevertheless, the difference between a Mavis 370 and 2000 is still less than between a Mavis 2000 and a feather shuttle.
If you want to stick to YONEX plastic shuttles and value good flight characteristics, the Mavis 2000 is certainly a good idea. If you want the plastic shuttle to fly like every other decent plastic shuttle, go for one of the other ones, e.g. a 350.
Comment: Yes, I believe Mavis 10 are built cheaper. But it's likely that the difference is not more than a couple of cents. More importantly, offering (even slightly) different qualities allows YONEX to engage in [price discrimination](https://en.wikipedia.org/wiki/Price_discrimination): Beginners who just want any shuttle (i.e. are looking just at the price) will buy the Mavis 10 (instead of a non-YONEX one), whereas more advanced players usually opt for 350 and upwards, because they are willing to pay more for a slight quality increase.
Comment: Just a side question to this, but what's the point of a mavis 10 if it shares the least similarity to a feather cock? Is it simply the cost?
Comment: still not tried the 600?


PACF correct interpretation

Question: I'm three days old to Time Series Analysis and I'm trying to build an AR model on the variable slope_ma, which is a one period difference of X's mva 5 periods. X is generated from a random walk process.
$\Large Z_t = slope_{ma_t} = MVA(X;5;t) - MVA(X;5;t-1)$
$\Large Z_{t} = \Phi_{1}Z_{t-1} + \Phi_{2}Z_{t-2} + \Phi_{2}Z_{t-3} + \Phi_{4}Z_{t-4} + \Phi_{5}Z_{t-5} + \Phi_{6}Z_{t-6}$
(Ref. Time Series Analysis - Univariate and Multivariate - Second Edition - William Wei, pg. 15)
In this case k=0
As I understand PACF at lag $t-6$ (, $\approx 0.3.945$), corresponds to the value of $\Phi_{k6}$ coefficient and as per my knowledge that means that term $t-6$ it is positively correlated with term $t-1$ and $t$ itself.
But something tells me I'm wrong, cannot be that easy.
Can some one please explain correct interpretation for this case?
The code below performs the following analysis:

<code>import numpy as np
import pandas as pd
from datetime import datetime
from dateutil import parser
import seaborn as sns
sns.set()
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
from statsmodels.tsa.arima_model import ARMA

class RandomWalk:

    @staticmethod
    def gen_random_walk(size, std, last_date=None, value_0=0, freq="H", output_col_name="X"):

        if last_date == None:
            _last_date = datetime.today()
        else:
            _last_date = parser.parse(last_date)

        _p_t = np.zeros(size)
        _wn = np.random.normal(loc=0, scale=std, size=size)
        _p_t[0] = value_0
        _wn[0] = 0

        _date_index = pd.date_range(end = _last_date, periods=size, freq=freq)

        _df_rw = pd.DataFrame(np.stack([_p_t, _wn], axis=1), columns=[output_col_name, "wn"], index=_date_index)

        for i in range(1, size):
            _df_rw.iloc[i][output_col_name] = _df_rw.iloc[i - 1][output_col_name] + _df_rw.iloc[i].wn

        return _df_rw

PRD = 5
df = RandomWalk.gen_random_walk(10000,0.0001,value_0=1.0,freq="5min")
df["X"].plot(figsize=(15,5), title="X")
plt.show()
df["mva"] = df["X"].rolling(PRD).mean()
df["slope_ma"] = df["mva"] - df["mva"].shift(1)
df["slope_ma"].plot(figsize=(15,5), title="Slope MA")
df.dropna(inplace=True)
sgt.plot_pacf(df.slope_ma, lags=40, zero=True)
plt.show()

model = ARMA(df.slope_ma, order=(6,0))
results = model.fit()
print(results.summary())
</code>
Answer: PACF at lag $6$ mean the correlation de $X_t$ and $X_{t-6}$ that does not take into account the intermediate terms ($X_{t-1}, X_{t-2}, X_{t-3}, X_{t-4}$ and $X_{t-5}$)
Comment: Correct, and now I also know that the pattern in PACF (spikes each 5 periods) is because is detecting a Moving Average process in the underlying data, which is the case; Z is a one period difference on a 5 periods moving average.

PACF correct interpretation


SQL Server Getting where an data object was based in a Period of Time given Track Info

Question: I have a doubt on how to conclude this in SQL Server 2008 R2.
I have a table that has some inputs and this inputs have a Parent tag and a timestamp.
Sometimes these objects have their parent Tag changed in a timestamp. This parent tag can change from time to time.
 Let´s suppose that I have the table below. My current table has millions of data with different ObjectIDs. Seeing the Table, it is easy to see that the ParentID was changed in the timestamps 3 to 4, 6 to 7 and 8 to 9.

ProductID      ParentID       DateID          value
--------       ---------      -------         -------------
  100            1              1                325,2
  100            1              2                326,2
  100            1              3                329,6
  100            2              4                335,2
  100            2              5                336,5
  100            2              6                338,3
  100            3              7                339,2
  100            3              8                342,1
  100            1              9                343,7
  100            1              10               355,6
  100            1              11               385,8

The Answer I want is to which ParentID the ObjectID belonged and the Start and End timestamp and what was the delta value between the timestamps (Timestamp = TS)

ProductID      ParentID       DateID_Start   DateID_End   DeltaValue
  --------      ---------     ----------     --------     ----------
  100           1             1              4            10,0
  100           2             4              7            4,0
  100           3             7              9            4,5
  100           1             9              11           42,1

What I have Accomplish so far is getting when there is a change, but it only gives me the changes, but not the table above.

ObjectID      ParentID_Old   ParentID_New    DateID_Changed
  --------      ------------   ------------  ------------
  100           1              2              3 to 4
  100           2              3              6 to 7
  100           3              1              8 to 9

Here are the code to generate the table and the test inserts. Below as well is the Select to get the changes.
        --Initial Insert Code
   IF OBJECT_ID('tempdb..#Trackings') Is Not Null
    Drop table #Trackings

 Create Table #Trackings
 (
   ProductID bigint
 , value    float
 , StoreID  int
 , DateID int
 , Aux_Row_Number int
 )

Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,1,325.2,1)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,2,326.2,2)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,3,329.6,3)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,4,335.2,4)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,5,336.5,5)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,6,338.3,6)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,7,339.2,7)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,8,342.1,8)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,9,343.7,9)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,10,355.0,10)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,12,385.0,12)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,13,485.0,13)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,14,985.0,14)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,15,1585.0,15)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,16,3585.0,16)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,17,5585.0,17)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,18,6585.0,18)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,19,8585.0,19)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,20,9585.0,20)

And the SQL to get the changes I am using:
Select      ISNULL(A.StoreID,-1)
,           ISNULL(B.StoreID,-1)
,           A.ProductID
,           A.value
,           B.value
,           A.DateID
,           B.DateID
From        #Trackings A
Join        #Trackings B
On          A.ProductID = B.ProductID
And         A.Aux_Row_Number + 1 = B.Aux_Row_Number
And         ISNULL(A.StoreID,-1) <> ISNULL(B.StoreID,-1)

Any lights ideas Guys?
Thanks in advance!
EDITED: Just a little bit more "Business" info: ParentID would be like a store a product is and DateID the Time that it arrived there. So let's suppose that productID 100 is in the ParentID 1, it means that in the DateID 1 the productID 100 entered in Store 1. So for some reason it moved to Store 2 in DatedID 4. So my first row in the answer table means that ProductID 100 was in the StoreID 1 from DateID 1 up to DateID 4. The productID 100 then stayed in StoredID 2 from DateID 4 up to 7, then changed to StoredID 3 and finally it came back to StoreID 1 from DateID 9 up to our last DateID in the DateID range "selected". So that's why the answer table has 2 lines with ParentID 1.
Comment: In your answer table the logic for the last row is different that the first three rows. the `TSID_End` on row 4 is coming from a record with the same parent. On the other rows it is coming from the first record of the next parent.   Is this the expected result?
Comment: There is good details here, but there's a bit of a disconnect between the examples and the actual sample data, e.g. `ObjectID` and `ProductID`, `Aux_Row_Number`... It would be most useful to have consistent data and table structures between these different parts of the question.
Comment: @Declan-k The Result is like because it is the last Aux_Row_Number available :). So in the interval selected, the result does not give me more options and we need to just add in the TSID_End the last available number in the interval.
Comment: @IanPreston Thanks Man to pointing my silly mistake! Edited: objectId replaced for ProductID to be consistent! Aux_Row_Number will be used because I have different ProductsIDs and as so far I found it necessary, but you were right, I didn't gave more details about it. When I finally solve my issue I will update the posts below and check! Thanks :)
Answer: I finally found a solution that based on my Initial Table has a better performance than using CTE and as sugested by https://stackoverflow.com/users/2522030/mike-abramczyk (the real table has 5k entries and using the his suggestion was taking a long time).
After querying the search table, I added two lines to the table for each ProductID. These lines would receive a dummy StoreID (i.e. -9999): one with a Min(DateID) - 1 and another One with a Max(DateID) + 1.
Insert into #Trackings (Aux_Row_Number,StoreID,DateID,ProductID,value)
Select Min(Aux_Row_Number)-1 Aux_Row_Number,-9999 as StoreID, min(DateID)-1 as DateID,ProductID,Min(value)
From #Trackings
group by ProductID
Order by ProductID

Insert into #Trackings (Aux_Row_Number,StoreID,DateID,ProductID,value)
Select Max(Aux_Row_Number)+1 Aux_Row_Number,-9999 as StoreID, max(DateID)+1 as DateID,ProductID,Max(value)
From #Trackings
group by ProductID
Order by ProductID

Then, I used the Query I posted to get the changes. So I could get the Change from Dummy(-9999) to the real StoreID (1) and the last change from a real StoreID(3) to Dummy(-9999).
select      ISNULL(A.StoreID,-1)
,           ISNULL(B.StoreID,-1)
,           A.ProductID
,           A.value
,           B.value
,           A.DateID
,           B.DateID
,           ROW_NUMBER() OVER (Partition by B.ProductID Order by A.DateID)
from            #Trackings A
Join            #Trackings B
On              A.ProductID = B.ProductID
And             A.Aux_Row_Number + 1 = B.Aux_Row_Number
AND             ISNULL(A.StoreID,0) <> ISNULL(B.StoreID ,0)

This was the Crucial Step! Now I have I can create the result table with the DateIDs of the changes I was looking for. The Aux_Row_Number Column helped get a sequence in the changes to each product using (think that the last query has create the table #ProductStoreChanges - I will be posting the entire Soltion below):
select              A.ID_FinalStore,A.DateID_Final,B.DateID_Final,A.ProductID,B.value_2,A.value_2,B.value_2 - A.value_2 DeltaValue
from                #ProductStoreChanges A
Join                #ProductStoreChanges B
On                  (A.Aux_Row_Number + 1 = B.Aux_Row_Number)
And                 A.ProductID = B.ProductID
Order by            A.DateID_Final

Here is the Final Solution:
IF OBJECT_ID('tempdb..#Trackings') Is Not Null
    Drop table #Trackings

IF OBJECT_ID('tempdb..#ProductStoreChanges') Is Not Null
    Drop table #ProductStoreChanges

 Create Table #Trackings
 (
   ProductID bigint
 , value    float
 , StoreID  int
 , DateID int
 , Aux_Row_Number int
 , flg_changed bit Default(0)
 )

Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,1,325.2,1)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,2,326.2,2)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,3,329.6,3)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,4,335.2,4)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,5,336.5,5)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,6,338.3,6)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,7,339.2,7)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,8,342.1,8)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,9,343.7,9)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,10,355.0,10)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,12,385.0,12)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,13,485.0,13)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,14,985.0,14)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,15,1585.0,15)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,16,3585.0,16)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,17,5585.0,17)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,18,6585.0,18)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,19,8585.0,19)
Insert into #Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,20,9585.0,20)

Insert into #Trackings (Aux_Row_Number,StoreID,DateID,ProductID,value)
Select Min(Aux_Row_Number)-1 Aux_Row_Number,-9999 as StoreID, min(DateID)-1 as DateID,ProductID,Min(value)
From #Trackings
group by ProductID
Order by ProductID

Insert into #Trackings (Aux_Row_Number,StoreID,DateID,ProductID,value)
Select Max(Aux_Row_Number)+1 Aux_Row_Number,-9999 as StoreID, max(DateID)+1 as DateID,ProductID,Max(value)
From #Trackings
group by ProductID
Order by ProductID

 CREATE TABLE #ProductStoreChanges
 (
            ID_InitialStore         INT
  ,         ID_FinalStore           INT
  ,         ProductID                   INT
  ,         value_1                 BIGINT
  ,         value_2                 BIGINT
  ,         DateID_Initial          BIGINT
  ,         DateID_Final            BIGINT
  ,         Aux_Row_Number          INT
 )

INSERT INTO #ProductStoreChanges
(
            ID_InitialStore
  ,         ID_FinalStore
  ,         ProductID
  ,         value_1
  ,         value_2
  ,         DateID_Initial
  ,         DateID_Final
  ,         Aux_Row_Number
)

select      ISNULL(A.StoreID,-1)
,           ISNULL(B.StoreID,-1)
,           A.ProductID
,           A.value
,           B.value
,           A.DateID
,           B.DateID
,           ROW_NUMBER() OVER (Partition by B.ProductID Order by A.DateID)
from            #Trackings A
Join            #Trackings B
On              A.ProductID = B.ProductID
And             A.Aux_Row_Number + 1 = B.Aux_Row_Number
AND             ISNULL(A.StoreID,0) <> ISNULL(B.StoreID ,0)

select              A.ID_FinalStore,A.DateID_Final,B.DateID_Final,A.ProductID,B.value_2,A.value_2,B.value_2 - A.value_2 DeltaValue
from                #ProductStoreChanges A
Join                #ProductStoreChanges B
On                  (A.Aux_Row_Number + 1 = B.Aux_Row_Number)
And                 A.ProductID = B.ProductID
Order by            A.DateID_Final

Answer: OK, try this, using your updated sample data:
Declare @Trackings table
 (
   ProductID bigint
 , value    float
 , StoreID  int
 , DateID int
 , Aux_Row_Number int
 )

Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,1,325.2,1)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,2,326.2,2)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,3,329.6,3)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,4,335.2,4)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,5,336.5,5)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,6,338.3,6)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,7,339.2,7)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,8,342.1,8)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,9,343.7,9)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,10,355.0,10)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,1,12,385.0,12)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,13,485.0,13)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,14,985.0,14)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,15,1585.0,15)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,3,16,3585.0,16)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,17,5585.0,17)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,18,6585.0,18)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,19,8585.0,19)
Insert into @Trackings(ProductID,StoreID,DateID,value,Aux_Row_Number) Values (100,2,20,9585.0,20)
 ;
with t
as (select *, ROW_NUMBER() over (order by dateid) as rn
from @Trackings ),

cte1
    (Productid,
    Storeid,
    DateID,
    value,
    rn,
    set1)
as
    (select ProductID, StoreID, DateID, value, rn , 1
    from  t
    where rn = 1
union all
    select t.productID, t.storeID, t.dateID, t.value, t.rn,
    case when
        cte1.Storeid = t.storeID then cte1.set1 else cte1.set1+1 end
    from  t join cte1 on t.rn = cte1.rn+1)

 ,

t2 as (select Productid, Storeid, set1, MIN(CAST(DateID as int)) as tmi, max(dateid) as tma
from cte1
group by Productid, Storeid, set1)

select t3.Productid, t3.Storeid, t3.set1, t3.date_min, t3.date_max, u.value - t.value
from
(select a.Productid, a.Storeid, a.set1, a.tmi as date_min, coalesce(b.tmi, a.tma) as date_max
from t2 a left join t2 b
on a.set1 + 1 = b.set1) t3 join @Trackings t
on t3.date_min =  t.DateID
join @Trackings u
on t3.date_max = u.DateID
order by set1

The "Value" column confused me, as you are using commas (,) instead of periods (.) to separate the integer from the decimal part of your float.
Comment: Hey Mike. Thanks for helping me out. I am trying to modify your SQL Code to meet my needs here and it is not working. I Edited the post and added the "business rule" for this case. If I found a solution I will post here as well. Thanks.


Passing Argument from URL in Panel to View Pane or Block

Question: I have a page where I want to display all resources for a course grouped by taxonomy term. The courses are organic groups and the resources are materials belonging to those groups. I'm using panels to display the content and I'm overriding view_node for this. I have already created a view pane which lists all the different resource categories, and I'm now trying to list all the resources for a category.
The panel is using the following URL structure:
course/course-name/resources/resource-taxonomy-term
So for instance I have a URL
/course/test-course/resources/transport
I then want to display all resources that belong to the taxonomy term "transport". So I guess the URL argument I want to pass is %4.
I've tried for over a day now trying different methods to pass the URL argument to the view without success. I've tried using a view pane to display the results and also a view block, and explored various methods of passing the argument across without success. It works fine in the view itself, but when I put it in the panel it doesn't work. Can anyone show me how I can do it?
I'm using D7.18, ctools 7.x-1.0-rc1, panels 7.x-3.0 and views 7.x-3.7.
Comment: http://drupal.stackexchange.com/questions/20486/panels-node-template-with-additional-arguments/
Comment: http://drupal.stackexchange.com/questions/26978/using-panels-node-template-how-do-i-pass-additional-arguments-for-my-blocks
Answer: Example scenario:
There is a panel containing View Content Pane.
Panel URL: /panel_url
Example with argument: /panel_url/term_name
With BEF: /panel_url?category=123
How to set up (having existing panel and added Content Pane):

Add Contextual filter to the View.
E.g.: Views contextual filters taxonomy name
Change settings in 'View -> Pane settings -> Argument input' to load the argument 'From panel argument' (e.g. First).

Done.

In addition, if you're using Better Exposed Filters, you could do the following improvements.
To set the current active link based on the argument (if you're using select_as_links):
<code>/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select_as_links(&$variables) {
  $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
  $selected = end((arg()));
  if (array_key_exists($selected, $options)) {
    $variables['element']['#value'] = $options[$selected];
  }
}
</code>
To set the current active link based on the argument (if you're using select):
<code>/**
 * Implements hook_preprocess_[themeFunctionName]().
 */
function foo_preprocess_select(&$variables) {
  switch (arg(0)) {
    case 'panel_url':
      if (@$variables['element']['#name'] == 'category') {
        $options = isset($variables['element']['#options']) ? array_change_key_case(array_flip($variables['element']['#options']), CASE_LOWER) : array();
        $selected = end((arg()));
        if (array_key_exists($selected, $options)) {
          if ($variables['element']['#value'] <> $options[$selected]) {
            $variables['element']['#value'] = $options[$selected];
          } else {
            // drupal_goto('panel_url');
          }
        }
      }
    break;
  }
}
</code>
To make the links SEO friendly, you can try something like:
<code>/**
 * Implements hook_url_inbound_alter().
 */
function foo_url_outbound_alter(&$path, &$options, $original_path){
  if (arg(0) == 'panel_url') {
    // Convert URL like: /panel_url?category=29 into /panel_url/term_name (SEO friendly)
    $path_info = parse_url($path);
    switch (@$path_info['path']) {
      case 'panel_url/term_name':
      case 'panel_url/term_name2':
        $path = 'panel_url/all'; // Convert loopy urls into base url
    }
    if (strpos($path, '?category=') !== FALSE) { // Convert term id into human name
      list(, $tid) = explode('=', current(explode('&', $path_info['query']))); // get tid from URL
      $term_name = strtolower(taxonomy_term_load((int)$tid)->name);
      $path = '/panel_url' . '/' . $term_name; // See also: $path_info['path']
    }
  }
}
</code>
Comment: Thank you very much for your answer. It is really helpful to see the code and how it would be implemented. Thanks again.
Answer: I've managed to solve this problem. The solution is not exactly what I was hoping for but it works.
First of all I changed the URL argument to use the term id rather than the term name in the panel. Then in the view pane, instead of using "taxonomy term id from URL" in the "provide default argument" section of the context settings, I used "raw value from URL", and specified the path component. I also needed to set up basic validation to use the term id.
I'd still be interested to hear if there is a neater way of doing this where it would be possible to use the term name in the URL instead of the id.
Comment: Yes, you can pass the term name rather than ID. http://drupal.stackexchange.com/questions/9332/drupal-7-views-contextual-filters-taxonomy-name
Answer: In your view pane, create a relationship with the taxonomy term. Once you've done that create a contextual filter based on that relationship to pass the term name.
Set the filter to accept raw URL argument, set the item number in the path and that does it.
Answer: My trouble with getting the argument to pass was due to not understanding panels/page enough. I wrongly created a node (from basic page content type) expecting that I could edit it in panels to send the argument. Adding an argument in the url path always resulted in page not found.
What I later realized was that I needed go to Structure > Pages > Add custom page and then add content pane view to effectively pass the argument. Also needed to make sure that content pane view had argument input set correctly before was able to find it from the custom page.
I found where I went wrong when reading this tutorial: http://www.metaltoad.com/blog/passing-page-arguments-view-panes


Laravel reject function on nested collection

Question: I am trying to iterate my collection, which has nested collections, with the collection reject() function and return the original collection with the updated nested data.
So this is my quiz collection
{
 "id": 1,
 "title": "quiz 1",
 "questions": [
     {
         "id": 1,
         "quiz_id": 1,
         "question": "q1 - q1",
         "answers": [
             {
                 "id": 1,
                 "question_id": 1,
                 "answer": "answer to question 1"
             },
             {
                 "id": 2,
                 "question_id": 1,
                 "answer": "answer to question 1"
             }
         ]
     },
     {
         "id": 2,
         "quiz_id": 1,
         "question": "q1 - q2",
         "answers": [
             {
                 "id": 3,
                 "question_id": 2,
                 "answer": "answer to question 1"
             }
         ]
     }
 ]
}

Now I want to iterate through the questions and reject those that were already answered and exist in the result collection. I do so by using the reject() function
$quizResults = [
    {
        "id": 1,
        "user_id": 1,
        "quiz_id": 1,
        "question_id": 1,
        "answer_id": 1,
        "correct": 1,
        "created_at": null,
        "updated_at": null
    }
];

$filtered = $quiz->questions->reject(function ($value, $key) use ($quizResult) {
   return $quizResult->contains('question_id', $value->id);
});

I want to return the quiz collection with the updated questions (without the rejected questions), but I can't seem to figure out the correct way to accomplish this. (if i return just the $filtered variable i get the correct filtered results, however if i try putting it back in to the $quiz var it won't apply the rejected filter). If I just do
return $quiz

I will get the same original collection with all the questions as if I never ran the reject() function.
How do I make the $quiz->questions = $filtered; ?
Comment: can you give us an example of `$quizResult`? like your `$quiz`
Comment: @AndySong i added it to the edit, thx.
Answer: I had to unset the $quiz['questions'] first so it was like this
unset($quiz['questions']);
$quiz['questions'] = $filtered->flatten();
return $quiz;

and the result was as intended:
{
    "id": 1,
    "title": "quiz 1",
    "questions": [
        {
            "id": 2,
            "quiz_id": 1,
            "question": "q1 - q2",
            "answers": [
                {
                    "id": 3,
                    "question_id": 2,
                    "answer": "answer to question 1"
                }
            ]
        }
    ]
}

Answer: This is the min steps to reproduce your problem,
    $quizResult = [
        0 => [
          'id' => 1,
          'user_id' => 1,
          'quiz_id' => 1,
          'question_id' => 1,
          'answer_id' => 1,
          'correct' => 1,
          'created_at' => null,
          'updated_at' => null,
        ],
    ];

    $quiz = [
        'id' => 1,
        'title' => 'quiz 1',
        'questions' => [
          0 => [
            'id' => 1,
            'quiz_id' => 1,
            'question' => 'q1 - q1',
            'answers' => [
              0 => [
                'id' => 1,
                'question_id' => 1,
                'answer' => 'answer to question 1',
              ],
              1 => [
                'id' => 2,
                'question_id' => 1,
                'answer' => 'answer to question 1',
              ],
            ],
          ],
          1 => [
            'id' => 2,
            'quiz_id' => 1,
            'question' => 'q1 - q2',
            'answers' => [
              0 => [
                'id' => 3,
                'question_id' => 2,
                'answer' => 'answer to question 1',
              ],
            ],
          ],
        ],
    ];

    $filtered = collect($quiz['questions'])->reject(function ($value) use ($quizResult) {
        return collect($quizResult)->contains('question_id', $value['id']);
    });
    $quiz['questions'] = $filtered;

    return $quiz;

And this the result,
{
"id": 1,
"title": "quiz 1",
"questions": {
"1": {
"id": 2,
"quiz_id": 1,
"question": "q1 - q2",
"answers": [
  {
         "id": 3,
         "question_id": 2,
         "answer": "answer to question 1"
  }
 ]
}
}
}

I do not understand why you said it's returning original one.
Comment: yes thats what i am trying to achieve, the issue is return $quiz will just return both questions without applying the rejected filtered changes
Comment: @Mika can you give us an example of `$quizResult`? like your `$quiz`
Comment: $quizResults = [
    {
        "id": 1,
        "user_id": 1,
        "quiz_id": 1,
        "question_id": 1,
        "answer_id": 1,
        "correct": 1,
        "created_at": null,
        "updated_at": null
    }
];
Comment: @Mika, have you run the code I provided? it will give what you want, will not give you both.
Comment: yes i ran your code, still the same, if i return just $filtered i get one answer, but if i return $quiz even after doing your code i get both answers (in other words it goes back to its original)
Comment: @Mika, wait, you want to filter questions right? there is nothing to do with answers. am I right?
Comment: the answers belong to the questions so when the questions gets rejected so should the answer. Which happens when returning just the $filtered but for some odd reason not when I return $quiz even after I do $quiz->questions = $filtered. Your result in your answer is perfect, but I don't understand why that won't come out for me I'm doing exactly the same thing
Answer: Pass it by reference
$filtered = $quiz->questions->reject(function ($value, $key) use (&$quizResult) {
   return $quizResult->contains('question_id', $value->id);
});

Comment: its still returning the same original $quiz and not applying the reject function


How to Attach debbuger to process from the first line without compile code every time

Question: I'm trying save compiling time only for debug first app lines code.
There is solution to exit by backPress() and the process still running (and then i can attach debugger to process), but my debug scenario need to check app from start so i need to kill process before debug, which prevent me to attach debugger unless otherwise i'm compiling the app in debug mode.
Does any one know how to prevent compile in debug only for that?
Answer: go to settings -> Developer options -> Select app to be debugged -> choose your app
turn on 'Wait for debugger'
then when you launch the app you see this screen:

Now app wait for you to attach debugger and auto start when it's attached
It is actually start the app-process without start launcher activity


Thumbnail for website's link hosted by GitHub not showing on WhatsApp

Question: I have a website hosted by GitHub and I wanted the thumbnail of the website's link I am sharing to show while sending it. I have found resources online about sharing link and having the thumbnail showing but none of the solution I have tried worked.
Below is an example of what I have tried to use:

  <meta property="og:title" content="my-title" />
  <meta property="og:description" content="my-content" /
  <meta property="og:url" content="https://my-website/path/" />
  <meta property="og:image" itemprop="image" content="https://my-website/path/images/thumbnail.png" />
  <meta property="og:type" content="website" />

          <link itemprop="url" href="https://my-website/path/images/Thumbnail.png">

Comment: You haven't properly closed the second `meta` tag. I guess it's just a typo in your question, though
Answer: You have a type-o in the meta tag.
<meta property="og:description" content="my-content" /

Should be closed:
<meta property="og:description" content="my-content" />
                                                      ▲

Comment: I didn't even realize that. Thank you! It works now


Cache + random + hook_form_user_register_form_alter

Question: for a captcha purpose, I'm trying to set a random number in the hook_form_user_register_form_alter
For example :
function my_module_form_user_register_form_alter(&$form, &$form_state) {
    $random_case = rand(0, 3);
    $form["random"] = array(
        "#type" => "textfield"
        , "#title" => ""
        , "#disabled" => 0
        , "#value" => $random_case
        , "#description" => null
        , "#weight" => -2
    );
}

When cache is disabled it's working as intended.
when I enable the cache the random number is always the same until I flush all caches.
I tried to flush cache programmatically, but it doesn't seem to work. What can I do ?
if I put a
die($random_case);

It's working but I think it's because drupal can't put the hook inside the cache.
Best regards.
Answer: When the forms cached, it caches the original, unprocessed $form array, and the builder functions are not called again.
you can explicitly set cache off by setting $form_state['no_cache'] = TRUE;. Note that this has potential to break Ajax forms.
Comment: I found a hack but I wasn't totaly pleased. It was putting   $GLOBALS['conf']['cache'] = FALSE; inside the hook_init. I prefer and adopt your way. Thank you.


Como truncar decimal em X casas decimais?

Question: Estou utilizando o seguinte código, porém quando envio ex:'10.100' para 2 casas ele retorna '10.1', mas deveria ser '10.10'
    public decimal TruncarDecimal(decimal value, int decimalPlaces)
    {
        decimal integralValue = Math.Truncate(value);

        decimal fraction = value - integralValue;

        decimal factor = (decimal)Math.Pow(10, decimalPlaces);

        decimal truncatedFraction = Math.Truncate(fraction * factor) / factor;

        decimal result = integralValue + truncatedFraction;

        return result;
    }

Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Dá suporte sim, veja a documentação. Ali tem sem o parâmetro de casas decimais, com esta informação e até como deve ser o critério do arredondamento.
Math.Round(valorDecimal, 2);

Se o que deseja não é arredondamento então faça o Truncate() escalando:
Math.Truncate(100 * valorDecimal) / 100;

Coloquei no GitHub para referência futura.
Mas isto é basicamente o que está na pergunta.
Comment: Mas não posso arredondar, o Round altera o valor
Comment: Eu respondi o que estava na pergunta, agora você diz que não pode fazer o que pediu para fazer. Acho que a pergunta não está clara então.
Comment: eu citei o exemplo do Round que posso escolher as casas decimais, mas precisaria ser o truncate, so que eu pudesse escolher as casas, Quando utilizo o Math.Truncate(decimal), o parâmetro é apenas o valor.
Comment: O `Truncate()` também altera o valor, você precisa decidir se quer alterar o valor ou não. Por outro lado se é o `Truncate()` que quer usar, use ele, não sei o objetivo da pergunta nesta caso.
Comment: Vou tentar resumir pra você entender, eu faço multiplicações e os resultados dão ex: 1,64857, preciso retornar o valor com X casas decimais dependendo de cada caso, não vou mais dizer sobre truncate ou math, estou precisando fazer isto.
Comment: Se você não deixar claro o que quer não tem como responder do jeito que quer. Eu já coclqoeui duas possibilidades, se nenhuma das duas resolve, eu acho que e você não consegue dizer o que está errado com estas soluções. o problema é que você não sabe o que você quer fazer. Aí não tem como dar uma resposta, quando não se sabe qual é a pergunta. O que você perguntou foi respondido, se queria perguntar outra coisa, precisaria deixar claro.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/65850/discussion-between-bruno-rodrigues-and-bigown).
Answer: Experimente usar o
Math.Truncate

por exemplo:
using System;

class Program
{
    static void Main()
    {
        decimal a = 1.223M;
        double b = 2.913;

        a = Math.Truncate(a);
        b = Math.Truncate(b);

        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}

Saídas:
1
2

Agora se você precisa exibir o valor com duas casas decimais use o código:
decimalVar.ToString("#.##");

Mais informações sobre Math.Truncate veja esse link: https://social.msdn.microsoft.com/Forums/pt-BR/fbf78553-93ab-4a96-9e1b-39160df5d216/truncar-variavel-para-apenas-2-decimais?forum=vscsharppt
Comment: Se puder adicione um link com a referência de alguma documentação que explique o que é o `Math.Truncate`.
Comment: Adicionado o link https://social.msdn.microsoft.com/Forums/pt-BR/fbf78553-93ab-4a96-9e1b-39160df5d216/truncar-variavel-para-apenas-2-decimais?forum=vscsharppt
Comment: Eu preciso exibir exatamente com casas específicas, o truncate não deixa eu escolher o número de casas. E eu estou tentando fazer de forma genérica em um método que passo parâmetro de valor e número de casas decimais.
Comment: @BrunoRodrigues você precisa arredondar pra cima ou para baixo? Se sim, onde trabalhava a gente usava a soma de + 0.4 no valor, assim ele aumentava pra cima, se usar -0.4 ele diminui pra baixo... aí trunca de forma natural, não sei se é seu caso, mas experimenta testar


How to add symbols on smooth lines in a R's lattice xyplot?

Question: In a lattice xyplot with multiple smooth curves, I plotted curves categorized by color (y1, y2, y3 in blue; z1, z2, z3 in red).
If we consider the following simple data :
x<-1:50
y1<-rnorm(50,100,20)
y2<-rnorm(50,80,20)
y3<-rnorm(50,90,20)
z1<-rnorm(50,60,20)
z2<-rnorm(50,40,20)
z3<-rnorm(50,65,20)

we can make such a plot with smooth lines and specify colors with this code:
xyplot(y1+y2+y3+z1+z2+z3~x,type='smooth', span=0.4,
par.settings=list(superpose.line=list(col=c('blue','blue','blue','red','red','red'))))

and we get this result:

My question : Do you know how to add symbol (markers) on each curves to identify it ?
For instance, y1 with a triangle marker in blue, y2 with a square marker in blue, etc.
It is easy to do this when raw data is plotted, but I can't find how to do it with smooth curves. I tried to use superpose.symbol but it seems that it's works only when type=c('p','smooth'). But in this case, symbols are not on the curves but in the raw positions.
NB. I tried to identify the curves with different line type (cf. lty) but but the result does not allow a good visualization with my data.
Comment: This IMO is better suited for SO, did you check out the [lattice questions over there](http://stackoverflow.com/search?q=%5Br%5D+%5Blattice%5D+label). Some examples over there may be pertinent to your example.
Answer: Here is a way to achieve this:
library(lattice)
library(gridExtra)

my.df <- data.frame(y=c(y1, y2, y3, z1, z2, z3),
                    g=gl(6, 50), x=rep(x, 6))

my.panel.loess <- function(x, y, span=2/3, ...) {
  loess.fit <- loess.smooth(x, y, span=span)
  panel.lines(loess.fit$x, loess.fit$y, ...)
}

pp <- list()
pp[[1]] <- xyplot(y ~ x, data=my.df, groups=g, type="b",
                  col=rep(c("blue","red"), each=3), cex=.6,
                  panel=function(...)
                    panel.superpose(panel.groups=my.panel.loess, ...))

pp[[2]] <- update(pp[[1]], span=1/5)
pp[[3]] <- update(pp[[1]], col=1:6, type=c("p", "g"))
pp[[4]] <- update(pp[[1]], pch=rep(c(2,6), each=3))

do.call(grid.arrange,  pp)

You will notice that I had to briefly define a custom panel function for the smoother. This is because I need to pass an extra parameter to panel.lines ("p"+"l"="b"); note that it cannot be used directly when calling panel.lines since this formal parameter is already defined in xyplot.
The rest of the code is pure drawing with varying parameters (all digested through the ... argument). Although I arranged your data in a more convenient data.frame, I believe your original formulation will work with slight adaptation around the call to panel.groups.

However, you can annotate the curves directly with the directlabels package (a lot of examples are available on R-forge). Something along those lines should work fine:
library(directlabels)
pp0 <- xyplot(y ~ x, data=my.df, groups=g, type="smooth")
direct.label(pp0, "follow.points")

I should note that there is a nice function, labcurve(), in the Hmisc package that does pretty much the same job.
Comment: `labcurve` is called by the Hmisc package's `xYplot` function to make this even easier.


How to retain variable in arc in every class

Question: I have a lot of classes which are sending requests and finally it all comes to SplitViewController. In the SplitUIviewclass I have to long poll and write the data in a table view. The long polling is done in the background thread, so I have declared a variable in app delegate, but when it comes to that it is nil. And the problem is whenever I try to access the NSMutablearray through the appdelegate, its coming as nil and the array is being released. My code for long polling is
- (void) longPoll {

@autoreleasePool
{
//compose the request
NSError* error = nil;
NSURLResponse* response = nil;
NSURL* requestUrl = [NSURL URLWithString:@"http://www.example.com/pollUrl"];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];

//send the request (will block until a response comes back)
NSData* responseData = [NSURLConnection sendSynchronousRequest:request
                        returningResponse:&response error:&error];

//pass the response on to the handler (can also check for errors here, if you want)
[self performSelectorOnMainThread:@selector(dataReceived:)
      withObject:responseData waitUntilDone:YES];
}

//send the next poll request
[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) startPoll {

[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) dataReceived: (NSData*) theData {
//i write data received here to app delegate table
}

If I call any other method in my SplitView class from data received, I'm losing control, also I cannot print my app delegate values in data received or the variables being released, I cannot call reload table or any other method from here.
Comment: set your property as strong/retain
Comment: Can you print "theData" in dataRecieved: method? Is it correct? If so you need to post more code.
Comment: i can print the theData in dataRecieved and sure give me some time ill post d complete problem
Answer: Cant you set your properties in your ViewControllers as strong/retain like so
property (strong,retain) NSMutableArray *myData;
BTW, I learned a moment ago that it is bad practise to use your AppDelegate as a storage place for global containers. The ApplicationDelegate is a place for application delegate methods and for the initial setup of the foundation of your app; such as setting up the navigationController.
So consider storing your data in the appropriate place, perhaps core data or something else.


Can I search for parent nodes from deep child nodes using Views?

Question: I've a complicated hierarchy of nodes.
Node A contains(by node reference) multiple B nodes, each B contains multiple C nodes and so on.
Using Views will it be possible to reach C from A or vice versa given even higher depth level?
I think this is independent of D6/D7 views but I'm on D6.
There will be thousands of such nodes. Each top level A is an organization and there are a 1000 of them now. Information about each employee or department will be held in File(aka file cabinet) which again is a node).
I want to give users facility to search information from one end to another.
Update: The parent to child relationship is one to many
Answer: You can probably do it with the Corresponding Node References module. Otherwise you can't do reverse references at all. You'll use relationships, of course, to go both ways.
Comment: Thanks for this module which is really useful. But what I want to know if we can join view relationships than 2 levels. In SQL it'd be joining 3 or more tables together
Comment: Views can do relationships at more than one level.
Comment: what about 2-5 levels? Do you have an example?
Comment: I've parent-child one to many relationship and just now realized both side node reference will not be possible with these modules that is from parent to child and vice versa since parent will then need to have unlimited node reference to children
Answer: You have a bunch of options.  I am using noderelationships and thinking of pairing it with reverse_node_reference.
I'd look into these modules.
D6: http://drupal.org/project/noderelationships
D6: http://drupal.org/project/reverse_node_reference (See http://drupal.org/node/798786 for some good insight)
D6, D7: http://drupal.org/project/cnr
D6: http://drupal.org/project/nodereferrer
D6: http://drupal.org/project/backreference
D6: http://drupal.org/project/partners
D7: http://drupal.org/project/references
Comment: With these modules when given C you should be able to find A.  And Given A you should be able to see all B -> C combinations.   Having those two cases in a single View is probably not possible with these modules.
Comment: You'd most likely have multiple D nodes.  You'd have to set up a View "Relationship" for each step using the node reference fields.  Meaning you'd need a View "Relationship" for A->B, then one from B->C, and then one for C->D.
Comment: Which one do you recommend and why?
Comment: reverse_node_reference is the one I am pursuing because of what is said in this comment, http://drupal.org/node/798786#comment-2966208
Comment: I've parent-child one to many relationship and just now realized both side node reference will not be possible with these modules that is from parent to child and vice versa since parent will then need to have unlimited node reference to children
Comment: Given A's information how to show information of D in Views? When the relationship(1 to many) A->B->C->D


REST on *just* IIS7 (without a webframework)

Question: I want to upload files directly to IIS7 (in this case I am using the WebRequest object in .NET). Thus I need IIS7 to accept POST, PUT, and DELETE verbs such that I can upload and delete files on the server directly. Is it possible to have IIS accept files without a a web framework like ASP.NET? Essentially I want to be able to use IIS (HTTP) as an FTP server.
Answer: A web server by itself is not designed to do this, which is why the frameworks exist.  The closest option is to install and configure WebDAV.  WebDAV gives you most of the functionality you ask for.
The WebDAV module for IIS 7/7.5 appears to be completely rewritten to work with the new architecture of IIS 7.  Here's a link for the download and instructions for installing and configuring it.
Installing and Configuring WebDAV on IIS 7
Answer: It looks like Joseph Fultz has a blog post on MSDN on how to enable those verbs in IIS 7.
Answer:
Is it possible to have IIS accept
  files without a a web framework like
  ASP.NET?

No. Especially given that IIS7 is in large parts written in .NET - what would be the sense of that? Driving a car without using any fuel?
If you would rup out the .NET framework (which ASP.NET is integral part of) IIS would not even start.
Comment: IIS 7 is native code - the .Net bits are all optional.


How to understand and carry out the "score bootstrap"?

Question: I want to translate the "score bootstrap" that Kline and Santos (2011) propose into R code. The algorithm is described on page 6 as follows.

STEP 1: Obtain the full sample OLS estimate $\hat\beta$ and employ it
to generate the fitted score contributions
$\{X_i(Y_i-X^{'}_i\hat\beta)\}^n_{i=1}$.
STEP 2: Using an i.i.d. sample of random weights $\{W_i\}_{i=1}^n$
independent of $\{Y_i,X_i\}_{i=1}^n$ and satisfying $E[W_i]=0$ and
$E[W^2_i]=1$, construct a new set of perturbed score contributions
$\{X_i(Y_i-X^{'}_i\hat\beta)W_i\}_{i=1}^n$.
STEP 3: Multiply the constructed perturbed score by the inverse
Hessian to obtain $H_n^{-1}n^{-\frac12}\sum_i(Y_i-X_i\hat\beta)X_iW_i$ and use its distribution conditional on $\{Y_i,X_i\}_ {i=1}^n$ as an
estimate of the distribution of $\sqrt{n}(\hat\beta-\beta_0)$.

STEPS 1 and 2 seem to be straightforward.
set.seed(42)
n <- 100
x <- rnorm(n)
y <- x + rnorm(n)

fit <- lm(y ~ x)

X <- model.matrix(fit)
yhat <- fit$fitted.values  # Xb

S <- X*(y - yhat)  # score matrix
H <- - solve(vcov(fit))  # hessian
w <- ifelse(runif(n) < .5, 1, -1)  # draws from Rademacher distr.

However, when I attempt to calculate STEP 3, I'm getting an error, because the number of columns of $H^{-1}$ won't match with the number of rows of $S$.
# sqrt(n) * solve(H) %*% S * w  # STEP 3
## Error in solve(H) %*% S : non-conformable arguments

Does anyone see if I'm maybe misinterpreting the math somewhere?

##Edit
I obviously made an error with the multiplication in STEP 3, where I need to take account of the $\sum$, i.e. colSums of the perturbed scores. Thus, after STEP 3 I get this result:
solve(H) * sqrt(n) * colSums(S * w)  # STEP 3
#             (Intercept)           x
# (Intercept)  1.15362358 -0.03490467
# x            0.04228051 -1.30034588

To verify the result I set $w=1$, i.e. I don't apply any weights, and I get essentially zero.
w <- 1
solve(H) * sqrt(n) * colSums(S * w)
#               (Intercept)            x
# (Intercept) -4.149004e-16 1.255345e-17
# x           -3.034329e-19 9.332144e-18

This feels right, because the sum of the scores is (by definition) zero, too:
colSums(S)
#  (Intercept)             x
# 5.023759e-15 -1.214306e-16

###Where I'm stuck
However I'm not sure what I'm actually getting here. According to the algorithm I have an "estimate of the distribution of $\sqrt{n}(\hat\beta-\beta_0)$". I know this has to do with maximum likelihood, but how to derive my variance estimator from this? If the result is already my variance matrix, then taking the square root of the diagonal should give me standard errors similar to those of the model summary, but they're pretty off:
sqrt(diag(solve(H) * colSums(t(S) %*% S) * solve(H)))
# (Intercept)           x
#  0.06225221  0.07737588

summary(fit)$coe[, 2]
# (Intercept)           x
#  0.09087774  0.08766507

Is this the wrong interpretation of the estimate of $\sqrt{n}(\hat\beta-\beta_0)$? Did I make an error in interpreting the equations? What I finally need is the test statistic of one bootstrap iteration, and I am not sure how to get it out of the equation of STEP 3.
Note: I'm asking for statistical help (distinct from programming help) to understand how to derive a variance estimator from the estimate of $\sqrt{n}(\hat\beta-\beta_0)$ of STEP 3.
For sake of completeness below the formula for the test statistic of the score bootstrap given in the paper on page 7.
$$T_n^{*score}:=\left(H_n^{-1}\sum_{n}^*(\hat\beta)H^{-1}_n\right)^{-\frac12}H^{-1}_n\frac1{\sqrt{n}}\sum_{i=1}^nX_i\epsilon_i^*,\quad where \quad\sum_n^*(\beta) := \frac1n\sum_iX_iX_i^T(Y_i^*-X_i^T\beta)^2$$
Comment: Replace `X*(y-yhat)` by `apply(X, 1, \`*\`, y-yhat)`
Comment: @AdamO When I run this line in conjunction with the rest of the OP's code, I still get a conformability error...
Comment: @compbiostats you need to use `dim` to debug your code. It's a good R skill. Your implementation isn't wrong from a stat side, you just need to sooth out your code. So probably off topic here.
Comment: Looks like $X$ should be transposed so that matrix columns and rows are conformable. Doing this, the code runs smoothly without errors.
Comment: @AdamO Thanks. Yes, I see that on comparing S[1,] with y - yhat.
Answer: $X$ (the model matrix) is a $n \times 2$ matrix. $y-\hat{y}$ is a $n \times 1$ vector.
The * operator in R is not generic, meaning it can't figure out $X$ is a matrix for you, so it just recycles the multiplication over a $2n$ vector of the entries of $X$ by column. Not the desired output.
Research %*% and apply and study the output carefully.
Comment: @jay.sf I think you're right. an earlier comment suggested transposing `X` and naively I had that in my workspace. However, my comment on good coding practice is still well, warranted: don't trust R's recycling for matrix operations. Use `%*%`, `sweep`, and `apply`.
Comment: This is not right, `X*(y - yhat)` yields exactly what it should yield. Compare the output of `sandwich::estfun(fit)` which is designed to yield the scores, see _@AchimZeileis_'s [answer](https://stackoverflow.com/a/30280035/6574038) on Stack Overflow.


JS Auto Scroll Code Only Works as Part of HTML but Not as Separate Script in JSFiddle

Question: Good day Masters.
I need your help with below code. The target outcome is to auto scroll the page from top to bottom then jump to top once at the bottom and repeat again and again.
The auto scroll code is working as expected in JSFiddle when ran as part of the whole HTML enclosed within "script" portion.
The problem would occur when I removed it from the whole HTML and placed it in JavaScript window in JSFiddle.
The Code:

          var currentpos=0,alt=1,curpos1=0,curpos2=-1
          function initialize(){
          startit()
          }
          function startit(){
          const itemsElement = document.getElementById("Units");
          setInterval(
          function () {
          if (itemsElement.all)
          temp=itemsElement.body.scrollTop
          else
          temp=window.pageYOffset
          if (alt==0)
          alt=1
          else
          alt=0
          if (alt==0)
          curpos1=temp
          else
          curpos2=temp
          if (curpos1!=curpos2){
          if (itemsElement.all)
          currentpos=itemsElement.body.scrollTop+1
          else
          currentpos=window.pageYOffset+1
          window.scroll(0,currentpos)
          }
          else{
          currentpos=0
          window.scroll(0,currentpos)
          }
          }
          ,50)
          }
          window.onload=initialize

          <title>Auto Scroll Test Page</title>

Unit 1

Unit 2

Unit 3

Unit 4

Unit 5

Unit 6

Unit 7

Unit 8

Unit 9

Unit 10

Unit 11

Unit 12

Unit 13

Unit 14

Unit 15

Unit 16

Unit 17

Unit 18

Unit 19

Unit 20

Thanks in advance everyone for the help on this.
Have a great day :)
Answer: In JSFiddle in JavaScript window click on options (it will be something like: JavaScript + No-Library (pure JS) ). Then under load type change it to No wrap - bottom of
Comment: Thank you very much @Kalimah, it's working in JSFiddle now.

My next step is to apply it to visual.ts in creating Microsoft Power BI Visual. Can't seem to make it work there.

Thanks


Will a forte tympani overpower a quiet orchestra?

Question: So far, I have been mainly using the tympani in my orchestration of the Pathétique Sonata for the purpose of adding an accent. It might change later on to having a more important role but right now, it is just an accenting instrument. Because of this, I feel that I can give plenty of time for the tympanist to retune the drums if I have to to keep the accent consonant with the rest of the orchestra. I also think that most likely the tympanist would have tympani pedals to raise the note without retuning the instrument. So far, I have been keeping it forte because of its accenting purpose.
But I'm wondering whether it would simply overpower an orchestra that is at piano if the tympani stays at forte. I mean, the distance between the tympani and the woodwinds and strings and the sheer power of the brass makes me think: "No, of course not. It is too far from the more mellow instruments of the strings and the woodwinds to overpower them. Besides, the brass, even at a piano dynamic is very powerful, especially if you include the heavy brass (tuba and trombones) as I do in my orchestration."
But, am I right in that assessment? Or should I lower the dynamics of the tympani a bit to something like mezzo piano when the orchestra is at piano so that it still sounds accented, but not overpowering?
Comment: "tympani pedals to raise the note without retuning the instrument."  What does this mean?
Answer: Yes, timps at forte would dominate an orchestra at piano.  Give them the same dynamic as the rest of the orchestra unless you're looking for a special effect.  If you want accents, write accents.
If the timps are too loud when seated next to the wind, they're still too loud if seated several yards away.  Don't over-think this!
"...tympani pedals to raise the note without retuning the instrument..."  More confused thinking I'm afraid.   The pedals are HOW the player 'retunes' his kettles.
Trombones can play very loudly, but also very softly.


Need to Encrypt a Binary .bin file that an automotive computer or EEC uses to operate the engine

Question: I personally tune ford cars or modify the factory binary files used by the cars ECM. recently a company has developed a way to connect to the car via OBD2 port and read the file off of the ECM. they then can modify it and re flash it to the ECM.
as such thousands of hours of my hard work will be up for grabs by anyone. I am looking to protect my work and not harm any cars in the process. as well as tuning cars I am an IT professional and am working with a programmer to accomplish this task. just thought I would ask here to get some basic information.
items I know: the computer uses a Binary file with a header. it is a .bin file, the ECM actively reads the binary to operate the engine and other parameters in real time.
is there a way to encrypt the file so that the ECU can read it but if an outside source tries to read / remove / alter the file it would be encrypted or locked?
Comment: You can't stop them reading it but you can make it difficult. Eg corrupt the osid so standard packages don't know how to edit it. Nothing stopping them copying it completely though. Drm is always crackable able with enough time.
Comment: btw, is there any way to read ECU .bin files (as human readable) and make changes. etc. ? Looking tor something that helps me changing my car's file without any cost of going to dealer and paying him for that. I'm new to this cars things, so any direction/guidance appreciated.
Answer: The ECU would need to have the ability to de-code whatever type of encryption you used in the first place otherwise it won't be able to make any use of it. This would probably appear as a bad/corrupted ECU flash.
As far as I know, no one is hard coding OTF encryption into their ECUs.
If you somehow added to the ECU code to allow for OTF encryption, someone could simply dump your BIN file and read the un-encrypted portion that the ECU would run to decrypt your tuning. This would probably be enough to reverse engineer your encryption technique and give them access to your tuning. I would suggest not trying to add encryption code to the ECU programming, the ECU was never designed to run such things.
I think this sounds like a scenario where someone has found a better way to achieve something, in this case flash ECUs. This makes it easier to retrieve your custom tune, and there isn't much you can do about it.
Even if you could encrypt your tuning, how many cars are already driving around with it? Would they all return just so you can re-flash your encrypted tuning and thus lock them out from using the new, easier OBD2 method? That sounds like a recipe for angry customers.
My advice would be embrace the future and learn the OBD2 method. DRM never works and the hackers/crackers/thieves will always beat you.


The lattice of closed subsets of an algebraic closure operator is an algebraic lattice

Question: Let $A$ be a set. Let $C:Su(A)\longrightarrow Su(A)$ be a function, where $Su(A)$ denotes the set of all subsets of $A$. Suppose that
1) $X\subseteq C(X)$
2) $X\subseteq Y\rightarrow C(X)\subseteq C(Y)$
3) $C^2(X)=C(X)$
for every $X,Y\subseteq A$.
Let $L_C$ be the set of all $C(X)$, $X$ varying in $SU(A)$. Then $L_C$ is a poset, with $\subseteq$ as partial order, $L_C$ is also a lattice, with the two operations:
$$\bigvee C(A_i):=C(\bigcup_iA_i)$$
$$\bigwedge C(A_i):=\bigcap_iC(A_i)$$
Suppose now that $C$ satisfies the further property:
4) $C(X)=\bigcup \{C(Y): Y\subseteq X \textrm{ and } Y \textrm{ is finite }\}$, for every $X\subseteq A$.
I want to prove that $C(X)$ is compact if and only if $X$ is finite. I recall the definiton of compactness in this context: an element $a$ in a lattice $L$ is compact iff, whenever $a\leq\bigvee A$ for some $A\subseteq L$ then $a\leq\bigvee B$ for some finite $B\subseteq A$. I am able to prove that $X$ finite implies $C(X)$ compact, but I can't prove the converse. My textbook says what follows: suppose $C(Y)$ is not equal to $C(X)$ for any finite $X$. From
$$C(Y)\subseteq\bigcup\{C(X):X\subseteq Y\textrm{ and } X \textrm{ is finite }\}$$
it is easy to see that $C(Y)$ cannot be contained in any finite union of the $C(X)$'s, hence $C(Y)$ is not compact.
I can't undersand the last sentence: $C(Y)$ cannot be contained in any finite union of the $C(X)$'s. Why?
Answer: Assume that $C(Y) \subseteq \bigcup_{i = 1}^n C(X_i)$ for some family of finite subsets $X_i \subseteq Y, i = \overline{1, n}$.
It follows that $C(Y) = \bigcup_{i = 1}^n C(X_i)$. (Why we have the inverse inclusion?)
Hence $C(Y) = C(C(Y)) = C(\bigcup_{i = 1}^n C(X_i)) = \bigvee_{i = 1}^n C(C(X_i)) = \bigvee_{i = 1}^n C(X_i) = C(X)$, where $X = \bigcup_{i = 1}^n X_i$ is a finite subset of $Y$. So we get a contradiction with  ''$C(Y)$ is not equal to $C(X)$ for any finite $X$''.


How to find element using two link texts that are separated (using Selenium's find element by link text function)

Question: I want to find elements using two partial link texts. I want to do this to separate instances where the first link text is the the same as another one.
For example if link text 1 for an element is "Publix Eggs, Large" and link text 2 is "12 ct", and link text 1 for another item is also "Publix Eggs, Large" but its link text 2 is "18ct" I want to be able to find only the first items element if I were to write something like below:

EXAMPLE HTML
Comment: Welcome to Stack Overflow. [Please don't post screenshots of text](https://meta.stackoverflow.com/a/285557/354577). They can't be searched or copied, or even consumed by users of adaptive technologies like screen readers. Instead, paste the code as text directly into your question. If you select it and click the `{}` button or Ctrl+K the code block will be indented by four spaces, which will cause it to be rendered as code.
Answer: You can do that with xPath.
//a[contains(.,'Publix Eggs, Large') or contains(.,'12ct')]

however, if you are just concerned about fetching the first element, then you can use
find_element
link = driver.find_element(By.PARTIAL_LINK_TEXT, "Publix Eggs, Large")
link.click()

Note that even though there are multiple matching nodes in HTML, it will always pick the first one.
Using find_elements
links = driver.find_elements(By.PARTIAL_LINK_TEXT, "Publix Eggs, Large")
links[0].click()

Comment: doesn't  the "or" in the first solution find the element with one or the other? I want something that finds the element with both "Publix Eggs, Large" and "12 ct" ignoring whether or not it is the first item because I will be for looping it. Because of that the texts being looped need to be unique which is why I want both "Publix Eggs, Large" and "12 ct" because that will make it unique.
Comment: `doesn't the "or" in the first solution find the element with one or the other? ` - it depends on how do you use them? if you would use `find_element` it's gonna return the first matching node irrespective of `or`. If you want that be unique use `and`, it should only look for both the condition `//a[contains(.,'Publix Eggs, Large') and contains(.,'12ct')]`


How to insert table view inside another view?

Question: I have created a View and two display blocks inside the View and set the format to table on each.
like this:

I will display these two tables at the front page. Now I need to write a common  for both tables

For this may I need to use table view inside another view?
My tables looks like this
Answer: You should be able to put services view block reference into your members view block for example into Header / Footer. Then by overriding template for this view type view-view--<views_machine_name> you can easily add Bootstrap classes and wrap each table into specific container / wrapper.
In your main view click on button Add at Header section. Add Rendered entity - block and type in your second block block_machine_name (it means your second block needs to be added to some region with specific machine name).


Proving that a linear isometry on $\mathbb{R}^{n}$ is an orthogonal matrix

Question: I wish to prove that if $T:\mathbb{R}^{n}\to\mathbb{R}^{n}$ is defined by $T(v)=Av$ (where
$A\in M_{n}(\mathbb{R})$) is an isometry then $A$ is an orthogonal
matrix.
I am familiar with many equivalent definition for $A\in M_{n}(\mathbb{R})$
to be orthogonal, and it doesn't matter to me which one to show.
What I tried to do is the following:
$||x-y||=||Ax-Ay||\implies\langle x-y,x-y\rangle=\langle Ax-Ay,Ax-Ay\rangle\implies\langle x-y,x-y\rangle=\langle x-y,A^{t}A(x-y)\rangle$,
from here I thought that I will be able to deduce $A^{t}A=I$ and
complete the proof, but I was unable to do so.
How can I complete the proof, or prove this in another fashion ? Help
is appreciated!
Comment: So you now that $\langle z, A^tAz \rangle = \langle z,z\rangle$ for every $z$. Try to let $z = x \pm y$ and expand ...
Answer: For every $x, y \in \mathbb{R}^n$ we have
$$
\langle Ax,Ay\rangle=\frac{1}{4}\left[|A(x+y)|^2-|A(x-y)|^2\right]=\frac{1}{4}\left[|x+y|^2-|x-y|^2\right]=\langle x,y\rangle.
$$
Hence, for every $x,y \in \mathbb{R}^n$ we have
$$
\langle A^TAx,y\rangle=\langle x,y\rangle,
$$
i.e. $A^TA=I_n$.
Answer: We know that $\,\langle\, x,y\,\rangle =0\,\,\,\forall\,y\Longleftrightarrow x=0\,$ , so
$$\forall x,y\,\,:\,\langle\,x,y\,\rangle=\langle\,Ax,Ay\,\rangle=\langle\,x,A^tAy\,\rangle\Longrightarrow \langle\,x,(A^tA-I)y\,\rangle=0$$
$$\Longrightarrow (A^tA-I)y=0\,\,\,\,\forall y\,\,\Longrightarrow A^tA-I=0\Longrightarrow A^tA=I$$
Comment: @Belgi , it's the same: $$||x-y||=||Ax-Ay||\Longleftrightarrow \langle x-y,x-y\rangle=\langle Ax-Ay,Ax-Ay\rangle$$ Now just use linearity of inner product
Comment: @Belgi By definition of being an isometry.
Comment: Why $\langle x,y\rangle=\langle Ax,Ay\rangle$ ?
Comment: @MTurgeon, how's that ? I am given the definition that $f$ is an isometry if $d(x,y)=d(f(x),f(y))$ where in this case $d(x,y):=||x-y||$