Second derivative of f(x,y)

Question: I try do finde the Matrix $D^3f(a)$ where $f(x,y)=x^4-3x^3y^2$
What i tried is
$Df(x,y)=\left( \begin{array}{c}
4x^3-9x^2y^2 && -6x^3y\\
\end{array} \right)$
This is a $1\times 2 $ matrix.
Then following this post
I get:
$
D^2f(x,y)=
\left( \begin{array}{c}
12x^2-18xy^2 && -18x^2y && -18x^2y && -6x^3\\
\end{array} \right)
$
and
$
D^3f(x,y)=
\left( \begin{array}{c}
24x-18y^2 && -36xy^2 && -36xy && -18x^2 &&
36xy && -36x^2 && -18x^2 && -18x^3\\\\
\end{array} \right)
$
which is a $8\times1$ matrix.
I have troubles by understanding how to get $D^rf(x,y)$ for arbitrary functions
Comment: Do you mean you want to find the Hessian?
Comment: No, I have a problem where the Hessian becomes zero and the first non-vanishing term is $D^4f(0,0)$ but I don't know how to compute $D^4f$
Comment: Well, do you necessarily need to write down $D^4f$? It should be enough to compute the $4$-th derivatives of $f$ at $(0,0)$ to see what you say, shouldn't it?
Comment: I ultimatly want to know if the function $f$ has a lokal extremum in $(0,0)$. For this i think need $D^4f(0,0)$
Answer: What you are looking for is called the Hessian matrix. You can read more on wikipedia here.
Basically it allows you to have a matrix in which all of the variables of your multivariable function are partially derived. The Hessian for a 2 variable function with be: $$\pmatrix { \frac { \partial^2f }{\partial x^2 }& \frac {\partial^2f}{\partial x \partial y} \\ \frac {\partial^2f}{\partial y \partial x } &\frac { \partial^2f }{\partial y^2}  }$$
Comment: When the second order derivatives vanish, I can't use the Hessian. In those cases I need the higher order derivative $D^rf$. I try to edit my question
Comment: I have $$
\nabla ^2f\left( x,y \right) =\frac{\partial ^2f\left( x,y \right)}{\partial x^2} + \frac{\partial ^2f\left( x,y \right)}{\partial y^2}
\\
\frac{\partial ^2f\left( x,y \right)}{\partial y^2} = f(x+1,y) - 2f(x,y) + f(x-1, y)
$$

Why we have $\frac{\partial ^2f\left( x,y \right)}{\partial y^2} = f(x+1,y) - 2f(x,y) + f(x-1, y)$ please?
Answer: About your last comment: you can observe that $f(x,y) = x^3(x-3y^2)$. So in the half plane $x \geq 0$ you have that $f \geq 0$ if $x \geq 3y^2$ or $x=0$, otherwise $f < 0$. If $x < 0$, then $f$ is a sum of a non-negative and a positive term, so $f(x,y) > 0$. So $(0,0)$ is not a local extremum.

Second derivative of f(x,y)


close previous dropdown in jquery not working

Question: I have a menu in my WordPress theme, I have to close the previous dropdown and open current dropdown, I tried bwelow script but it not working.
Would you help me out ?

$('ul#left-primary-menu li').on('click', function(e) {
  e.preventDefault();
  //$(this).find('> ul').slideToggle();
  if (!$(this).next('.sub-menu').is(':visible')) {
    $('.sub-menu').hide(500);
    $(this).next('.sub-menu').slideToggle('fast');
  }
});
ul#left-primary-menu ul.sub-menu {
  display: none;
}

Home

Tech

Headphones

Smartphones

Accessories

Access1

Access2

Access3

Footwear

Rain Boots

Answer: Use find() instead of next() while searching for .sub-menu

$('ul#left-primary-menu li').on('click', function(e) {
  e.preventDefault();
  //$(this).find('> ul').slideToggle();
  if (!$(this).find('.sub-menu').is(':visible')) {
    $('.sub-menu').hide(500);
    $(this).find('.sub-menu').slideToggle('fast');
  }
});
ul#left-primary-menu ul.sub-menu {
  display: none;
}

Home

Tech

Headphones

Smartphones

Accessories

Access1

Access2

Access3

Footwear

Rain Boots

Comment: Sorry for the late reply, Yes, It's working. Thanks for the help.
Answer: I'd go with something like this. Add classes and go away from psuedo selectors. It's a bit of jQuery chaining, but this is a quick POC.
const $menu = $('ul#left-primary-menu');
const $menuItem = $('ul#left-primary-menu li');
$menuItem.on('click', function(e) {
  e.preventDefault();
  $menu.find('li.active').removeClass('active').find('.sub-menu').slideToggle('fast');
  $(this).addClass('active').find('.sub-menu').slideToggle('fast');
});

Comment: You might want to add `.not(this)` to the first jQuery chain to ensure that both statements don't try to act on the clicked element.
ie: `$menu.find('li.active').not(this).removeClass('active').find('.sub-menu').slideToggle('fast');`


PAC learning theory and lower bound on the amount of input samples

Question: I am trying to answer the following question: "How much (binary) data do I need for my learner to have seen every variable of the dataset at least once?" In my set-up I am feeding my algorithm binary vectors (i.e. with all elements equal to either 1 or 0), these vectors have a known 'density' (average amount of ones) which - for the purpose of answering this question - are uniformly constant (ok) or follow a long tailed distribution (better). I have tried looking at it from the perspective of combinatorics but this was harder than expected. I suppose this question must have been asked before, but I have not been able to find any references so far.
In "A theory of the Learnable" by Valiant, I read that:

Let L(h,S) be the smallest integer such that in $L(h,S)$
  independent Bernoulli trials each with probability at
  least $h^{-1}$ of success, the probability of having fewer
  than $S$ successes is less than $h^{-1}$. [...]
  PROPOSITION: For all integers $S > 1$ and all real $h > 1$.
  $$L(h,S) \leq 2 h (S + \ln (h))$$

This can be translated to an upper bound for my question given that each feature is assumed to be drawn from an independent Bernoulli trial, but not a lower bound. Does anyone know of other related work that could point me towards a lower bound?
Comment: What is $h$, $S$ and $L$?
Comment: Hi, I have updated the question and added a reference to the original manuscript, hopefully it will be clearer now.
Answer: To answer my own question, it is easy to get a lower bound when you assume that all variables are uniformly distributed. Then the probability of this event (let's call it A) becomes:
$$
P(A)  = 1 - P (X_1 = 0, X_2 = 0, \ldots, X_n = 0) \\
      = 1 - \prod P(X_i = 0)  \quad \quad \quad \quad \quad\\
      = 1 - \left[ \binom{n}{k}\,\theta^{k} (1-\theta)^{n-k} \right]^m  \quad\\
      = \cdots \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad \quad
$$
The solution for non-uniform distributions can be found by compounding the Bernoulli distribution with an a priori Beta distribution.


Shuffling data for machine learning

Question: I've come across a lot of posts suggesting shuffling data for certain machine learning models. Are there any downsides to this? Should this be a standard practice regardless of the model? I'm curious to know this, because there are a few approaches for which there is no literature on shuffling, so if there is no downside, it might be better to do it anyway.
Comment: It's never a good idea to follow a practice *blindly*. If there is an order that might be relevant in your data, you should typically try to preserve or model ist (e.g., if you have time series, or if you want to predict customer behavior based on each customer's prior history).
Answer: If by shuffling you mean changing the order of rows in a dataframe or changing the order in which the model is given training data, then this primarily matters for models that are trained using batches of data.
A typical example is neural networks for images. A typical approach is to run a batch of say 32 images (when there might be 50,000 in total) through the model, update the parameters a little bit, run the next batch trough etc. until all images have been used. A complete run through all data batch-by-batch is then typically called a training epoch. In that context it is useful to vary the order of the training data, because this shakes up the training a bit and hopefully gets the final fit to a better (global) minimum for the loss function. However, the order of the data within a batch does not matter.
In contrast, many other ("traditional") algorithms/models (e.g. logistic regression, linear models, mixed models, gradient boosted decision trees, random forest etc.) are typically fit to all data at once (and the only subsetting of the data is for regularization purposes like bagging/using a subset of features for some trees etc.). I.e. in each iteration of the training process a single parameter update (or a single tree is constructed) based on all data at once without using its order. In that case, the order the data is in does not matter. Even with these types of algorithms you can run into the situation that the data are so big that training needs to proceed in batches (e.g. not enough memory to run the algorithm with all data at once). In that case, shuffling what data is in what batch does make sense.

Shuffling data for machine learning


Use regex or unix to select specific columns

Question: I am using Runtime.getRuntime().exec("df") to get the space details for my partitions.
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/sdb12      41022792 4219168  34713128  11% /
udev             8103980       4   8103976   1% /dev
tmpfs            3245332     924   3244408   1% /run
none                5120       0      5120   0% /run/lock
none             8113328     160   8113168   1% /run/shm
/dev/sdb2         262144   28584    233560  11% /boot/efi

How can I use regex or UNIX commands to get as the output just the 2nd,3rd and 4th columns - changing the headers as follows - Available Memory, Used Memory and Total memory exactly in this order.
 So the desired output is :
Available    Used     Total
34713128   4219168    41022792
8103976       4       8103980
3244408      924      3245332
             ...

Thank you!
Comment: as long as I can execute it all in getRuntime().exec(...), Yes!
Comment: This is most definitely a job for `awk`, not `regex`. Would that be OK?
Comment: Do you want the text centered like that for the middle column, or is right-aligned preferred (as in the original command)
Answer: The following rather long string does what you ask:
df | awk 'BEGIN {print "   Available        Used       Total";} {if (NR>1)  printf("%12d%12d%12d\n", $4, $3, $2);}'

Explanation:
| awk          take the output of the df command as input to awk
BEGIN          do this first: print headers. Note the use of spaces to align things
if (NR > 1)    skip "record 1" = do not do anything with the headers
printf()       do formatted printing
%12d           print integer in fixed width of 12 characters (maintains alignment

Result on my machine:
   Available        Used       Total
    71644456   551306776   623463232
           0         372         372
           0           0           0
           0           0           0
   407510704   377391216   784901920
   618400760   549288520  1167689280

Not terribly useful without the name of the disks, but this is what you were asking...
Comment: Happy to help - clearly the above can be modified in many ways and I hope you will… `awk` is really the perfect tool for this kind of thing, well worth becoming familiar with it. It can be obscure, but is surprisingly powerful. Best reference I found is the grymoire (unusual word meaning "book of spells") - written by Bruce Barnett. Google `grymoire awk`.
Answer: You can use awk to do this:
df | awk '{print ""$4" "$3" "$2""}'

Comment: I modified the order.  I'd not try to do a modification of the headers in a Unix command; just do the substitution against the resulting Java string.
Answer: For me this works
df | perl -pe \
  's!^(?:\S+\s+){2}(\S+)\s+(\S+).*!"$1\t$2\t" . ($1 eq "Used" ? "Total" : $1 + $2)!e'

It's not nice: It finds the columns as non-blanks separated by blanks, which is a bit fragile. It computes the last column as the sum or "Total" based on the column name. Rather fragile, I'd say.


Suppose $f\in H(U), f(U) \subseteq U$. How many zeros can $f$ have in the disc $D(0,\beta)$?

Question: I'm trying to solve exercise 9 from chapter 15 in Rudin's Real and Complex Analysis:

Suppose $0 < \alpha < 1, 0 < \beta < 1, f\in H(U), f(U) \subseteq U, f(0) = \alpha$. How many zeros can $f$ have in the disc $D(0,\beta)$? What is the answer if $f(\alpha)=1/2,\beta=1/2$.

$U$ is the unit disc.
My thoughts:
This sounds like a combination of Jensen's formula and Schwarz lemma but I'm unable to combine them to produce a useful inequality. I would appreciate help. By the way, this is self study.
Answer: Let $z_1, \dotsc, z_m$ be all the zeroes of $f$ (with multiplicity) such that $|z_k| \leq \beta$ for $k \in \{1, \dotsc, m\}$ and define
$$
g(z) = \prod_{k=1}^m \frac{z-z_k}{1-\overline{z}_k z}.
$$
Then $g(z)$ is holomorphic on a neighbourhood of $\overline{U}$ and $|g(z)|=1$ for all $z$ such that $|z|=1$.
The quotient $f(z)/g(z)$ is holomorphic on $U$ and by the maximum principle $|f(z)/g(z)| \leq 1$ for all $z \in U$. In particular for $z=0$ this results in
$$
1 \geq \left| \frac{f(0)}{g(0)} \right| = \frac{\alpha}{\prod_{k=1}^m |z_k|} \geq \frac{\alpha}{\beta^m}.
$$
So $\beta^m \geq \alpha$ and therefore the number of roots $m$ is bounded by
$$
m \leq \frac{\log(\alpha)}{\log(\beta)}.
$$
For $\alpha = \beta = \tfrac{1}{2}$ you get $m \leq 1$.


WebRequest 504 Gateway Timeout

Question: Eai galera, estou com dificuldade em entender o porque está dando gateway timeout em um request, pois sendo que testei por cURL e foi normal, estou utilizando Basic Auth.
Segue:
            var authorization = "apikey:";
            HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create("https://api.konduto.com/v1/orders/0");
            ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
            wbRequest.Headers["Authorization"] = string.Format("Basic {0}", authorization);
            wbRequest.Method = "GET";
            var response = (HttpWebResponse)wbRequest.GetResponse();
            var stringFinally = "";
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                stringFinally = reader.ReadToEnd();
            }

Ao dar getResponse ele me volta :
The remote server returned an error: (504) Gateway Timeout.

Gostaria de saber se alguém já passou por isso e como eu poderia resolver, pois via cURL o GET funciona normal.
Comment: É verdade, já tinha esquecido. Mas no te que isto é um retorno real, não é um erro de autorização do navegador. Só você sabe o que fazer com isto, o navegador não sabe. É claro que pode ser que também tenha um erro de autorização que eu não vi (não tenho como ver agora). Ainda acho que você precisará de suporte específico para ver o que falta enviar. Mas não tenho experiência com estes componentes, então pode ter um problema óbvio que eu não estou percebendo.
Comment: `wbRequest.Timeout = timeout;` deve funcionar.
Comment: O problema parece ser o local acessado (talvez você tenha alguma dificuldade por causa da sua internet). O timeout *default* é de 100 segundos, Já acho até muito. Pode ser até o jeito de usar mas só com estas informações não dá para saber. O código parece estar ok em relação a isto (como sempre a maioria dos códigos postados aqui não fazem tudo o que devem para serem robustos, mas isto é outra coisa). Você tentou acessar sem este código? Tenho minhas dúvidas se essa autorização é necessária. Eu usei sem nada e foi.
Comment: Eu tentei fazer um teste, não sei se há algum problema com o ambiente que tenho mas se eu acessar no navegador sem passar um chave de API retorna um resultado imediato. Sem tento por código sem autorização, dá erro de autorização. Não faz muito sentido já que pelo navegador funciona. E realmente quando coloca a autorização ele não consegue retornar nada em tempo hábil. Isto indica que este tipo de autorização está causando problema. Veja na documentação se existe alguma outra forma de fazer isto. É complicado responder perguntas sobre APIs muito específicas.
Comment: @WisnerOliveira apaga isto rápido. A não ser que isto seja temporário, não vá te causar problemas (mesmo) não coloque informação privativa na internet. Com o cURL você passa esta chave de e faz o processo de autorização ou não? Isto está com cara de algum problema deles ou uso errado da API, não sei se alguém aqui conseguiria ajudar. Eles fornecem suporte?
Comment: @bigown a key é temporária, eu revogo ela e pego outra e sim eu passo via curl também, segue script:
curl -u "apikey" -X GET "https://api.konduto.com/v1/orders/0"
Comment: Já tentou usar `HTTPClient`?
Comment: @bigown sim, já tentei.
Comment: @bigown o retorno quando sai pelo cURL vem assim :
{"status":"error","message":{"where":"/","why":{"expected":"order (0) to exist","found":"order (0) does not exist"}}}

certinho
Comment: É o que eu consegui pelo navegador sem autorização, sem nada. Por isto é estranho. Porque eu acho que tem algo erro no uso da API, provavelmente tem que passar algo mais para funcionar. Mas por outro lado deveria funcionar sem autorização também, funciona no navegador.
Comment: @bigown sério ? o.o qual o retorno que você obtêm pelo navegador ? o único retorno que pelo navegador eu tenho é esse :
{"status":"error","message":{"where":"/","why":{"expected":"Authentic API key.","found":"Unauthentic API key."}}}
Comment: Vamos [continuar esta discussão no bate-papo](http://chat.stackexchange.com/rooms/20767/discussion-between-wisner-oliveira-and-bigown).
Comment: Entendi, vou procurar o suporte da API e ver com eles se falta algo, muito obrigado pela atenção.
Answer: Resolvido da seguinte maneira:
var authorization = "apikey:";
HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create("https://api.konduto.com/v1/orders/0");
wbRequest.Credentials = CredentialCache.DefaultCredentials;
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

string apiKey = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(authorization));
wbRequest.Headers["Authorization"] = string.Format("Basic {0}", apiKey);
wbRequest.Method = "GET";
try
{
    var response = (HttpWebResponse)wbRequest.GetResponse();
    var stringFinally = "";
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        stringFinally = reader.ReadToEnd();
    }
 }
 catch (WebException ex)
 {
     var stringFinallyException = "";
     using (var reader = new StreamReader(ex.Response.GetResponseStream()))
     {
          stringFinallyException = reader.ReadToEnd();
     }
 }

Joguei a API key para Base64. O erro 504 gateway timeout é que a requisição ainda nem foi validada pois o basic Auth estava indo puro tipo XYZXYZXYZX: e ele tem que ir em Base64.

WebRequest 504 Gateway Timeout


Inquiring about finding mentors in the drupal community

Question: Recently, I've noticed that drupal.org has added user profile fields for areas such as adding drupal ID's for attributing thanks to some mentors.
I was curious as to see if there currently is a means or process of seeking or finding a drupal mentor online or through drupal.org? I would ask people in person but i really don't know that many drupalers at the current moment.
Would the best place to look be the forums on Drupal.org? Or just persistent begging on IRC? I would eventually like to mentor others myself once i feel comfortable
Comment: Also found this link helpful: http://drupalofficehours.org/tasks?field_level_value=2&tid=All&field_priority_tid=All
Answer: Welcome to Drupal! There are established core-office-hours for folks looking for mentorship (and looking to mentor); Your best best is to start there and outline your skill set. Someone will be more than happy to help. See http://drupal.org/core-office-hours - So you don't have to beg in IRC. Just show up at the appropriate time. :)


Force DIV's that start in a new row to sit directly underneath the DIV above

Question: I would like to remove the white gaps underneath each DIV so that they are positioned directly underneath, and not with a large white gap which is caused by the DIV on the row above that has the largest height:
I am currently using the following CSS
<code>.extmar {
    height: auto !important;
    margin-bottom:25px;
    display:inline-block !important;
    float:left !important;
    white-space: nowrap !important;
    vertical-align: top !important;
}
</code>
https://jsfiddle.net/3u3z5quk/
I have attached an image of what I am aiming to replicateenter image description here.
Comment: That's called masonry layout - if you google it there's lots of ways to do it with css and with javascript
Answer: I've found this on JSFiddle for you : https://jsfiddle.net/gabrieleromanato/tQANc/
I do not made this code but I think you can try it with your case.
The interesting part :
<code>#container {
    width: 100%;
    max-width: 700px;
    margin: 2em auto;
}
.cols {
    -moz-column-count:3;
    -moz-column-gap: 3%;
    -moz-column-width: 30%;
    -webkit-column-count:3;
    -webkit-column-gap: 3%;
    -webkit-column-width: 30%;
    column-count: 3;
    column-gap: 3%;
    column-width: 30%;
}
.box {
    margin-bottom: 20px;
}
</code>
If you have questions about this code, I can explain it to you.
Comment: Hi Vincent, that's fantastic. Thanks so much for this. Works great!
Comment: No problem, I did not made this code, we should thanks the owner ;)


Sorting a non-copy array

Question: I am working on my lab #5 and it's about sorting algorithms such as Quick Sort, Heap Sort and Merge Sort. I am somewhat done besides measuring the execution time and some other stuff, and I ran into an issue.
in this code:
  int *arr = fill();
  int size = 10;

  std::cout << "\nMERGE SORT: \n";
  std::cout << "array#1: ";
  print_arr(arr, size);

  merge_sort(arr,size);
  std::cout << "array#2: ";
  print_arr(arr,size);

  std::cout << "\nQUICK SORT: \n";
  std::cout << "array#1: ";
  print_arr(arr, size);

  quick_sort(arr, size);

  std::cout << "array#2: ";
  print_arr(arr, size);

  std::cout << "\nHEAP SORT: \n";
  std::cout << "array#1: ";
  print_arr(arr, size);

  heap_sort(arr, size);

  std::cout << "array#2: ";
  print_arr(arr, size);

  delete[] arr;

I am passing my array to all of the sorting methods and what's happening is that the array get's sorted with Merge Sort, which works fine but then that sorted array is being passed into Quick Sort and Heap Sort.
I did some research and I found that I can use std::copy() to create copies of the array and them pass them separatley as copies, but I know my professor is not a "fan" of the STL and usually tells us to not use it if it's not our last resort.
My restrictions for this assigment are some prototypes such as this function:
const int MAX = 100000;
int* fill() {
    int* arr = new int[10]; // create a new array of size 100

    // set the seed for the random number generator
    std::srand(static_cast<unsigned int>(std::time(nullptr)));

    for (int i = 0; i < 10; i++) { //!change to MAX
        arr[i] = std::rand() % 10 + 1; // fill the array with random numbers from 1 to 100
    }
    return arr;
}

and
void heap_sort(int *arr, int size);
void merge_sort(int *arr, int size)
void qucik_sort(int *arr, int size)

So far all the algorithms work since I tested them separatley, but when I run them all together it sorts the already sorted array. This affects the QS algorithm.
I know it looks like spaghetti code right now, function pointers are on the TODO list.
Comment: Manually copy the elements with a loop to three separate arrays ... Also, if you prof is actively telling you not to use the STL, then they are a terrible prof (exception being for learning purposes, but `std::copy` is hardly something to worry about).
Comment: A couple of things related to your code, but not necessarily to your problem: Call `srand` *once* only in your program, preferably among the first things in your `main` function. But also don't use `srand` and `rand`, C++ have [much better PRNG facilities](https://en.cppreference.com/w/cpp/numeric/random). Then don't allocate memory yourself. Use either `std::vector` if you need a truly dynamic array, or `std::array` if you don't.
Comment: Your prof may have reasons to avoid STL-ish parts from the C++ ISO Standard, but that's a questionable advise for general C++, as is use of vector new and manual resource management in general. That said, concerning your problem, please extract a [mcve] from your code and include that in your question. As a new user here, please also take the [tour] and read [ask].
Comment: @Dude [How to implement sorting algorithms using modern C++](https://stackoverflow.com/questions/24650626/how-to-implement-classic-sorting-algorithms-in-modern-c).
Comment: @Someprogrammerdude I'd love to but I can't use the STL containers unfortunatley
Comment: Also, why sort the array multiple times? What difference would that make between the sorting calls? You never shuffle the array (as far as we can see) so once sorted it should hopefully stay sorted no matter how many times you call different sorting functions.
Comment: I forgot to add the "instructions" to my question. The purpose of the lab is to make a working implementation of QS, MS an HS and print the results in main. I figured having the same array would show best that the algorithm works since the user could compare results and see that the output is the same
Comment: For that you should create three new copies of the original array with the random values. Then pass each array-copy to each of the sorting functions. Then compare the three arrays to make sure they are all the same. So you should have a total of four arrays: The original unsorted array, and one each for each sorting function.
Answer: You need to generate the array and then copy it. You might do something like:
int* copy_array(int* arr, std::size_t n) {
    int* new_arr = new int[size];

    for (std::size_t i = 0; i < n; i++) {
        new_arr[i] = arr[i];
    }

    return new_arr;
}

Then simply call this to create as many copies of your array as you need before sorting it.
Answer: You could manually copy your array like this:
for (int i = 0; i < size; i++) {
    destination[i] = src[i];
}

Or you could use memcpy. Example from the link:
/* memcpy example */
#include <stdio.h>
#include <string.h>

struct {
  char name[40];
  int age;
} person, person_copy;

int main ()
{
  char myname[] = "Pierre de Fermat";

  /* using memcpy to copy string: */
  memcpy ( person.name, myname, strlen(myname)+1 );
  person.age = 46;

  /* using memcpy to copy structure: */
  memcpy ( &person_copy, &person, sizeof(person) );

  printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );

  return 0;
}

and, of course you can use std::copy as well, even though it's not an option due to the preferences of your professor.
Comment: Nitpick: as this is C++ (sans STL) I would suggest including `` and ``.

Sorting a non-copy array


Run Python script on windows from .py file in Latest Version Python 3.5.1

Question: I am learning Python now.
At my very first program I am getting following error.
>>> python first_tutorial.py
  File "<stdin>", line 1
    python first_tutorial.py
                       ^
SyntaxError: invalid syntax
>>>

Below is my code in that file -
name = "John"
age = 19
print name
print age

I am using following Python 3.5.1 version on Windows 10
I can print simple text from cmd line but no able to run script from file.
Update
I am running it from command line itself.. first I make a folder on my docs then run cmd line and type python after that when I just type print "Hello" it works fine but when I run python file like python first_tutorial.py it shows error
Any guidance please.
Thanks
Comment: Just a nitpicking but `first_tutorial.py` and `firsttutorial.py` seems to be a little different. Anyway, more seriously, have you set the path of the Python interpreter?
Comment: @John: I would expect that if you followed those answers, you would then get a SyntaxError at `print name` rather than `python first_tutorial.py`.  That means that your current problem is solved.  The `print name` is a separate problem.  To fix that, use `print(name)`.  Likewise, `print(age)`.
Comment: Oh sorry thats my typo error.
Comment: Its not duplicate of that question. May be question is same but those answer not solved my problem.
Comment: It is a duplicate. The `>>>` arrows show you are trying to run python from python, not the command python
Comment: Thanks  zondo  cricket_007 ASCIIThenANSI
Answer: You're running in the Python interactive shell. It's trying to interpret your command as Python code, which causes an error.
You need to run python first_tutorial.py from the commandline. After that your code should work fine, assuming there's no other errors.
Comment: I am running it from commandline itself.. first I make a folder on my docs then run cmd line and type `python` after that when I just type `print "Hello"  ` it works fine but when I run python file like `python first_tutorial.py` it shows error
Comment: Yes you are correct. I was running after entering in Python interactive shell. But still Can I run file inside python shell. ?
Comment: John, if your script is named `mytest.py`, you can run it (once) from the interactive prompt with `import mytest`. But it's better to edit it in IDLE and run it with F5.
Answer: When you type 'python' on the command prompt, you get an interpreter, so you can enter python code here:
>>> name = "john"
>>> print(name)
john

If you have a file test.py that you want to run, you can do that from the windows command prompt:
C:\Apps>python test.py
John
19

If you really want to run a python file from the python interpreter, you can do that too, but you need to open the file in python and exec it.
>>> with open("test.py") as f:
...   exec(f)
...
John
19

Comment: The third part is poor advice *and* incorrect (try it).


How to find X value for slope of zero from a natural cubic spline in RStudio

Question: I have a scatter plot that I've fitted with a natural cubic spline with 4 knots using ns(), pictured below:

I would like to find the value of x where the slope is zero at the abline pictured below:

Is there a straightforward way to do this in RStudio? I'm having trouble with trying to figure out what the natural cubic spline formula would be and haven't had experience with derivatives since college. If it's helpful, here is the summary output:

Thanks very much!
Answer: In principle, one could simply differentiate the spline and solve for where the derivative is 0 (even if that solution requires some sort of root finding procedure).  Alternatively, you could just use a bisection method with predictions from the spline.
More practically, you can evaluate the spline over a fine grid to approximate the derivative using finite differences.  Here is an example
library(splines)

set.seed(0)
# Simulate data
n <- 1000
x <- runif(n, min=0, max = 1)

# We already know the derivative is 0 at x=0.5
y <- sin(pi*x) + rnorm(n, 0, 0.3)

plot(x, y)

knts <- c(0.2, 0.4, 0.6, 0.8)
fit <- lm(y~ns(x, knots = knts, Boundary.knots = c(0.1, 0.9)))

## fine grid over which to evaluate the spline
h <- 1e-4
xx <- seq(0, 1, h)
yy <- predict(fit, newdata = list(x=xx))

lines(xx, yy, col='red', lwd=3)

est_yprime <- diff(yy)/h

# Find the x which produces the smallest absolute yprime
x_min <- xx[order(abs(est_yprime))[1]]

# Close enough, and hovers around the right answer when you run it
# With different seeds
x_min
#> [1] 0.4611

Created on 2024-03-01 with reprex v2.0.2
Answer: Just piggybacking off the previous answer, there actually is a package in R designed to yield derivatives of natural splines, and you can pretty quickly obtain the derivatives of the fitted spline and then use a root finding package.
require(splines2)
require(rootSolve)

set.seed(1234)

n = 1000
x = rnorm(n);
basis = model.matrix(~naturalSpline(x,df=6,
                                    Boundary.knots = c(-4,4),
                                    knots = quantile(x,probs = seq(0.1,0.9,length.out=6))))
beta = rnorm(8,sd=3)

y = basis%*%beta + rnorm(n)
fit <- lm(y~-1+basis)

xeval = seq(min(x),max(x),0.01)
derivBasis = model.matrix(~-1+naturalSpline(xeval,
                                            Boundary.knots = c(-4,4),
                                            knots = quantile(x,probs = seq(0.1,0.9,length.out=6)),
                                            derivs = 1))
derivs = derivBasis%*%coef(fit)[-1]

deriv_func <- function(xpoint){
  naturalSpline(xpoint,
                Boundary.knots = c(-4,4),
                knots = quantile(x,probs = seq(0.1,0.9,length.out=6)),
                derivs = 1)%*%coef(fit)[-1]
}

zeroes = uniroot.all(deriv_func,interval = range(x))

plot(x,y,xlab='X',ylab='Y');abline(v=zeroes,lty=2)
lines(sort(x),fit$fitted.values[order(x)],col='red',lwd=5)
plot(xeval,derivs,xlab='X',ylab="df(X)/dx");abline(h=0);abline(v=zeroes,lty=2)


Percona PMM's clickhouse doesn't clean up old metric_log directory

Question: We've got Percona's PMM installed for a few years now in docker with the /srv directory mounted to the filesystem.
We've spotted that the clickhouse service isn't cleaning up its data in the directory /srv/clickhouse/data/system/metric_log. Some of the directories there are over 2 years old and some still contain +150MB data. I think we can clean this up, but I couldn't find any documentation about this on pmm websites.
I could manually remove these directories, but I expect pmm (or clickhouse) has some retention mechanism available for it.
I've also verified that pmm's retention works as expected since I don't have any data available in the pmm dashboard older than the retention period configured in pmm.
A short list of the size (and names) of those directories:
--- /srv/clickhouse/data/system/metric_log -----
  130.5 MiB [##########] /202312_8404047_8653546_1838
  105.5 MiB [########  ] /202207_2445036_2694502_2246
   99.6 MiB [#######   ] /202301_4676883_4912218_2210
   95.6 MiB [#######   ] /202307_6644116_6874350_2392
   94.1 MiB [#######   ] /202305_5942426_6168500_2386
   92.4 MiB [#######   ] /202112_5912_265478_2749
   92.3 MiB [#######   ] /202212_4205342_4421596_2234
...

Most of the data is stored in [dir]/event_time_microseconds.bin.
As you can see, some of these directories are old but still contain quite some data.
Answer: From the config examples mentioned in their documentation, these files are most probably kept there because they have not reached the thresholds (read more here https://clickhouse.com/docs/en/operations/server-configuration-parameters/settings#metric_log).
I would not take the risk of removing them manually since I can't predict the result. Rather, you could try to temporarily disable the metrics_log and, once the directories are cleanup up and space is reclaimed, you can reenable the logs.
That would certainly require you to stop PMM's clickhouse server, modify the config, then start the server.
In other words, if you run it in a docker container, here are three steps

stop the server: docker exec -it pmm-server supervisorctl stop clickhouse
change clickhouse configuration via an override:

To disable metric_log setting, you should create the following file
"/etc/clickhouse-server/config.d/disable_metric_log.xml" with the following content:

<clickhouse>
<metric_log remove="1" />
</clickhouse>

start the server: docker exec -it pmm-server supervisorctl start clickhouse

Please make sure you have a full backup of PMM's /srv directory before proceeding with any changes so you can recover if things go wrong :)


Performance de requisição usando Html.BeginForm versus jQuery AJAX

Question: Existe algum ganho de performance ao utilizar jQuery para realizar requições ajax em relação ao post utilizando Html.BeginForm?
@using (Html.BeginForm("Create", "Teste")
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

           @Html.LabelFor(m => m.Nome, new { @class = "col-md-2 control-label" })

        @Html.TextBoxFor(m => m.Nome, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Nome, "", new { @class = "text-danger" })
   }

         <input type="submit" class="btn btn-default" value="Enviar" />

Se for melhor fazer via requisição ajax, tem algum código de exemplo onde trate do ValidationSummary e ValidationMessageFor?
Answer: A verdade é que não há relação nenhuma entre as duas práticas, por assim dizer.
O Html.BeginForm() é executado ainda no servidor, ele apenas ajuda - afinal, é um HTML Helper - a criar as tags <form></form>.
Já o jQuery, esse é executado no lado do client, no browser, bem depois do ciclo de vida do BeginForm() ter terminado.
Comment: A minha dúvida não é com relação ao HTML.BeginForm em si, mas à forma como a requisição é feita.
Comment: Isso é configurado nas duas maneiras. Mas ambos farão, como default, um HTTP POST Request. Então, no final, eles fazem exatamente a mesma coisa.


from VBS to WPF via COM

Question: we have a nasty (or maybe a trivial?) issue.
There is a WPF control. It has 2 interfaces, the main and one for automated testing purpose. Defined this way:
[ComVisible(true)]
[Guid("xxx")]
public interface IXXXXXTest
{
[DispId(1)]
    void Test1(int index);
}

[ComVisible(true)]
public interface IXXXXX
{
    void Main1(index);
}

[ComVisible(true)]
[Guid("xxx")]
ClassInterface(ClassInterfaceType.None)]
public partial class XXXXX_WPF_CONTROL : UserControl,
                         IXXXXX,
                         IXXXXXTest
{
     ...
}

Now we are trying to reach it from VBS.
Try 1)
Set Ctrl = GetControl(...)  <---- this is ok
Ctrl.Test1(0)  <---- Object doesn't support this property or method: 'Ctrl.Test1'

Set Ctrl = GetControl(...)  <---- this is ok
Ctrl.Main1(0)  <---- this is ok

So it works fine for the "main" interface but for the test interface.
This seems ok(?), because as far as I know VBS reaches the "main" interface only via IDispatch if there is no IDispatchEx. So I added a property to the IXXXXX to get the test interface.
[ComVisible(true)]
public interface IXXXXX
{
    void Main1(index);
    IXXXXXTest Test { get;}
}
....
public IXXXXXTest Test
{
    get {   return this as IXXXXXTest;  }
}

Great, so now I can reach this IXXXXTest interface via the "main" interface.
Try 2)
VBS:
Set Ctrl = GetControl(...)  <---- this is ok
Set CtrlTest = Ctrl.Test  <----- this is ok
CtrlTest.Test1(0)    <---- Object doesn't support this property or method: 'CtrlTest.Test1'

:(
Note that, for an other .NET control of us the "Try1" works, without any trick!
So probably due to the WPF something different?
Also, changing the
ClassInterface(ClassInterfaceType.None)]

into anything else (AutoDispatch / AutoDual), or leaving it makes the WPF control unusable.
Besides that this is also how it should be by this article: Is it possible to package WPF window as COM Object
Do you have any idea what could be the problem?
Thank much in advance!
Answer: Scripting languages can only use the default interface on a class.  You've got more than one so at least one of them will not be usable.  And method names may be renamed if they conflict with other declarations.  I'd assume you obfuscated the real names in your question so hard to diagnose such a renaming happening from what you posted.
Best thing to do is to temporarily apply the [InterfaceType(ComInterfaceType.InterfaceIsDual)] attribute on your interface types.  Which allows you to generate a type library with Tlbexp.exe which you can then view with the OleView.exe utility, File + View Typelib command.  You'll see the exact names of the methods and you'll see which interface is the [default] one on the coclass.  From there you should have little trouble modifying your declarations so they'll work in a scripting language.
Comment: Thanks your reply, I did not mean to obfuscate but to make it more clear :)

I checked the Tlb, and that's what I thought: the IXXXX is the [default] interface.
However you can reach it's "Test" property, which returns the objects as IXXXXTest interface.
And this is accessible from the VBS. So (in theory) I have an IXXXTest interface to this objects in the VBS.
However calling a method on the interface fails as "Object doesn't support..."
While this IXXXTest interface (checked in the TLB) HAS that Test1() method
Comment: Moreover, we have a basic .NET control, which also implements more interfaces, and we can reach ANY function from any interface on this from VBS directly, not only the ones from the [default[. Strange!
It only fails for this WPF control, even via the exported non-default-interface...
Comment: Hans, you gave a clue for the solution.
Comment: I have the solution: you need a tester class which has the object to test as a member, and implements the tester interface. Then delegates to the main class. In my example:
`class XXXXTester : IXXXXTest {
    XXXX _xxxx;
        public XXXXTester(XXXX x) { _xxxx = x; }

        //here comes IXXXXTest members
        public Test1() { ... }
     }
`
And in the class XXXX

`public IXXXXXTest Test
{
    get {   return new (XXXXTester(this));  }
}
`
I tested, it works.
Hans, you gave a clue for the solution, so I gave the answer to you.

from VBS to WPF via COM


How to call a list of items from a text file

Question: I'm using a tool called Benzin; everyday I have to write a new command for the new files I'm dealing with. I would like to create a text file that has a list of the files I need. Then, look through the list of files and use Benzin on them. Benzin is used as follows:
Benzin R filename.brlyt filename.xmlyt

I'd like the tool to automatically look through the list and then replace "filename.brlyt" with what's written inside the text file and convert the files one by one.
Sadly I don't know how to do this so I thought of doing another thing, I just simply place the files inside a folder and do this command:
FOR /D %%A IN ("Files\*.brlyt") Do Benzin.exe R %%A %%A.xmlyt
pause
cls
rename *.brlyt.xmlyt *.xmlyt
pause

That is giving file not found error, can anyone see what's wrong?
Ok, so I've found the code
    @echo off
for /f %%A in (files.txt) do (
echo converting
echo %%A
benzin r %%A coverted/%%A.xmlyt
pause
cls
)
pause
rename *.brlyt.xmlyt *.xmlyt
pause

How do I make another batch that writes the list of files in a directory into the text files.txt? Here's what I'm trying but it is only showing me "\files\" inside the text file.
@echo off
FOR /D %%A in (\files\) Do (
echo writing %%A into files.txt
echo %%A > files.txt
)
pause

Answer: Starting with:
FOR /F "tokens=*" %%A IN ('TYPE test_list.txt') DO ECHO %%A
PAUSE

Now, looking at, we see: http://www.robvanderwoude.com/files/servers_nt.txt
FOR /F "tokens=*" %%A IN ('TYPE %~dpn0.srv ^| FIND /V ";" ^| SORT') DO CALL :ChkSrv %%A
GOTO End

I would use/re-use that for your code.


Cisco 1841 - Configuration Issue with NAT

Question: We recently dug out an old Cisco 1841 to solve a need and have been in the process of trying to configure it appropriately.  Admittedly, this is my first escapade into the land of Cisco Routing.  I've been trying to piece together the correct NAT rules, but something just isn't right.
To give you a lay of the land, we have Outside Internet connection going into fa0/1.  Then we have a Cisco Firewall going to fa0/0.  Now, before I get too far, I know for a fact that the Cisco firewall is configured appropriately.  The original router that was in place before we swapped it with the 1841 worked just fine.  For those wondering, we were using an Edgemark router through a PBX provider that we no longer want to use.  To fill the need for a router, we replaced the Edgemark router with this Cisco router.
Internet -> Cisco 1841 FA0/1 -> Cisco 1841 FA0/0 -> Cisco ASA 5520 Firewall -> Core Internal Switch
interface FastEthernet0/0
description $ETH-LAN$
ip address 67.xxx.xxx.177 255.255.255.240
ip nat inside
ip virtual-reassembly
no ip route-cache
duplex auto
speed auto
!
interface FastEthernet0/1
description $ETH-WAN$
ip address 65.yyy.yyy.150 255.255.255.252
no ip proxy-arp
ip nat outside
ip virtual-reassembly
no ip route-cache
speed 10
full-duplex
!
ip classless
ip route 0.0.0.0 0.0.0.0 65.yyy.yyy.149
!
no ip http server
no ip http secure-server
ip nat pool Net67 67.xxx.xxx.176 67.xxx.xxx.191 netmask 255.255.255.240
ip nat pool ovrld 67.xxx.xxx.178 67.xxx.xxx.178 prefix-length 24
ip nat inside source list 101 pool ovrld overload
ip nat outside source list 101 pool Net67 add-route
!
access-list 101 permit ip 67.xxx.xxx.176 0.0.0.15 any

Now, the nat rules that I have here are rules that I had pieced together off of sites such as ServerFault, Cisco Community, and other sources.  I think something is wrong though.
Here are the issues:

Devices on the inside can't see the internet.

Though the router CAN ping 18.104.22.168 from itself.

Traffic on the outside going to the inside public IP's can't get through.

Any help would be appreciated.
Thanks!
EDIT:  A Previous config that I also tried, which also did not work was this.
interface FastEthernet0/0
 description $ETH-LAN$
 ip address 67.xxx.xxx.177 255.255.255.240
 ip nat inside
 ip virtual-reassembly
 duplex auto
 speed auto
!
interface FastEthernet0/1
 description $ETH-WAN$
 ip address 65.yyy.yyy.150 255.255.255.252
 no ip proxy-arp
 ip nat outside
 ip virtual-reassembly
 no ip route-cache
 speed 10
 full-duplex
!
ip route 0.0.0.0 0.0.0.0 65.yyy.yyy.149
!
no ip http server
no ip http secure-server
ip nat inside source route-map nonat interface FastEthernet0/1 overload
!
access-list 101 permit ip 67.xxx.xxx.176 255.255.255.240 any
route-map nonat permit 10
match ip address 101

Comment: Why are you NAT'ing one set of public IP's to another set?  Is there some specific reason for that?  Also, your description of the network is unclear.  Does it go Internet->FA0/1->FA0/2->Firewall->internal network?  In this case I would NAT on the firewall, not the router.  in addition, if you are managing NAT with source-lists, we need to see the access lists that you are using as well as the rest of the config.
Comment: Would there be any issue sourcing your traffic from the WAN Ethernet (i.e. 65.yyy.yyy.150)?  The easiest setup would be to overload based on that outbound address - so "ip nat inside source list 101 interface fa0/1 overload" would get you outbound.  This obviously doesn't apply if you're trying to do inbound NAT for a web server, but that wasn't indicated in your question.
Comment: There is a ton of natting that is going on with the firewall, so smithian, you may be right that I don't need to do NATing. Honestly, I just need simple routing here, and not sure what the config should be.  It goes Internet -> FA0/1 -> FA0/0 -> Firewall -> Core Network.  The config above is after approximately two days of trying to get this to work. Blankly, we have a block of IP's (noted as 67.xxx.xxx.176/28) that are public IP's that need to be pushed out to the firewall (which has all of the nating and ACL's setup). And all devices on the inside need to access the public internet.
Comment: To rnxrx's point, I need public internet traffic to appear as though it's coming from 67.xxx.xxx.178, and not the 65.yyy.yyy.149 address.
Comment: And yes, there are webservers that sit on the inside that are addressed using 67.xxx.xxx.### IP's if that clears up what we're trying to do.  Though the Cisco ASA 5520 Firewall is taking care of that NATing.
Answer: first of all you have a duplex mix match. if you are wanting to do at test to make your configuration work i would recommend that you make both interfaces duplex auto (in addition to your speed).
i would also change your inside outside overload statement to have your inside traffic pointing towards the outside interface.
ie. ip nat inside source list 101 interface fastethernet 0/1 overload
try this and see if it gets you access.... in 3 years


Modules to extend the Display Suite module?

Question: Just that. I find the Display Suite module really useful for my projects.
Are there more modules to extend its functionality in any way?
Thanks.
Answer: I really like the combination of Display suite with Custom Formatters - http://drupal.org/project/custom_formatters & with the Omega Theme, with these tools you can almost entirely skip having to use tpl.php files to theme your site's layout and content.
Also listed on the Display suite page you have Field Group - http://drupal.org/project/field_group & Rendable elemenets - http://drupal.org/project/rel However Rendable elements doesn't seem to work that well quite yet but it looks promising.
Comment: I didn´t know of custom formatters. Do you know of any video/screencast which shows me how to use it? I tried http://drupal.org/project/rel , it looks really useful but is not ready for production yet.
Comment: This was pretty helpful http://bxl2011.drupaldays.org/node/303


Can we configure ADFS for IDP initiated SSO

Question: I'm looking for ways of integrating ADFS as a IDP for a SAML2 service provider. I have already configured the SAML2 provider with the verification certificates etc. And we used "Add Relying Party Trust Wizard" to configure ADFS with the details of the SAML2 SP.
But I'm not sure about the rest of the workflow here. Appreciate if anyone can guide me to a good article.
Answer: See https://blogs.technet.microsoft.com/askds/2012/09/27/ad-fs-2-0-relaystate/ and referenced articles for details
Comment: It's inbuilt. Only needs to be manually enabled for windows 2016 via powershell. I don't know the os you have for adfs.
Comment: Thanks for the info. Does idpinitiatedsignon.aspx comes with ADFS itself or should we implement it in order to generate SAML request ?


how to wrap a text in react native ios.? In android it is wrapping within the flex width but in ios not wrapping

Question: i need to wrap the text inside a flex:
i searched last four days but i dint get any solutions. if anybody knows please help me>
Thank you in advance
 Some text to wrap inside the flex view
Answer: in android the text is wrapping but in iOS there if there is no height to wrap the text means the text will won't wrap. So that we have to give height to the text tag then it ill wrap the text


Playback duration of string harmonics in Sibelius

Question: I am currently notating some string harmonics in Sibelius (2020.9), and am using the "Harmonics playback" plugin to hear the natural harmonics at their actual pitch.
One example is of a natural harmonic "E" on the violin, played by bowing the A string and resting the finger at E. This creates the sound of the E note one octave above where the finger is resting.
I've notated this with a normal (type 0) notehead at A above middle C, and a diamond (type 2) notehead at E a 5th above. When I apply the plugin, the harmonic sounds at the correct pitch; however, it will not hold the pitch for the duration of the note value. No matter which note value I choose (minim, semibreve, etc.) it will only sound for a crotchet's duration.
Does anybody know of a fix for this?
Answer: Add a hidden note in another voice at the desired pitch/duration.

To make the harmonic play back, make the printed pitch use a silent notehead, and add the sounding pitch of the harmonic using a hidden note in another voice

From Sibelius Reference Guide 2019.4, page 607, from Section 6.6 "Interpretation of Your Score", "Harmonics".


Apache reverse proxy AH01597: could not open mime types config file

Question: I'm trying to configure Apache HTTP server 2.4 as a reverse proxy on RHEL 7 server. When Apache starts up it complains in its log file (/var/log/httpd/error_log):
 AH01597: could not open mime types config file /etc/httpd/conf/mime.types.

I'm surprised it cares about MIME types, as I do not want it to serve files from the file-system at  all. How can I configure Apache HTTP server so it does not demand a mime types configuration or which additional packages (RPMs) do I need to install to provide correct MIME types information.
Comment: Try to remove `TypesConfig` directive http://httpd.apache.org/docs/current/mod/mod_mime.html#typesconfig
Comment: mime.types are loaded by default to provide the correct mime for most types of files, all configurations by default should have it, every installation should come with them, just point or make sure the file is not corrupted, it won't hurt.
Answer: I had based my Apache configuration file on the example that Red Hat provided. I included the command
 Include conf.modules.d/00-base.conf

as I thought leaving out any base modules would lead to Bad Things.
But the Red Hat supplied conf.modules.d/00-base.conf files loads numerous modules, few of which are required for a reverse proxy. In particular, it loads the mod_mime module, which needs a MIME types configuration file.
Replacing that Include command with individual LoadModule commands for the few modules I need eliminated the problem.
Answer: As @ezra-s mentioned mime.types file should come with installation. For my case it is located at /etc directory. So I just solved the same problem by copying the mime.types files from /etc directory to /etc/httpd/conf/
Answer: This could be caused by setting the wrong ServerRoot - do not confuse it (as I did) with DocumentRoot.

ServerRoot - apache installation dir (and base dir for related logs, pidfiles, or mime.types etc.)
DocumentRoot - web dir


View that shows posts specific to the node

Question: In my website, under every project we do, there is a project info post which summarises what the project is about as well as all the recent updates(posts) about that project.
this is what it looks like https://i.stack.imgur.com/GI2vM.jpg
I am trying to find a way i can view a 'project-info' node and add a 'view' that shows all the related 'project-posts' related to the particular project that the 'project-info' node is about.
I'm not sure where to begin.
(Drupal 7)
Comment: Consider making it a bit less use-case specific.
Answer: You should begin around Views of course. Just make a taxonomy term per project, and use Views to create a page with all nodes of type "update(post)". Then in tpl.php for a texonomy field of "project info post", build a link based on taxonomy term. That's pretty much all.
Entity reference module is worth to look at, too. Using it you could relate all "update" nodes to "project info" node. Similar effect to taxonomy, has it's pros and cons of course. Read about both, and choose your poison - referencing node directly is cleaner way, but taxonomy seems to be supported better, and is in core so less contrib modules for you.
Last but not least - you could simply make the update posts a comments on project info post.


Easy way to make OpenCV's "undistort" run more efficiently?

Question: I'm currently in the works of making an auto-aiming turret, and my camera's have a noticeable fish eye effect, which is totally fine. I'm using OpenCV's undistort() function to handle this, with data from a camera checkerboard calibration.
I will most likely be running the vision system on a raspberry pi 4, and currently, my undistort function takes 80-90% of my CPU (i5-8600k OC 5GHz) when processing both of my cameras at 1280x720px, ideally this px as it's the largest and will provide best accuracy. Also note I'm aiming for a 15Hz update time.
Any ideas on how to make this more lightweight? Here's my code that I'm currently running as a test:
from cv2 import cv2
import numpy as np
import yaml
import time

cam1 = cv2.VideoCapture(0)
cam2 = cv2.VideoCapture(1)
cam1.set(3, 1280)
cam1.set(4, 720)
cam2.set(3, 1280)
cam2.set(4, 720)

#load calibration matrix
with open ("calibration_matrix.yaml") as file:

    documents = yaml.full_load(file)
    x=0
    for item, doc in documents.items():
        if x == 0:
            mtx = np.matrix(doc)
            x = 1
        else:
            dist = np.matrix(doc)

def camera(ID, asd):
    if asd == -1:
        ID.release()

    ret, frame = ID.read()

    if ret:
        newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
        undistortedFrame = cv2.undistort(frame, mtx, dist, None, newcameramtx)
        undistortedFrame = undistortedFrame[y:y+h, x:x+w]
        return undistortedFrame
while True:
    frame1 = camera(cam1, 0)
    frame2 = camera(cam2, 0)
    cv2.imshow('Frame 1', frame1)
    cv2.imshow('Frame 2', frame2)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        camera(cam1, -1)
        camera(cam2, -1)
        cv2.destroyAllWindows()

Comment: use initundistortrectifymap (once) and remap (for each image)
Comment: sorry, only have C++ experience with that function. The idea is that the expensive part of undistort is performed only once and only the then precomputed pixel motion is performed for each image,
Comment: If your camera is fisheye, then you should be using `fisheye` module for calibration. [Example Code for Fisheye Calibration - Python](https://medium.com/@kennethjiang/calibrate-fisheye-lens-using-opencv-333b05afa0b0)
Comment: Will look into it. What's the difference between undistort?
Comment: I'm really stuck with implementing this function in python, I've read all there is to read that I can understand about the function. Can you provide an example in python?
Comment: Thanks guys, I'll give the fish-eye a try. I was able to get the initUndistortRectifyMap work, and it runs many times lighter. I'll test out the fish eye method and compare performance.
Answer: Comments above resolved, here's the solution:
As @Micka said,

use initundistortrectifymap() (once) and remap() (for each image)

initundistortrectifymap() basically takes the heavy load off of the undistort function (Micka) In practice, you run initundistortrectifymap() at the start of the program with the image calibration matrix and distance coefficients, and then initundistortrectifymap() returns two maps, map1 and map2.
These maps can be passed into the remap() function to remap your image, which is a significantly lighter function than undistort(). In my particular case, I have a fisheye camera, and OpenCV has fisheye modules that are optimized to undistort fish eye cameras with ease.


DHTML flydown menu not working in IE7

Question: We just redesigned one of our sites at work with our new CMS and are having issues with the DHTML flydown menu in IE7 and IE6.
http://www.ohiomagazine.com/Main/Home.aspx
If you test it in IE7, you will see that the flydown is hidden behind the content below it. My coworker seems to think that there is something wrong with the CSS, while I believe it has to do with the CMS's god-awful JavaScript. The point is, neither of us know where to start and need a little help from the community.
Answer: make the z-index of container div of the menu higher than the other divs. Here is an example. ("position:relative" is also needed.)
<code>#menuwrapper
{
z-index:2;
position:relative;
}

#otherdiv1
{
position:relative;
z-index:1;
}

#otherdiv2
{
position:relative;
z-index:1;
}
</code>

DHTML flydown menu not working in IE7


How to remove tracked formatted changes

Question: I have been following the msdn-guide to remove tracked changes from a docx document: MSDN
However it doesnt remove tracked formatted changes thats been made to the document. Does anyone know how this can be done?
Answer: I eventually came across this neat little class that removes all tracked changes from a document:
accept revisions and I now use this one instead of the suggested method from the mentioned msdn post.

How to remove tracked formatted changes


What's the difference between $user login and access?

Question: I'm migrating users and I came across the $user object.
What's the difference between the login and access field? Does access get updated with every page request?
Answer: The access field is updated in Drupal's session write handler _drupal_session_write. This means it is potentially updated at every page request. If you look at the source code, you'll see that the access field is, by default, only updated every 180 seconds. This interval can be changed by setting the session_write_interval Drupal variable.
// Likewise, do not update access time more than once per 180 seconds.
if ($user->uid && REQUEST_TIME - $user->access > variable_get('session_write_interval', 180)) {
  db_update('users')
    ->fields(array(
    'access' => REQUEST_TIME,
  ))
    ->condition('uid', $user->uid)
    ->execute();
}

Answer: According to the the comments for the fields in user_schema():
access: Timestamp for previous time user accessed the site.
login: Timestamp for user's last login.
So access would get updated for each page load, login only when the user actually logged in.


attribute names with dashes don't work with get_attribute (perl Selenium)

Question: use feature 'say';
$selen = Selenium::Remote::Driver->new;
$selen->get("http://www.google.com");
$elem = $selen->find_element('(//div[@data-responsive-height-resize])[1]');
say $elem->get_attribute('data-responsive-height-resize'); # this doesn't work
say $selen->execute_script('return arguments[0].getAttribute("data-responsive-height-resize")', $elem);  # this works

Is there a problem with Selenium::Remote::WebElement::get_attribute in that it can't handle dashes in the attribute name?  Or am I doing something wrong?
Comment: Yes, it worked!
Comment: Did you try adding a `1` like it says in the [documentation](https://metacpan.org/pod/Selenium::Remote::WebElement#get_attribute) for `get_attribute`?
Comment: I suppose I should add that as an answer...
Answer: Adding comment as answer.
In the documentation for get_attribute it says that you can use a boolean as second argument

If you want to get the initial condition (e.g. the values in the tag hardcoded in HTML), pass 1 as the second argument.

So if you try that, you might get what you want. (And it seems it did work)


Can test-results in azure-devops pipelines be filtered by TestCategory?

Question: I have a pipeline running on Azure Devops that builds and runs tests for a C# solution. We use MsTest for test-runner, and we use the TestCategory attribute to categorize different tests. For example, we might have:
<code>[TestClass]
[TestCategory("UnitTests")]
[TestCategory("SomeFeature"]
public class SomeTestsForSomeFeatureTests
{
    Some test-code...
}

</code>
and
<code>[TestClass]
[TestCategory("IntegrationTests")]
[TestCategory("SomeFeature"]
public class SomeIntegrationTestsForSomeFeatureTests
{
    Some test-code...
}

</code>
Is there a way to group the test-results in Azure Devops Pipelines by TestCategory?
It is possible to group the test-results by Test Run, Test File, Priorty, Owner or None, but I have not found a way to group by the TestCategory.
I know that it is possible to setup the pipeline to run tests by TestCategory, but this is not what I am after. Rather, I would like to be able to get a subset of the test-results in my solution. Ideally, I would like to be able to link to the results of the tests in the TestCategory of my choice.
Answer: It seems that group by test category in test results UI is not supported currently. You can go to the developer community to suggest a feature.
You can also have a try developing a custom extension for this. You can check here for official documents about how to create extension.


If $S\subseteq M\times N$ is embedded, and $S$ and $\{p\}\times N$ intersect transversely in one point, then $\pi_M|_S$ is a diffeomorphism?

Question: I'm trying to prove the equivalence of the following statements:

Suppose $M^m$ and $N^n$ are smooth manifolds, $S\subseteq M\times N$ immersed, and $\pi_M$ and $\pi_N$ the projection maps. TFAE:
1) $S$ is the graph of a smooth function $f\colon M\to N$
2) $\pi_M|_S$ is a diffeomorphism from $S$ onto $M$,
3) For each $p\in M$, the submanifolds $S$ and $\{p\}\times N$ intersect transversely in exactly one point.

I've shown $(1)\iff (2)$, and $(2)\implies (3)$. I can include that work if needed. Right now I'm just trying to show $(3)$ implies either of the other two.
If $S$ and $\{p\}\times N$ intersect transversely in one point, then the inclusion $\iota\colon S\to M\times N$ is transverse to $\{p\}\times N$, and $\iota^{-1}(p\times N)$ is a singleton. Then this means there exists some $(p,q)\in S$ such that $(p,q)\in p\times N$, thus $\pi_M|_S$ is surjective, and it must be injective since $\iota^{-1}(p\times N)$ is a singleton.
The transversality condition implies
$$
T_{(p,q)}(p\times N)+d\iota_{(p,q)}(T_{(p,q)}S)\simeq T_{(p,q)}N+T_{(p,q)}(S)=T_{(p,q)}(M\times N)
$$
so necessarily $\dim(T_{(p,q)}(S))\geq m$, by dimension considerations.
As a bijection, it's enough to show $\pi_M|_S$ is either of constant rank, or a local diffeomorphism to prove it's a diffeomorphism. As a projection map, I feel like it should be a submersion onto $M$, and that would do the trick.
Note: This is Theorem 6.32 in John Lee's Intro to Smooth Manifolds.
Comment: Yes. Check out the proof of parametrized transversality in Guillemin and Pollack.
Comment: @CharlieFrohman Where is that? I'm scanning sections 1.6 and 2.3 on Transverality, but don't see it in either.
Comment: Oops, 1.5 not 1.6
Answer: You've got 99% of the proof already. Hint: Suppose $d\pi_M|_S$ is not surjective and think about the isomorphisms $T_{(p,q)} S+ T_{(p,q)}(\{p\} \times N) \cong T_{(p,q)}(M \times N) \cong T_p M \times T_q N$.
Click/rollover for full answer below:

 Full answer. Given $(p,q)\in S$ and $v \in T_p M$, transversality implies that $(v,0) \in T_p(M \times N)$ equals $a+b$ for some $a \in T_{(p,q)} S $ and $b \in T_{(p,q)}(\{p\} \times N)$. Since $T_{(p,q)}(\{p\} \times N)$ lies in the kernel of $d\pi_M$, $v$ lies in the image of $d(\pi_M|_S)$: $v=d\pi_M(a+b)=d\pi_M(a)+d\pi_M(b)=d(\pi_M|_S)(a)+0=0.$ So $d(\pi_M|_S)$ is surjective at $(p,q)$.
Comment: Thanks squirrel. How do you know $(v,0)\in T_{(p,q)}S$? Are you writing $(v,0)=a+b$ for $a\in T_{(p,q)}S$, $b\in T_{(p,q)}(\{p\}\times N)$, and then applying $d\pi_N$ to get $0=d\pi_N(a)+d\pi_N(b)$ or something? And then the result follows from $d(\pi_M|_S)(v,0)=v$?
Comment: My phrasing may have been unclear. How's this:  $v=d\pi_M(a+b)=(d\pi_M)|_{T_{(p,q)}S} (a)+(d \pi_M)|_{T_{(p,q)}(\{p\}\times N)}(b)=(d\pi_M)|_{T_{(p,q)}S} (a)+0=d(\pi_M|_S)(a).$
Comment: Thanks for catching my error. I realized I didn't mean "$(v,0) \in T_{(p,q)}S$" but rather $"(v,\text{[something]}) \in T_{(p,q)}S$". I edited the original post accordingly.


How can I prevent text areas from being resizable?

Question: Text areas in Drupal 7 are resizable by default.  I would like to turn this off, but when I checked a text area with Firebug, I couldn't find the CSS that was making it resizable.
How can I prevent text areas from being resized?
Answer: It's JS that makes the text areas resizable, not CSS. I think the simplest way to disable this behaviour for all textareas is to implement THEMENAME_textarea() in your theme and remove it there:
function THEMENAME_textarea($element) {
  $element['element']['#resizable'] = false ;
  return theme_textarea($element) ;
}

Comment: I found that `$element` contains an array called `element`, so this worked:

`$element['element']['#resizable'] = false;`
Comment: Hmm it should work, try `unset($element['#resizable']);` instead of `$element['#resizable'] = false;`. If you look at the code for [`theme_textarea()`](http://api.drupal.org/api/drupal/includes!form.inc/function/theme_textarea/7) that should definitely work
Comment: The same can be done with a module; in that case the module needs to implement [hook_theme_registry_alter()](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_theme_registry_alter/7) implementation. To notice the code cannot call `theme('textarea')`, or it would cause an infinite loop; it needs to call `theme_textarea()`, or the theme function that has been set from another module as replacement of `theme_textarea()`.
Comment: Thanks for the snippet, but I wasn't able to get it to work.  I should just be able to replace THEMENAME with my theme folder's name and place the code into template.php, right?  I tried this with Bartik as well but I wasn't able to get it to work.  I flushed the cache twice after updating the file.
Comment: Edited answer as per Derek Ahmedzai's comment.
Comment: Don't call theme_* functions directly.  This is a good use for a preprocess function to modify the incoming variable.
```/**
 * Implements template_preprocess_textarea().
 */
function THEME_preprocess_textarea(&$variables) {
  // Hide grippie.
  $variables['element']['#resizable'] = FALSE;
}```
Answer: If you only need CSS3 compatibility, you can use the following CSS:
textarea { resize: none; }

Or if you need to disable resize on a specific textarea, add the ID of that text area:
.edit-body-und-0-value { resize:none }

Answer: Overriding this in the theme is a last minute change, which modules won't have a chance to react on.
It's just as easy to do this via a module and a #process callback:
/**
 * Implements hook_element_info_alter()
 */
function custom_element_info_alter(&$types) {
  $types['textarea']['#process'][] = 'custom_process_textarea';
}

/**
 * A custom callback to disable "grippies" on textareas.
 */
function custom_process_textarea($element) {
  $element['#resizable'] = FALSE;
  return $element;
}

This gives modules like Wysiwyg a chance to notice that a textarea should not have a grippie, so it can avoid to attach that behavior when disabling an editor.
Answer: Implement this in your THEME. It will force the #resizable to FALSE and prevent the JS and markup from rendering.
/**
 * Implements template_preprocess_textarea().
 */
function THEME_preprocess_textarea(&$variables) {
  // Hide grippie.
  $variables['element']['#resizable'] = FALSE;
}

The accepted answer is close but theme_* functions shouldn't be called directly as they may bypass process/preprocess functions unintentionally
Answer: You can add custom inline CSS to your form, to hide the grippies:
$form['#attached']['css'][] = array(
  'data' => '.resizable-textarea .grippie { display: none; }',
  'type' => 'inline',
);

Answer: A new module called Disable Resizable Textarea was release now.

This is a simple module that add ability to override the default #resizable property of textarea fields. By default, all textareas are resizable. This module allows you to disable this feature on each field.

It is very easy to set up. Just edit the desired field and you will see an "Disable #resizable property of this textarea" option. You can also disable resizable from its summary, if the field is of type "Long text with summary".
Answer: You can do form alter of node or comment.
Check out the sample code and comments below:
$form['body'][LANGUAGE_NONE][0]['value']['#resizable'] = FALSE;

For mozilla and chrome, we can still see the issue.
place css hack.
textarea {
 resize: none;
 }

Answer: I was recently solving this problem too and found out these 2 solutions:
First one I prefer the most: Use this code in your theme's template.php and all grippies and textarea.js will disappear:
/**
 * Override of theme('textarea').
 * Deprecate misc/textarea.js in favor of using the 'resize' CSS3 property.
 */

function THEMENAME_textarea($variables) {
  $element = $variables ['element'];
  element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
  _form_set_class($element, array('form-textarea'));

  $wrapper_attributes = array(
    'class' => array('form-textarea-wrapper'),
  );

  $output = '
';
  $output .= '<textarea' . drupal_attributes($element ['#attributes']) . '>' . check_plain($element ['#value']) . '</textarea>';
  $output .= '
';
  return $output;
}

Don't forget to change THEMENAME to your theme name and flush all caches.
Second way is to install module Disable resizable textarea but I try to keep number of modules in my installations as low as possible.